Java Topics

Java Keywords
Key Concepts
Key Concepts #2
OOPS in java
Java Collections#1
Java Collections #2
Exceptions #1
Exceptions #2
Threads#1
Threads#2
InnerClass
Serialization
Immutable Class
Cloning in Java
Garbage Collection
JSP #1
JSP #2
Programming Q#1
Programming Q#2
Programming Q#3


Key Concepts in Java

Q1) Why is main() method static?

Ans) 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.

Q2) What is the difference between static methods and instance methods?

Ans) 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 doesn’t 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.

Q3) Can static block throw exception?

Ans) Yes, static block can throw only Runtime exception or can use a try-catch 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.

Q4 What is difference between abstract class and interface?

Ans) 1) A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method.Interface can contain only abstract( non implemented) methods.
2) The abstract class can have public,private,protect or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesnt have any variables it only has constants.
3) A class can extend only one abstract class but a class can implement multiple interfaces.
4) If an interface is implemented its compulsory to implement all of its methods but if an abstract class is extended its not compulsory to implement all methods. 5) The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

Q5) Explain with example to describe when to use abstract class and interface?

Ans) Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementaion for tyres will be provided.


public abstract class Car{

public abstract String getCarName();

public final int getNoOfTyres(){
   return 4;
}

}

Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.


public interface Car{

public abstract String getCarName();
public abstract int getNoOfTyres();
}

Q6) Does java support multiple interitance? Why?

Ans) Java doesnt support multiple inheritance but it provide a way through which it can enact it.
Consider the scenario is C++

Class A{

public void add(){
// some text
}
}

Class B{

public void add(){
// some text
}
}

Class C extends A,B{

public static void main(String arg[]){

C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}

This problem is called Diamond problem.

This problem in java is taken care with the use of interfaces
In Java similar problem would look like:

interface A{
add();
}

interface B{
add();
}

class C implements A,B{

add(){
// doesnt matter which interface it belong to
}
}

Q7) Can this keyword be assigned null value?

Ans) No

Q8) What are the different types of references in java?

Ans) Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references—soft, weak, and phantom references. Each type of reference is designed for a specific use.

A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable), but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."

A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool. Semantically, a weak reference means "get rid of this object when nothing else references it."


A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is called phantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no longer needed and has been finalized in preparation for being collected."

Q9) How to change the heap size of a JVM?

Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program

Q10) What is difference between instanceof and isInstance(Object obj)?

Ans) Differences are as follows:

1) 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)) {
...
}

2) 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.

Q11) Java supports pass by value or pass by reference?

Ans) 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.

Q12) What is memory leak?

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

Q13) What is the difference between equals() and ==?

Ans) == 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

Q14) 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.

Q15) How to find the size of an object?

Ans)The heap size of an object can be found using -

         Runtime.totalMemory()-Runtime.freeMemory() .

More Questions >>