You are on page 1of 108

Core Java

Abstraction:
Abstraction will Show functionality hide complexity. We can
achieve Abstraction in two ways first is by interface and second is by Abstract class. For real life example " All electronic device " viz., Mobile, Pen.

Eg:

Encapsulation:
Encapsulation is the mechanism that binds together code and data
it manipulates and keeps both safe from outside interference and misuse. Encapsulation refers to keeping all the related members (variables and methods) together in an object. Specifying members as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and refactoring efforts easy. Encapsulation is the process of binding together the method and data variable as a single entity. It keeps both the data and functionality code safe from outside world .It hide the data within class and make it available only through the method.

Benefits: The main benefit of encapsulation is the ability to modify


our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code. For real life example: A Person's mind is encapsulated, cannot be seen, one can try to read it by interacting with him. or Gems Packet Capsule Medicine

Example code:class check{ private int amount=0; public int getAmount() { return amount; } public void setAmount(int amt) { amount=amt; } } public class Mainclass { public static void main(String[]arg) { int amt = 0; check obj = new check(); obj.setAmount(200); amt = obj.getAmount(); System.out.println("your current amount is"+ amt ); } }

Inheritance:

Inheritance is the process by which one object acquires the


properties of another object. A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. However a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance

IS-A Relationship: This object is a type of that object.


Extends: With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass. Example code: public class Animal{ } public class Mammal extends Animal{} public class Reptile extends Animal{} public class Dog extends Mammal{} Now if we consider the IS-A relationship we can say:

Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal Hence : Dog IS-A Animal as well.

Implements:The implements keyword is used by classes by inherit


from interfaces. Interfaces can never be extended. Example code: public interface Animal {} public class Mammal implements Animal{} public class Dog extends Mammal{}

HAS-A Relationship: This determines whether a certain class


HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs. public class Vehicle{} public class Speed{} public class Van extends Vehicle{ private Speed sp; } This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.

Real time example: Parent and Child where child acquires all the
properties of a parent.

Benefits: With the use of inheritance the information is made


manageable in a hierarchical order.

No multiple inheritance in java?


Yes , there is no direct multiple inheritance in java as it may duplicate the methods in the child classes. But there is a possibility of having the multiple inheritance in java using the interfaces which will be of major importance in any of the Projects.

Polymorphism:
Polymorphism is the feature that allows one interface to be used for general class actions. When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to invoke based

on the actual class of the object, which may only be known at compile time.

Need of Polymorphism
Polymorphism is the association between a generalized

reference and a more specific object. The ability of a reference variable to change behavior according to what object instance it is holding. Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation. Polymorphism exists in three distinct forms in Java: Method overloading Method overriding through inheritance Method overriding through the Java interface.

Difference between method overriding and overloading?


Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.

Eight primitive Java types?


Ans: The eight primitive types are byte, char, short, int, long, float, double, and boolean.

Restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return overrides. The overriding method may not throw any exceptions that may not be thrownby the overridden method. type. The overriding method may not limit the access of the method it

Restrictions are placed on method overloading?


Two methods may not have the same name and argument list but different return types.

Casting?
Ans:There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference

Java package and how is it used?


Ans: A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.

this and super used?

this is used to refer to the current object instance. super is used to refer to the variables and methods of the super class of the current object instance

What is a stream and what are the types of Streams and classes of the Streams?A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer

Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiquity for the compiler.

Association?
Association is a relationship between two classes. In this relationship the object of one instance perform an action on behalf of the other class. The typical behaviour can be invoking the method of other class and using the member of the other class.

Aggregation?

Aggregation

has

relationship

between

two

classes.

In

this

relationship the object of one class is a member of the other class. Aggregation always insists for a direction.

What are pass by reference and pass by value?


Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed. Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. Consider the example: public void tricky(Point arg1, Point arg2) { arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; } public static void main(String [] args) { Point pnt1 = new Point(0,0); Point pnt2 = new Point(0,0); System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);

System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); System.out.println(" "); tricky(pnt1,pnt2); System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); } OutPut: X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0 The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.

Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

Final():
Final () method is used for constant declaration. A final variable act as constant, a final class is immutable A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). A final class can't be extended i.e., final class may not be sub classed.

Finally():
Handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.

Finalize()
method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Difference between declaring a variable and defining a variable?


In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g. String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

Differents Ways To Create An Object Of A Class In Java:


There are four different ways to create objects in java:

1) Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way MyObject object = new MyObject(); 2) Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way. It is also known as reflection. MyObject object = (MyObject)Class.forName("subin.rnd.MyObject"). newInstance(); 3) Using clone() The clone() can be used to create a copy of an existing object. MyObject anotherObject = new MyObject(); MyObject object = anotherObject.clone(); 4)Using object deserialization Object deserialization is nothing but creating an object from its serialized form. ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject(); 5) Using reflection in another way. this.getClass().getClassLoader().loadClass(com.amar.myobject) .newInstance();

J2SE 1.4 (february 6, 2002) merlin - assert keyword - Regular expressions - Exception chaining (allows an exception to encapsulate original lower-level exception) - Internet protocol version 6 (IPV6) support - Non-blocking nio (new input/output) - Logging API - Image i/o api for reading and writing images in formats like jpeg and png - Integrated XML parser and XSLT processor (JAXP) - Integrated security and cryptography extensions (JCE, JSSE, JAAS) - Java web start J2SE 5.0 (september 30, 2004) tiger [originally numbered 1.5] Generics Allows programmers to specify the types allowed for Collections Allows the compiler to enforce the type specifications //Before List stringList //In JDK 1.5 List<String> stringList; Varargs: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string... Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type. Allow a variable number of arguments for methods like printf() or

Method.invoke() Internally parameters are an array of Object Compiler constructs array for the call void printf(String format, Object?args); ? printf(?{0} {1} ?, ?Hello?, ?World?); printf(?PI = {0}?, 3.14159); Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. Autoboxing/unboxing: automatic conversions between primitive types (such as int, boolean) and primitive wrapper classes (such as integer). Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). - Swing: new skinnable look and feel, called synth. Enhanced for each loop: it internally extends IEnumerable interface and for-each loop is used to access each successive value in a collection of values. Here is a loop written as both a for-each loop and a basic for loop. double[] ar = {1.2, 3.0, 0.8}; int sum = 0; for (double d : ar) { // d gets successively each value in ar. sum += d; } basic for. It requires an extra iteration variable. double[] ar = {1.2, 3.0, 0.8}; int sum = 0;

for (int i = 0; i < ar.length; i++) { // i indexes each element successively. sum += ar[i]; } //Before for(Iterator i = line.iterator();i.hasNext(); ) { String word = (String)i.next(); ? } //In JDK 1.5 for(String word: line) { ? } For each in JSP: <c:forEach var="product" items="$(testattribute}"> <tr><td>${product}</td></tr> </c:forEach> - Automatic stub generation for rmi objects. - Static imports concurrency utilities in package java.util.concurrent. - Scanner class for parsing data from various input streams and buffers. - StringBuilder class (in java.lang package) - Annotations

Abstract class and methods What is an Abstract Class and what is its purpose?
A Class which doesnt provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

Can an abstract class be declared final?


Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

What is use of an abstract variable?


Variables cant be declared as abstract. Only classes and methods can be declared as abstract.

Can you create an object of an abstract class?

Not possible. Abstract classes cant be instantiated.

Can an abstract class be defined without any abstract methods?


Yes its possible. This is basically to avoid instance creation of the class.

What is an abstract method?


An abstract method is a method whose implementation is deferred to a subclass.

What does it mean that a method or class is abstract?


An abstract class cannot be instantiated. Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its super classes or it also should be declared abstract

Interface:
Why do you create interfaces, and when MUST you use one?
we create interface bcoz ... 1. To implement multiple inheritance in java. 2. To advertise the compiler that class implementing that interface is ready to deliver the functionality defined by the interface. We use the

interface in cases where the classes need to define the same method but the way of execution is different for every classes depending on their need. e.g.:- If we want to sort between two employee object on the basis of salary we have to implement the comparable interface and define the compareTo()such that it sorts on salary. but if we want to sort two manager object on age basis we again have to implement the comparable interface and define the compareTo() method but the code written inside the compareTo() method is now different from the above one . Now both implement the same interface and define the same method but still the way of execution is different .One sort on age another on salary .implementing comparable interface advertise the compiler that class implementing this interface will compare data but the basis of comparison depends upon the code written in compareTo().

Can a method inside a Interface be declared as final?


No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

Can an Interface implement another Interface?


Interfaces doesnt provide implementation hence a interface cannot implement another interface.

Can an Interface extend another Interface?


Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

Can a Class extend more than one Class?


Not possible. A Class can extend only one class but can implement any number of Interfaces.

Why is an Interface be able to extend more than one Interface but a Class cant extend more than one Class?
Basically Java doesnt allow multiple inheritances, so a Class is restricted to extend only one class. But an Interface is a pure abstraction model and doesnt have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.

Can an Interface be final?


Not possible. Doing so so will result in compilation error.

Can a class be defined inside an Interface?


Yes its possible.

Can an Interface be defined inside a class?


Yes its possible.

Can i declare variables inside Interface? If yes then how?


Variables inside an Interface is only constants..i mean you can say something and convenience. like public static final int=20. Generally, Constants are used for readability

Eg: e.g. interface UsefulAction { public static int ACTION_SUCCESS = 1; public static int ACTION_FAILURE = 0; public int doAction(); } Any class implementing the Useful Action interface must implement the doAction() method which returns an int value and one could reasonably expect that value to correspond one of the constants, so that the calling code can be written thus. int result = doAction(); if (result == ACTION_SUCCESS) { // continue processing } else { // handle the failure } Both yes and no: yes, you can declare interface fields but they will automatically receive "public", "static" and "final" modifiers so they will be constants, so no, there will be no variables. But you surely can declare some Singleton as an Interface static final field which will held some variables inside of it. That's how you can obtain static fields of an Interface. However it is a bad practice and should not be used since Interface declares how the particular object will be used while mutable field is a part of implementation. And for partial implementation abstract classes are preferred

What is a Marker Interface?


An Interface which doesnt have any declaration inside but still enforces a mechanism.

An interface which has no methods is called marker interface. If we implement that interface jvm will provide ability to the object Eg is Serializable. When a class implements this interface then only we can serialize the object. i.e we can save in the file. In other words any class which implements serializable can be serialized which is the additional feature when compared with an ordianary object

When can an object reference be cast to an interface reference?


An object reference be cast to an interface reference when the object implements the referenced interface.

What is fully abstract class?


Ans) An abstract class which has all methods as abstract and all fields are public static final.

Difference between Abstract and interface:


1) An abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods. 2) An interface can extend one or more other interfaces. An interface cannot extend anything but another interface. interface cannot implement another interface or class. interface must be declared with the keyword interface. An An

Transient variable?
These variables are not included in the process of serialization and are not the part of the objects serialized state. Does the order in which the value of the transient variables and the state of the object using the defaultWriteObject() method are saved during serialization matter? Yes. As while restoring the objects state the transient variables and the serializable variables that are stored must be restored in the same order in which they were saved.

About Main()
Why is main() method static?
To access the static method the object of the class is not needed. The method can be access directly with the help of ClassName. So when a program is started the jvm search for the class with main method and calls it without creating an object of the class.

What is the return type of the main method?


Main method doesnt return anything hence declared void.

Why the main method is declared static?


Main method is called by the JVM even before the instantiation of the class hence it is declared as static.

What is the argument of main method?


Main method accepts an array of String object as argument.

Can a main method be overloaded?


Yes. You can have any number of main methods with different method signature and implementation in the class.

Can a main method be declared final?


Yes. Any inheriting class will not be able to have its own default main method.

What is a native method?


A native method is a method that is implemented in a language other than Java.

Why not static public void main?


Actually you can have a static public void main. The java compiler or the JVM does not complain about the order in which the keywords are placed for the main method as long as all of them are there.

What happens if you remove public from public static void main?
Until you run the program nothing happens. You would be able to happily compile your program, but when you try to execute it, you will get the below exception. Main Method Not Public

Why public static void main?


public - so that any class can access it static - so that the JVM can access it without the need to instantiate the class object void - because it does not return anything main - this is just the...

What is public static void main in java?


The method of an class that can is triggered when starting a Java application e.g. by running the command: "java MyProgram" Answer Public is an Access Specifier, static is a keyword which so that the JVM can access it without the need to instantiate the class object...

Should a main method be compulsorily declared in all java


class is a java application.

classes?

No not required. main method should be defined only if the source

Can you have an inner class inside a method and what variables can you access?Yes, we can have an inner class inside a method and final variables can be accessed.

What will be the value of transient variable after deserialization?

Ans) Its default value. E.g. if the transient variable in question is an int, its value after deserialization will be zero. Explanation

The transient variable is not saved as the part of the state of the serailized variable, its value after deserialization is its default value.
public class TestTransientVal implements Serializable{ private static final long serialVersionUID = -22L; private String name; transient private int age; TestTransientVal(int age, String name) { this.age = age; this.name = name; } public static void main(String [] args) { TestTransientVal c = new TestTransientVal(1,"ONE"); System.out.println("Before serialization: - " + c.name + " "+ c.age); try { FileOutputStream FileOutputStream("testTransients.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(c); os.close(); } catch (Exception e) { e.printStackTrace(); } try { FileInputStream fis = new FileInputStream("testTransients.ser"); ObjectInputStream ois = new ObjectInputStream(fis); c = (TestTransientVal) ois.readObject(); fs = new

ois.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("After de-serialization:- " + c.name + " "+ c.age); }} Result of executing above piece of code Before serialization: - Value of non-transient variable ONE Value of transient variable 1 After de-serialization:- Value of non-transient variable ONE Value of transient variable 0

About String
Differences between String and StringBuffer in Java
String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method.

Difference between StringBuilder and StringBuffer in Java


StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also

applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilders vs String.

Summary
1) String is immutable while StringBuffer and StringBuilder is mutable object. 2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer. 3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder. 4) Use String if you require immutability, use Stringbuffer in java if you need mutable + threadsafety and use StringBuilder in Java if you require mutable + without thread-safety.

Difference

between

String

and

StringBuffer/StringBuilder?
Well, the most important difference between String and

StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable. By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is If String is immutable then how am I able to change the contents of the object whenever I wish to? . Well, to be precise its not the same String object that reflects the changes you do. Internally a new String object is created to do the changes. So suppose you declare a String object: String myString = Hello;

Next, you want to append Guest to the same String. What do you do? myString = myString + Guest; When you print the contents of myString the output will be Hello Guest. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String. Now isnt that a performance issue? Yes, it definitely is.

How do you make your string operations efficient?


By using StringBuffer or StringBuilder.

How would that help?


Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.

What

is

difference

between

stringbuffer

and

stringbuilder?
StringBuffer and StringBuilder have the same methods with one difference and thats of synchronization. StringBuffer is

synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isnt thread safe). So, if you arent going to use threading then use the StringBuilder class as itll be more efficient than StringBuffer due to the absence of synchronization. Incase you do not know Heres how you use StringBuilder A simple Example to demonstrate that String object is Immutable Incase you still have any doubts regarding String or StringBuilder then do leave a comment. Ill be more than eager to help you out. The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer. Criteria to choose among StringBuffer and StringBuilder 1)If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous Mutable string means we can append to that string. example StringBuffer object is mutable string. String is immutable object.. when we declre String="abc"; a string object abc with fixed length is created. We cant add anything to it .If we do java simply creates a new object.

How to compare Stringbuffer objects?

Stringbuffer can be converted to string objects and compared using compare method.. String objects are immutable. Well let me explain taking an example:Look at the code below along with the comments:String test = "Java"; // Create a string object "java" and assign a reference 'test ' to it.String test2 = test; //create another reference test2. Now both the references point to the //same string object i.e. "java"test = test + "world"; //this statement creates another string object i.e. "java world" and now the reference test refers to this object and not to "java" implying that string objects are immutable. The previous object "java" is then garbage collected if there is no other refrence to it. Right now test2 points to it, so it isnt garbage collected.System.out.println("test "+test);//Having understood the above, u can make out the output of this line. it will be "java world"System.out.println("test2 "+test2);//out put of this will be "java".Hope this makes it clear.

I have one string like "Happy Birthday to you". But i want to print it like "you to Birthday Happy". Pls tell me the program on java?
import java.util.*; class ReverseString1 { public static void main(String[]arg) { String input ="Happy Birthday To You"; Stack stack = new Stack(); StringTokenizer strTok = new StringTokenizer(input); while(strTok.hasMoreTokens()){ stack.push(strTok.nextElement()); } StringBuffer revStr = new StringBuffer(); while(!stack.empty()){

revStr.append(stack.pop()); revStr.append(" "); } // System.out.println("original String:"+input); System.out.println("\nReverse String : " + revStr); }}

Or
String str =new String("Happy Birthday to you"); StringBuffer sb = new StringBuffer("str"); StringBuffer sb1 = sb.reverse(); System.out.print(sb1);

About Static
Static class ?
A class cannot be declared static. But a class can be said a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only

Static Keyword
Static keyword can be used with the variables and methods but not with the class but there are static class. Anything declared as static is related to class and not objects.

Static variable :
Multiples objects of a class shares the same instance of a static variable.Consider the example: public class Counter{ private static int count=0; private int nonStaticcount=0; public void incrementCounter(){

count++; nonStaticcount++; } public int getCount(){ return count; } public int getNonStaticcount(){ return nonStaticcount; } public static void main(String args[]){ Counter countObj1 = new Counter(); Counter countObj2 = new Counter(); countObj1.incrementCounter(); countObj1.incrementCounter(); System.out.println("Static count for Obj1: "+countObj1.getCount()); System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount()); System.out.println("Static count for Obj2: "+countObj2.getCount()) System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount()) } Output Static count for Obj1: 2 NonStatic count for Obj1: 2 Static count for Obj2: 2 NonStatic count for Obj2: 0

In the above program obj1 and obj2 share the same instance of static variable count hence if the value is incremented by one object , the incremented value will be reflected across the other objects.

Static method?
A method defined as static is called static method. A static method can be accessed without creating the objects. Just by using the Class name the method can be accessed. Static method can only access static variables and not local or global non-static variables. For eg: public class Test{ public static void printMe(){ System.out.println("Hello World"); } } public class MainClass{ public static void main(String args[]){ Test.printMe() } } OutPut: Hello World Also static method can call only static methods and not non static methods. But non-static methods can call static mehtods.

Can static block throw exception?


Yes, static block can throw only Runtime exception or can use a trycatch block to catch checked exception. Typically scenario will be if JDBC connection is created in static block

and it fails then exception can be caught, logged and application can exit. If System.exit () is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader

Difference between static methods and instance methods?


instance method belongs to the instance of a class therefore it requires an instance before it can be invoked, whereas static method belongs to the class itself and not to any class instance so it doesnt need an instance to be invoked. Instance methods use dynamic (late) binding, whereas static methods use static (early) binding. When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to invoke based on the actual class of the object, which may only be known at compile time.

Dynamic binding and static binding?


Method invocation: The Java programming language provides two basic kinds of methods: instance methods and class (or static) methods. The difference is: 1. Instance methods require an instance before they can be invoked, whereas class methods do not. 2. Instance methods use dynamic (late) binding, whereas class methods use static (early) binding. When the Java virtual machine invokes a class method, it selects the method to invoke based on the type of the object reference, which is always known at compile-time. On the other hand, when the virtual

machine invokes an instance method, it selects the method to invoke based on the actual class of the object, which may only be known at run time.

Difference between instanceof and isinstance(Object obj)?


instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class. if (obj instanceof MyType) { ... }else if (MyType.class.isInstance(obj)) { ... } instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.

Difference between equals() and ==?


== operator is used to compare the references of the objects. public bollean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overriden like for String class. equals() method can be used to compare the values of two objects. String str1 = "MyName"; String str2 = "MyName"; String str3 = str2; if(str1 == str2){ System.out.println("Objects are equal") }

else{ System.out.println("Objects are not equal") } if(str1.equals(str2)){ System.out.println("Objects are equal") }else{ System.out.println("Objects are not equal") } Output: Objects are not equal Objects are equal _______________ String str2 = "MyName"; String str3 = str2; if(str2 == str3){ System.out.println("Objects are equal") }else{ System.out.println("Objects are not equal") } if(str3.equals(str2)){ System.out.println("Objects are equal") }else{ System.out.println("Objects are not equal") } OutPut: Objects are equal Objects are equal.

Can an abstract class have a static method?


Yes an abstract class have a static method and it can be accessed by any other class(even not a concrete class).

Why static methods cannot access non static variables or methods?


A static method cannot access non static variables or methods because static methods dont need the object to be accessed. So if a static method has non static variables or non static methods which has instantiated variables they will no be intialized since the object is not created and this could result in an error.

Difference between Static {} block and init {} block?


The static block is loaded when the class is loaded by the JVM for the 1st time only whereas init {} block is loaded every time class is loaded. Also first the static block is loaded then the init block. public class LoadingBlocks { static{ System.out.println("Inside static"); } { System.out.println("Inside init"); } public static void main(String args[]){ new LoadingBlocks(); new LoadingBlocks(); new LoadingBlocks(); }

} Output: Inside static Inside init Inside init Inside init.

Does

static class'

nested

class

have

access or

to

the

enclosing variables?
No.

non-static

methods

instance

If you compile a file containing inner class how many .class files are created and what are all of them accessible in usual way?
If a inner class enclosed with an outer class is compiled then one .class file for each inner class an a .class file for the outer class is created. e.g. class EnclosingOuter { class Inner{ } } If you compile the above code with command % javac EnclosingOuter.java Two files EnclosingOuter.class EnclosingOuter$Inner.class will be created. Though a separate inner class file is generated, the

inner class file is not accessible in the usual way like, % java EnclosingOuter$Inner.

How to access the inner class from code within the outer class?
The inner class is instantiated only through the outer class instance. class EnclosingOuter { private int noInnerClass = 1; public void getNoOfInnerClasses(){ Inner in = new Inner(); System.out.println(No } class Inner{ public int getNoOfClassesFromOuter(){ return noInnerClass; } } Here the method getNoOfInnerClasses() is called on the outer classs instance through this outer class instance the inner class instance in is created. Of Inner classes is : + in.getNoOfClassesFromOuter());

How to create an inner class instance from outside the outer class instance code?
To create an instance of the inner class you must have the instance class Inner{ } } To create the instance of inner class from class other than the enclosing class. of its enclosing class. e.g. class EnclosingOuter {

1) class OtherThanOuter{ EnclosingOuter out = new EnclosingOuter(); EnclosingOuter.Inner in = out.new Inner(); } 2) class OtherThanOuter{ EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }

Are the static variables saved as the part of serialization?


No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.

Immutable class?
Immutable class is a class which once created, its contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class.

Create an immutable class?


To create an immutable class following steps should be followed: 1. Create a final class. 2. Set the values of properties using constructor only. 3. Make the properties of the class final and private 4. Do not provide any setters for these properties. 5. If the instance fields include references to mutable objects, don't allow those objects to be changed: 1. Don't provide methods that modify the mutable objects.

2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods. E.g. public final class FinalPersonClass { private final String name; private final int age; public FinalPersonClass(final String name, final int age) { super(); this.name = name; this.age = age; } public int getAge() { return age; } public String getName() { return name; }

Immutable objects:
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer. Immutable objects greatly simplify your program, since they :

are simple to construct, test, and use

are automatically thread-safe and have no synchronization issues

do not need a copy constructor do not need an implementation of clone allow hashCode to use lazy initialization, and to cache its return value

do not need to be copied defensively when used as a field make good Map keys and Set elements (these objects must not change state while in the collection)

have their class invariant established once upon construction, and it never needs to be checked again

always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state

Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.

Immutable objects are automatically thread-safe true/false?


True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/threadsafe.

Which classes in java are immutable?

All wrapper classes in java.lang are immutable String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger.

Advantages of immutability?
Ans) The advantages are: 1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided. 2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state. 3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction. 4) The best use of the immutable objects is as the keys of a map

How to make sure that Childclass method actually overrides the method of the superclass?
Ans) The @Override annotation can be added to the javadoc for the new method. If you accidently miss an argument or capitalize the method name wrong, the compiler will generate a compile-time error.

Explain

re-entrant,

recursive

and

idempotent

methods/functions?
A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each other. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from

many sorts of algorithms. Allrecursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.

Can a private variable or method of a class can be accessed?


Yes its possible using reflection.

When an obj is passed through a function, one can set the properties but cannot set a new memory location?
Ans) It is because when u pass an object the address value is passed and stored in some new address . like if address 1234 is passed , it is stored in 4567 location. So if u change in the value of an object it will take the address from 4567 and do 1234.setXXX(). If u set the object to null it will set 4567=null.

About Threads Related

Thread?
In Java, thread means two different things: An instance of class java.lang.Thread. A thread of execution: An instance of Thread is justan object.

Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a lightweight process) that has its own call stack. In Java, there is one thread per call stackor, to think of it in reverse, one call stack per thread. Even if you dont create any new threads in your program, threads are back there running. The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread. If you looked at the main call stack (and you can, any time you get a stack trace from something that happens after main begins, but not within another thread), youd see that main() is the first method on the stack the method at the bottom. But as soon as you create a new thread, a new stack materializes and methods called from that thread run in a call stack thats separate from the main() call stack.

What is difference between thread and process?


Differences between threads and processes are:1. Threads share the address space of the process that created it; processes have their own address. 2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.

3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes. 4. Threads have almost no overhead; processes have considerable overhead. 5. New threads are easily created; new processes require duplication of the parent process. 6. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes. 7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process do not affect child processes.

What are the advantages or usage of threads?


Threads support concurrent operations. For example, Multiple requests by a client on a server can be handled as an individual be handled in the client background without disturbing thread. foreground Long computations or high-latency disk and network operations can computations or screen updates. Threads often result in simpler programs. In sequential programming, updating multiple displays normally requires a big while-loop that performs small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler. In Java, each view can be assigned a thread to provide continuous updates.

Programs that need to respond to user-initiated events can set up service routines to handle the events without having to insert code in the main routine to look for these events. Threads provide a high degree of control. Imagine launching a complex computation that occasionally takes longer than is satisfactory. A watchdog thread can be activated that will kill the computation if it becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential programs must muddy the computation with termination code, whereas, a Java program can use thread control to non-intrusively supervise any operation. Threaded applications exploit parallelism. A computer with multiple CPUs can literally execute multiple threads on different functional units without having to simulating multi-tasking (time sharing). On some computers, one CPU handles the display while another handles computations or database accesses, thus, providing extremely fast user interface response times.

What are the two ways of creating thread?


There are two ways to create a new thread. 1) Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. e.g. public class NewThread extends Thread{ public void run()

{ //the code that has to be executed in a separate new thread goes here } public static void main(String [] args) { NewThread c = new NewThread(); c.start(); } } 2) Implements the Runnable interface. The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class public class NewThread implements Runnable{ public void run(){ // the code that has to be executed in a separate new thread goes here } public static void main(String [] args){ NewThread c = new NewThread(); Thread t = new Thread(c); t.start(); } }

What are the different states of a threads lifecycle?


The different states of threads are as follows: 1) New When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive. 2) Runnable The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive. 3) Running When the thread scheduler picks up the thread from the Runnable threads pool, the thread starts running and the thread is said to be in Running state. 4) Waiting/Blocked/Sleeping In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. 5) Dead When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

What is use of synchronized keyword?


Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same

method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g. public void synchronized method(){} public void synchronized staticmethod(){} public void myMethod(){ synchronized (this) { // synchronized keyword on block of code } }

What

is

the

difference

when

the

synchronized

keyword is applied to a static method or to a non static method?


When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class dont interfere with each other. It means, a thread accessing a synch non static method, then the other thread can access the synch static method at the same time but cant access the synch non static method.

What is a volatile keyword?


In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.

What is the difference between yield() and sleep()?


yield() allows the current thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority. sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesnt release the lock.

What is the difference between wait() and sleep()?


Both wait() and sleep() are the methods of Object class. sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesnt release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.

What is difference between notify() and notfiyAll()?

notify( ) wakes up the first thread that called wait( ) on the same object.

notifyAll( ) wakes up all the threads that called wait( ) on the same object. highest priority thread will run first. The

What happens if a start method is not invoked and the run method is directly invoked?
If a thread has been instantiated but not started its said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.

What happens when start() is called?


A new thread of execution with a new call stack starts. The state of thread changes from new to Runnable. When the thread gets chance to execute its target run() method starts to run.

If code is running a thread, creates a new thread what will be the initial priority of the newly created thread?
When a code running in a thread creates a new thread object , the priority of the new thread is set equal to the priority of the thread which has created it.

When jvm starts up, which thread will be started up first?


When jvm starts up the thread executing main method is started.

What are the daemon threads?


Daemon thread are service provider threads run in the

background,these not used to run the application code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to complete their execution if all user threads have completed their execution. To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a user thread use isDaemon() method. Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are done with their execution.

What all constructors are present in the Thread class?


Thread() Thread(Runnable target) Thread(Runnable target, String name) Thread(String name)

Can the variables or classes be Synchronized?


No. Only methods can be synchronized.

How many locks does an object have?


Each object has only one lock.

Can

class

have

both

Synchronized

and

non-

synchronized methods?
Yes a class can have both synchronized and non-synchronized methods.

If a class has a synchronised method and nonsynchronised method, can multiple threads execute the non-synchronised methods?
Yes. If a class has a synchronised and non-synchronised methods, multiple threads can access the non-synchronised methods.

If a thread goes to sleep does it hold the lock?


Yes when a thread goes to sleep it does not release the lock.

Can a thread hold multiple locks at the same time?


Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into the synchronized method / block, it may call another synchronized method and acquire a lock on another object.

Can a thread call multiple synchronized methods on the object of which it hold the lock?
Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that same object using the lock that it already holds.

Can static methods be synchronized?


Yes. As static methods are class methods and have only one copy of static data for the class, only one lock for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on this instance is used to synchronize the static methods.

Can two threads call two different static synchronized methods of the same class?
No. The static synchronized methods of the same class always block each other as only one lock per class exists. So no two static synchronized methods can execute at the same time.

Does a static synchronized method block a non-static synchronized method?


No As the thread executing the static synchronized method holds a lock on the class and the thread executing the non-satic synchronized method holds the lock on the object on which the method has been called, these two locks are different and these threads do not block each other.

Once a thread has been started can it be started again?


No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been already started once an IllegalThreadStateException is thrown, which is a runtime exception. A thread in runnable state or a dead thread can not be restarted.

When does deadlock occur and how to avoid it?


When a locked object tries to access a locked object which is trying to access the first locked object. When the threads are waiting for each other to release the lock on a particular object, deadlock occurs.

What is a better way of creating multithreaded application? Extending Thread class or implementing Runnable?
If a class is made to extend the thread class to have a multithreaded application then this subclass of Thread cant extend any other class and the required application will have to be added to this class as it cant be inherited from any other class. If a class is made to implement Runnable interface, then the class can extend other class or implement other interface.

What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and

these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.

Can the start() method of the Thread class be overridden? If yes should it be overridden?
Yes the start() method can be overridden. But it should not be overridden as its implementation in thread class has the code to create a new executable thread and is specialised.

What are the methods of the thread class used to schedule the threads?
public static void sleep(long millis) throws InterruptedException public static void yield() public final void join() throws InterruptedException public final void setPriority(int priority) public final void wait() throws InterruptedException public final void notify() public final void notifyAll()

Which thread related methods are available in Object class?


public final void wait() throws Interrupted exception

public final void notify() public final void notifyAll()

Which thread related methods are available in Thread class?


public static void sleep(long millis) throws Interrupted exception public static void yield() public final void join() throws Interrupted exception public final void setPriority(int priority) public void start() public void interrupt() public final void join() public void run() public void resume()

List the methods which when called the thread does not release the locks held?
notify() join() sleep() yield()

List the methods which when called on the object the thread releases the locks held on that object?
wait()

Does each thread has its own thread stack?


Yes each thread has its own call stack. For eg Thread t1 = new Thread(); Thread t2 = new Thread(); Thread t3 = t1; In the above example t1 and t3 will have the same stack and t2 will have its own independent stack.

What is thread starvation?


In a multi-threaded environment thread starvation occurs if a low priority thread is not able to run or get a lock on the resoruce because of presence of many high priority threads. This is mainly possible by setting thread priorities inappropriately.

What is threadLocal variable?


ThreadLocal is a class. If a variable is declared as threadLocal then each thread will have a its own copy of variable and would not interfere with the others thread copy. Typical scenario to use this would be giving JDBC connection to each thread so that there is no conflict. ThreadLocal class by JAVA API

public class ThreadLocal { public Object get(); public void set(Object newValue); public Object initialValue(); } Implementation of ThreadLocal public class ConnectionDispenser { private static class ThreadLocalConnection extends ThreadLocal { public Object initialValue() { return DriverManager.getConnection(ConfigurationSingleton.getDbUrl()); } } private static ThreadLocalConnection conn = new

ThreadLocalConnection(); public static Connection getConnection() { return (Connection) conn.get(); } }

Whats the difference between Thread and Runnable types?


A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it. The Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation.

How does the run() method in Runnable work?


It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects.

Why not override Thread to make a Runnable?


There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot

extend any other type, so application-specific code would have to be added to it rather than inherited. Separating the Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed.

When could I adapt the Thread class though?


It is always best to implement a Runnable type rather than extend a Thread. On that basis, the extension of the Thread class should only be considered in exceptional circumstances when the application is very simple, composed of few classes, where the interaction of threads is minimal and requires only minimal control over thread execution.

Whats the difference between a threads start() and run() methods?


The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns. The Thread class run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the threads run() method executes the run() method of the Runnable object in the new thread instead. Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the

start() method, but in the latter case the code is actually executed in a new thread.

Can I implement my own start() method?


The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method.

When you will synchronize a piece of your code?When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.

What is deadlock?When two threads are waiting each other and cant precede the program is said to be deadlock.

When a thread cannot acquire a lock on an object?


If a thread attempts to execute a synchronized method or

synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

If all methods are synchronized, is a class thread safe?


Even if all the methods of a class are synchronized, it may still be vulnerable to thread safety problems if it exposes non-final fields or its methods return mutable objects that could be manipulated by multiple

threads. Non-final fields should be declared private and encapsulated with synchronization. Rather than return references to internal object fields, create an independent copy that has no relation to the original, known as a deep copy. A deep copy of an object duplicates the content and state of the original object and all its constituent fields in such a way that none of its properties refer to instances in the original at any level. These measures will help prevent uncontrolled access to the internal state of objects, but you must also ensure synchronization techniques are applied in a robust, consistent manner that will not cause deadlock or race conditions. It is generally better to use synchronized blocks than synchronized methods for performance reasons. Limit the extent of synchronized blocks and ensure they all use the same object monitor.

How do I create a Runnable with inheritance?


To introduce a Runnable type to an existing class hierarchy, you need to create a sub-class that declares that it implements the Runnable interface, and provide a run method to fulfil the interface. This combination of interface and inheritance means that runnable implementations can be very minor extensions of existing classes

What is Serialization?
Serializable is a marker interface. When an object has to be transferred over a network ( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface. Implementing this interface will allow the object converted into bytestream and transfer over a network.

Need of Serialization?

To send state of one or more objects state over the network through a socket. To save the state of an object in a file. An objects state needs to be manipulated as a stream of bytes.

Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

Do we need to implement any method of Serializable interface to make an object serializable?


No. Serializable is a Marker Interface. It does not have any methods.

To serialize an array or a collection all the members of it must be serializable. True /False?
True

If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from super class after deserialization?
The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run. E.g.

public class ParentNonSerializable { int noOfWheels; ParentNonSerializable(){ this.noOfWheels = 4; } }

public class ChildSerializable extends ParentNonSerializable implements Serializable { private static final long serialVersionUID = 1L; String color; ChildSerializable() { this.noOfWheels = 8; this.color = "blue"; } } public class SubSerialSuperNotSerial { public static void main(String [] args) { ChildSerializable c = new ChildSerializable(); System.out.println("Before : - " + c.noOfWheels + " "+ c.color); try { FileOutputStream fs = new FileOutputStream("superNotSerail.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(c); os.close();

} catch (Exception e) { e.printStackTrace(); } try { FileInputStream fis = new FileInputStream("superNotSerail.ser"); ObjectInputStream ois = new ObjectInputStream(fis); c = (ChildSerializable) ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("After :- " + c.noOfWheels + " "+ c.color); }} Result on executing above code Before : - 8 blue After :- 4 blue The instance variable noOfWheels is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.

Use of serialVersionUID?
During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the

secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid. So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown. Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

Add fields Change a field from static to non-static Change a field from transient to non-transient Add classes to the object tree

List of incompatible changes:


Delete fields Change class hierarchy Change non-static to static Change non-transient to transient Change type of a primitive field

So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used . The only way to get rid of the exception is to recompile and deploy the application If we explicitly metion the suid using the statement: private final static long serialVersionUID = <integer value> again.

then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Are

the

static

variables

saved

as

the

part

of

serialization?
No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object Result on executing above code Before : - 8 blue After :- 4 blue The instance variable noOfWheels is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.

About Garbage Collection:


Which part of the memory is involved in Garbage Collection? Stack or Heap?
Heap

What is responsibility of Garbage Collector?


Garbage collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects. It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run.

Is garbage collector a dameon thread?


Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM. The thread stops when all non-dameon threads stop.

Garbage Collector is controlled by whom?


The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low, but this behavior of jvm cant be guaranteed. One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by jvm.

When does an object become eligible for garbage collection?


An object becomes eligible for Garbage Collection when no live thread can access it.

What are the different ways to make an object eligible for Garbage Collection when it is no longer needed?

1. Set all available object references to null once the purpose of creating the object is served : public class GarbageCollnTest1 { public static void main (String [] args){ String str = "Set the object ref to null"; //String object referenced by variable str is not eligible for GC yet str = null; /*String object referenced by variable str becomes eligible for GC */ } } 2. Make the reference variable to refer to another object : Decouple the reference variable from the object and set it refer to another object, so the object which it was referring to before reassigning is eligible for Garbage Collection. publc class GarbageCollnTest2 { public static void main(String [] args){ String str1 = "Garbage collected after use"; String str2 = "Another String"; System.out.println(str1); //String object referred by str1 is not eligible for GC yet str1 = str2; /* Now the str1 variable referes to the String object "Another String" and the object "Garbage collected after use" is not referred by any variable and hence is eligible for GC */

} } 3) Creating Islands of Isolation : If you have two instance reference variables which are referring to the instances of the same class, and these two reference variables refer to each other and the objects referred by these reference variables do not have any other valid reference then these two objects are said to form an Island of Isolation and are eligible for Garbage Collection. public class GCTest3 { GCTest3 g; public static void main(String [] str){ GCTest3 gc1 = new GCTest3(); GCTest3 gc2 = new GCTest3(); gc1.g = gc2; //gc1 refers to gc2 gc2.g = gc1; //gc2 refers to gc1 gc1 = null; gc2 = null; //gc1 and gc2 refer to each other and have no other valid //references //gc1 and gc2 form Island of Isolation //gc1 and gc2 are eligible for Garbage collection here } }

Can the Garbage Collection be forced by any means?

No. The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.

How can the Garbage Collection be requested?


There are two ways in which we can request the jvm to execute the Garbage Collection. 1) The methods to perform the garbage collections are present in the Runtime class provided by java. The Runtime class is a Singleton for each java main program. The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked using this instance of Runtime to request the garbage collection. 2) Call the System class System.gc() method which will request the jvm to perform GC.

If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some point the same object becomes eligible for Garbage collection, will the finalize() method be called again?
No

How many times does the garbage collector calls the finalize() method for an object?
Only once.

What are different ways to call garbage collector?


Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().

About Exceptions
Difference between Error and Exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you cant repair them at runtime. Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an

exception (probably by giving user a feedback for entering proper values etc.)

Explain the exception hierarchy in java.


The hierarchy is as follows: Throwable is a parent class off all Exception classes. They are two types of Exceptions: Checked exceptions and Unchecked Exceptions. Both type of exceptions extends Exception class.

Checked exceptions?
Checked exception is those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions. Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch block. It is a subClass of Exception. Example: IOException.

Runtime exceptions or Unchecked?


Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time. Unchecked exceptions represent problems that are the result of a programming problem.

Different ways to handle exceptions?


1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. 2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions. In the first approach as a programmer of the method, you yourselves are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not

the responsibility of the method to deal with its own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

Throw keyword?
Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application. The exception thrown should be subclass of Throwable. public void parent(){ try{ child(); }catch(MyCustomException e){ } } public void child{ String iAmMandatory=null; if(iAmMandatory == null){ throw (new MyCustomException("Throwing exception using throw keyword"); } }

Throws keyword?

If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration. public void parent(){ try{ child(); }catch(MyCustomException e){ } } public void child throws MyCustomException{ //put some logic so that the exception occurs. }

How to Create custom Exception?


To create you own exception extend the Exception class or any of its subclasses. e.g. 1 class New1Exception extends Exception { } // this will create Checked Exception 2 class NewException extends IOExcpetion { } // this will create Checked exception 3 class NewException extends NullPonterExcpetion { } // this will create UnChecked exception

When to make a custom checked Exception or custom unchecked Exception?


If an application can reasonably be expected to recover from an exception, make it a checked exception. If an application cannot do

anything to recover from the exception, make it an unchecked exception.

Once the control switches to the catch block does it return back to the try block to execute the balance code?
No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).

Where is the clean up code like release of resources is put in try-catch-finally block and why?
The code is put in a finally block because irrespective of try or catch block execution the control will flow to finally block. Typically finally block contains release of connections, closing of result set etc.

Is it valid to have a try block without catch or finally?


NO. This will result in a compilation error. The try block must be followed by a catch or a finally block. It is legal to omit the either catch or the finally block but not both. e.g. The following code is illegal. try{ int i =0; } int a = 2; System.out.println(a = +a);

Is it valid to place some code in between try the catch/finally block that follows it?
No. There should not be any line of code present between the try and the catch/finally block. e.g. The following code is wrong. try{} String str = ABC; System.out.println(str = +str); catch(Exception e){}

What happens if the exception is never caught and throws down the method stack?
If the exception is not caught by any of the method in the methods stack till you get to the main() method, the main method throws that exception and the JVM halts its execution.

How do you get the descriptive information about the Exception occurred during the program execution?
All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.

Can you catch more than one exceptions in a single catch block?

Ans)Yes. If the exception class specified in the catch clause has subclasses, any exception object that is a subclass of the specified Exception class will be caught by that single catch block. E.g.. try { // Some code here that can throw an IOException } catch (IOException e) { e.printStackTrace(); } The catch block above will catch IOException and all its subclasses e.g. FileNotFoundException etc.

Exception matching?
Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called exception matching.

What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?

Compilation fails. The catch block for handling the most specific exceptions must always be placed above the catch block written to handle the more general exceptions. e.g. The code below will not compile. 1 try { // code that can throw IOException or its subtypes } catch (IOException e) { // handles IOExceptions and its subtypes } catch (FileNotFoundException ex) { // handle FileNotFoundException only } The code below will compile successfully :try { // code that can throw IOException or its subtypes } catch (FileNotFoundException ex) { // handles IOExceptions and its subtypes } catch (IOException e){ // handle FileNotFoundException only }

Is an empty catch block legal?


Yes you can leave the catch block without writing any actual code to handle the exception caught. e.g. The code below is legal but not appropriate, as in this case you will nt get any information about the exception thrown.

try{ //code that may throw the FileNotFoundException }catch(FileNotFound eFnf){ //no code to handle the FileNotFound exception }

Can a catch block throw the exception caught by itself?


Yes. This is called rethrowing of the exception by catch block. e.g. the catch block below catches the FileNotFound exception and rethrows it again. void checkEx() throws FileNotFoundException { try{ //code that may throw the FileNotFoundException }catch(FileNotFound eFnf){ throw FileNotFound(); }}

NoClassDefFounderror v/s ClassNotFoundException:


Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next loader. time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Class

A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. Consider if NoClassDefFoundError occurs which is something like java.lang.NoClassDefFoundError src/com/TestClass does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.

StackOverflowError?
The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM. e.g. void swap(){ swap(); }

What happens if an uncaught exception is thrown from during the execution of the finalize() method of an object?
The exception will be ignored and the garbage collection (finalization) of that object terminates

About Collections
What are the classes implementing List interface?
There are three classes that implement List interface: 1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe. 2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block. 3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

Arraylist
arraylist-in-java-tutorial.html)

v/s

Vector

(http://javarevisited.blogspot.com/2011/05/example-of-

Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe. Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Arraylist are not synchronized but if you want to make it synchronize then you can do like this List list = Collections.synchronizedList(new ArrayList(...)); While are synchronized. Default increment capacity of Arraylist is 50% while that of Vector is 100% i.e. Suppose you have a Arraylist of 10 objects & if 11th object is added then size of Arraylist will be increased to 15 but in the case of Vector it would be 20. Vectors

Arrays v/s ArrayList ?


Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as : 1. int [] intArray= new int[6]; 2. intArray[7] // will give ArraysOutOfBoundException. Also the size of array cannot be incremented or decremented. But with arrayList the size is variable. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime. List list = new ArrayList(); list.add(1); list.add(3); list.remove(0) // will remove the element from the 1st location. ArrayList is one dimensional but array can be multidimensional. int[][][] intArray= new int[3][2][1]; // 3 dimensional array To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But

arrayList is all about dynamic creation and there is no wastage of memory

Use of ArrayList or LinkedList ?


Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.

ArrayList v/s LinkedList ?


Arraylist is Indexed where as linked list is not. If you need to support random access, without inserting or removing elements from any place to other than the end, then ArrayList offers you the optimal collection, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. Note that these implementation is not synchronized. If multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set: List list = Collections.synchronizedList(new LinkedList(...)); List list = Collections.synchronizedList(new ArrayList(...)); In List, ArrayList is faster because it is unsynchronized while vector is synchronized. In Map, HashMap is faster because it is unsynchronized while Hahtable is synchronized.

If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.

If accessing through iterator is slow then why do we need it and when to use it?
For loop does not allow the updation in the array (add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Can Arraylist be synchronized without using Vector?


Arraylist can be synchronized using: Collection.synchronizedList(List list) Other collections can be synchronized: Collection.synchronizedMap(Map map) Collection.synchronizedCollection(Collection c)

I have 100 elements in the array list. i want to delete from 50 to 100 position how can i do it .please write the code ?
Use removeRange method from ArrayList Ex: al.removeRange(50,101); 50 is include in deletion and 101 is excluded

An Employee class is present and its objects are added in an arraylist. Now I want the list to be sorted on the basis of the employeeId of Employee class. What are the steps?
1) Implement Comparable interface for the Employee class and override the compareTo ( Object obj) method in which compare the employeeID 2) Now call Collections.sort() method and pass list as an argument. Now consider that Employee class is a jar file.

1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method . 2) Call Collections.sort() on the list and pass comparator as an argument.

Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();
It is preferred because: If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that. The most important one If a function is declared such that it takes list. E.g void showDetails(List list);When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.

How to make a List (ArrayList,Vector,LinkedList) read only?


A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown

I need to use a collection object in my application which can insert/delete objects at any placed and can

retrieve

any

particular

positioned

object

in

the

collection? Note: I am not using Threads in my class so dont consider about synchronization.?
If you need in a key/value pair then for your requirements HashMap is best. If you need just an list which you can use to retrieve values using index means ArrayList is best. All the collections are best complexity for solving their own nature depends on the application requirement.

Difference between HashMap and HashTable?


Both collections implements Map. Both collections store value as keyvalue pairs. The key differences between the two are 1. Hashmap is not synchronized in nature but hshtable is. 2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. Fail-safe - if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException? 3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null. (Or) 1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

2. HashMap does not guarantee that the order of the map will remain constant over time. 3. HashMap is non synchronized whereas Hashtable is synchronized. 4. Iterator in the HashMap is fail-fast while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. 1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. 2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception wjavascript:void(0)ill be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown. 3)Structurally modification means deleting or inserting element which could effectively change the structure of map. HashMap can be synchronized by Map m = Collections.synchronizeMap(hashMap);

Is it better to have a hashmap with large number of records or n number of small hashmaps?
It depends on the different scenario one is working on:

1) If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map. 2) If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.

Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap


HashMap is fastest,

ConcurrentHashMap,Collections.synchronizedMap,HashTable.

Difference between List and a Set?


1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements. 2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet).

What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

How to sort list in reverse order?


Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with

reverseOrder(). Then, pass the reverse Comparator to the sort() method. List list = new ArrayList(); Comparator comp = Collections.reverseOrder(); Collections.sort(list, comp)

About Memory Related


Find the maximum size of heap used in the memory in java.? find the size of an object?
The heap size of an object can be found using Runtime.totalMemory()-Runtime.freeMemory() .

Change the heap size of a JVM?


java -Xms <initial size> -Xmx <maximum size> program For example: java -Xms64m -Xmx128m program Runtime class in java has all the memory related methods. [b]maxMemory(): [/b]Returns the maximum amount of memory that the Java virtual machine will attempt to use and [b]totalMemory():[/b] Returns the total amount of memory in the Java virtual machine.

Memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.

Consider a scenario in which the admin want to sure that if some one has written System.exit() at some part of application then before system shutdown all the resources should be released. How is it possible?
This is possible

using Runtime.getRuntime().addShutdownHook(Thread hook).

Does Java allocate stack and heap memory?


Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.

In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.

Marshling is convert from byte code to network understand able


format .

Unmarshsling is converting from network understand able format


to byte code conversion..

Reference sites:
http://coffeewithcode.com/2011/07/13/java-interview-question-vii/

http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm http://www.techartifact.com/blogs/2011/07/factory-method-pattern-in-java.html

About Design Patterns


What is Singleton? Have you used Singleton before?
Singleton is a class which has only one instance thought out the application and provides a getInstance() method to access the singleton instance.

Step 1: Provide a default Private constructor Step 2: Create a Method for getting the reference to the Singleton Object Step 3: Make the Access method Synchronized to prevent Thread Problems. Step 4: cloning
class SingletonClass { private static SingletonClass singletonObject; /** A private Constructor prevents any other class from instantiating. */ private SingletonClass() { // } public static synchronized SingletonClass getSingletonObject() { Optional Code

Override the Object clone method to prevent

if (singletonObject == null) { singletonObject = new SingletonClass(); } return singletonObject; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } public class SingletonObjectDemo { public static void main(String args[]) { // SingletonClass obj = new SingletonClass(); //Compilation error not allowed SingletonClass obj = SingletonClass.getSingletonObject(); // Your Business Logic System.out.println("Singleton object obtained"); } }

How do you prevent for creating another instance of Singleton using reflection?
Open to all. In my opinion throwing exception from constructor is an option.

Factory Design Pattern:


Factory Pattern is an interface responsible for creating the object but the sub classes decides which class to instantiate. It is like the interface instantiate the appropriate sub-class depending upon the

data passed. Here in this article we will understand how we can create an Factory Pattern in Java.

When to use a Factory Pattern?


1. When a class does not know which class of objects it must create. 2. A class specifies its sub-classes to specify which objects to create. 3. In programmers language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided. EG: In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the subclasses, we use a factory pattern. Lets suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr. <Name> and if the sex is Female (F), it displays message saying Hello Ms <Name>. The skeleton of the code can be given here. public class Person { // name string public String name; // gender : M or F private String gender; public String getName() { return name; } public String getGender() { return gender;

} }// End of class This is a simple class Person having methods for name and gender. Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen. public class Male extends Person { public Male(String fullName) { System.out.println("Hello Mr. "+fullName); } }// End of class

Also, the class Female public class Female extends Person { public Female(String fullNname) { System.out.println("Hello Ms. "+fullNname); } }// End of class Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided. public class SalutationFactory { public static void main(String args[]) { SalutationFactory factory = new SalutationFactory(); factory.getPerson(args[0], args[1]); }

public Person getPerson(String name, String gender) { if (gender.equals("M")) return new Male(name); else if(gender.equals("F")) return new Female(name); else return null; } }// End of class

Abstract Factory Pattern:


This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes. Use of Abstract Factory: One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another. Eg: Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for.

The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server. So, here we have an abstract base class Computer. package creational.abstractfactory; public abstract class Computer { /** * Abstract method, returns the Parts ideal for Server * @return Parts */ public abstract Parts getRAM(); /** * Abstract method, returns the Parts ideal for Workstation * @return Parts */ public abstract Parts getProcessor(); /** * Abstract method, returns the Parts ideal for * PC * @return Parts */ public abstract Parts getMonitor(); }// End of class This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The specification of Parts will be different for different types of computers. Lets have a look at the class Parts. package creational.abstractfactory; public class Parts { /** * specification of Part of Computer, String

*/ public String specification; /** * Constructor sets the name of OS * @param specification of Part of Computer */ public Parts(String specification) { this.specification = specification; } /** * Returns the name of the part of Computer * @return specification of Part of Computer, String */ public String getSpecification() { return specification; } }// End of class And now lets go to the sub-classes of Computer. They are PC, Workstation and Server. package creational.abstractfactory; public class PC extends Computer { /** * Method over-ridden from Computer, returns the Parts ideal for * Server * @return Parts */ public Parts getRAM() { return new Parts("512 MB"); } /**

* Method over-ridden from Computer, returns the Parts ideal for * Workstation * @return Parts */ public Parts getProcessor() { return new Parts("Celeron"); } /** * Method over-ridden from Computer, returns the Parts ideal for * PC * @return Parts */ public Parts getMonitor() { return new Parts("15 inches"); } }// End of class

package public class Workstation extends Computer { /**

creational.abstractfactory;

* Method over-ridden from Computer, returns the Parts ideal for * * */ public return } /** Parts new getRAM() Parts("1 { GB"); @return Server Parts

* Method over-ridden from Computer, returns the Parts ideal for * * */ public return } /** * Method over-ridden from Computer, returns the Parts ideal for * * */ public return } }// End of class package creational.abstractfactory; public class Server extends Computer{ /** * Method over-ridden from Computer, returns the Parts ideal for * * */ public return } /** * Method over-ridden from Computer, returns the Parts ideal for * * @return Workstation Parts Parts new getRAM() Parts("4 { GB"); @return Server Parts Parts new getMonitor() Parts("19 { inches"); @return PC Parts Parts new getProcessor() Parts("Intel P { 3"); @return Workstation Parts

*/ public return } /** * Method over-ridden from Computer, returns the Parts ideal for * * */ public return Parts new getMonitor() Parts("17 { inches"); @return PC Parts Parts new getProcessor() Parts("Intel P { 4");

} }// End of class Now lets have a look at the Abstract factory which returns a factory Computer. We call the class ComputerType. package creational.abstractfactory; /** * * * */ public class ComputerType { private Computer comp; public static void main(String[] args) { ComputerType type = new ComputerType(); Computer computer = type.getComputer("Server"); System.out.println("Monitor: "+computer.getMonitor().getSpecification()); System.out.println("RAM: "+computer.getRAM().getSpecification()); System.out.println("Processor: "+computer.getProcessor().getSpecification()); This is of the computer the abstract factory types which of returns one three computers.

} /** * * * @param computerType String, PC / Workstation / Server * @return Computer */ public Computer getComputer(String computerType) { if (computerType.equals("PC")) comp else comp else comp = new Server(); return comp; } }// End of class Running this class gives the output as this: Monitor: RAM: Processor: Intel P 4. 17 4 inches GB = = new new PC(); Workstation(); if(computerType.equals("Workstation")) if(computerType.equals("Server")) Returns a computer for a type

Data Access Object :


Abstracts and encapsulate all access to the data source. The DAO manages the connection with the data source to obtain and store data.

Base Controller :
Provides a centralized controller for managing the handling of requests.

Session Facade :
Encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.

You might also like