What is Varargs method in java?

Variable list of arguments(Var-arg) methods is the most important concept introduced in java 1.5 version. The main purpose of this Var-args methods is to increase the usability of a method by allowing any number of arguments in the method call. Best example of varargs method is main method

public static void main(String[] args) is same as ...
public static void main(String... args)

Var-arg is indicated using three sequential dots ( "..." ) .
Example:
method(int... args); // accepts any number of arguments of type int.
m1(String... args); // accepts any number of arguments of type String.
We can pass any number of arguments to the varargs methods including zero. Let us see how we can declare and call a var-arg method.
package com.programmerQueries.java.Varagrs;

/**
 * @author ProgrammerQueries
 * @since: 22-04-2017
 */
public class VarargApp
{
    public static void main( String[] args )
    {
        m1();
        m1(1);
        m1(1,2);
       
    }
    public static void m1(int... args)
    {
        System.out.println( "Programmer Queries!" );
    }
Output

The above example contains a vararg method  m1.We can pass any number of arguments to the method m1 . All the 3 method calls in the above program are valid.
The var-arg parameters are converted to one dimentional array internally.Hence the var-arg values can be differentiated using index.





 



What is the difference between Exception and Error?

Most of the people think that Exception causes at run-time and Error causes at compile time. But here are we are going to discuss about run-time exceptions and errors.
Throwable is the root class for exception hierarcy and Exception and Error are the subclasses of throwable class.

Exception:

Exception is the subclass of throwable class. Exceptions are caused by the program itself . We can recover a exception by handling the exception using try-catch block.
Example: 
If we are trying to read a file from a particular location and if the file is not available in that location at run-time, then the program will throw an exception. We can handling the exception and can provide a local file to continue the program.

Error:

Error is the subclass of throwable class. Errors are not caused by the program but due to lack of system resources and these are non-recoverable.
Example:
out of memory error due to lack of heap size.

What is the difference between overloading and overriding?

Overloading:

Two methods are said to be overloaded if and only if both the methods have same name but different argument types.
Example:
public class MethodOverloading {

    public void test(int a)//overloaded
    {
        System.out.println("int argument method");
    }
   
    public void test(long a)//overloded    {
        System.out.println("long argument method");
    }
}

Overriding: 

 Overridding concept comes with inheritance. When a child class extends its parent class, all the methods of parent class are available to child class. If child class want to use any method available from parent class but with some modifications, then the child class has the flexibility to redefine the method based on its requirements.
The parent class method which is overridden is called overridden method and the child class method which overrides is called overriding method.
Example:
public class TestParentOverriding {
    public static void method1(int args)
    {
        System.out.println("method1 of main class");
    }
}
class TestChildOverriding extends TestParentOverriding
{
  public static void main(String[] args)
    {
        method1(5);
    } 
    public static void method1(int args)
    {
        System.out.println("method1 of child class");
    }
}
Output:
 method1 of child class

 Differences between overloading and overriding: 

The differences between method overloading and method overriding is defined in the below table based on the property.
Differences between overloading and overriding


Explain about public static void main(String args[ ])

Let us consider the following class Test
class Test
{
   // code
}

The java compiler compiles this class successfully irrespective of main() method existence.
But at run-time, if JVM is unable to find the main() method, then we will get run-time exception saying: NoSuchMehtodException:main

JVM always searches for the main method with the following prototype:
public static void main(String args[])

But, there are many questions related to this. Like, why jvm only search for this prototype? what is the use to have this prototype?
JVM is also a software program. As it is programmed in such a way in that whenever jvm starts executing a java program, it should starts its execution from the main method with prototype
public static void main(String args[]).
 
main method prototype 
 
The syntax of main method is very strict. If we do any change in the prototype, we will not get any error in the compile time, but we will get run-time exception saying that NoSuchMethodException:main.
But, the following statements are true.
  • The order of the modifiers is not important that is, instead of "public static", we can write as "static public".
  • we can declare "String[]" in any acceptable form. i.e., all the following declarations are acceptable.
main(String[] args)
main(String args[])
main(String []args)
  • Instead of "args ", we can take any valid java identifier. 
  • We can replace String[] with var arg parameter. i.e.,the following declaration is possible.
main(String[] args) => main(String... args)
  • We can declare main() method with the following modifiers also: final, Synchronized, Strictfp

  Overloading of main(): 

Overloading of main() method is possible but JVM always call the main method with String[] argument only. 
Example: 

public class TestMainOverloading {

    public static void main(String[] args)
    {
        System.out.println("main method with String[] args");
    }
  
    public static void main(int args)
    {
        System.out.println("main method with int args");
    }
}
Output:
main method with String[] args
The other overloaded method should be called explicitly as a normal method as shown below.
 Example:
public class TestMainOverloading {

    public static void main(String[] args)
    {
        System.out.println("main method with String[] args");
        main(5);
   
}
   
    public static void main(int args)
    {
        System.out.println("main method with int args");
    }
}

Output:
main method with String[] args
main method with int args

Inheriting of main():

main method can also be overridden. That is if a child class extends a super class having main method, and if we run the child class, then the execution starts from the main method in the super class.
Example:
public class TestMainOverriding {

    TestMainOverloading obj = new TestMainOverloading();
    public static void main(String[] args)
    {
        System.out.println("main method of parent class");
    }
}
class ChildTestMainOverriding extends TestMainOverriding
{
     public static void main(String[] args)
    {
        System.out.println("main method of child class");
    }
}
Output:
 main method of parent class
The class ChildTestMainOverriding extends the class TestMainOverriding which contains the main() method.Hence when we run the class ChildTestMainOverriding , the main method in the parent class will be called by JVM and execution starts from the main() method of parent class.
Hence inheritance is applicable for main() method also.

Method Hiding:

If the child class contains main() method, the main() method of parent class will be hidden by the child class main() method and when we run the child class, the child class main() method will be called by JVM. This concept is called method hiding .
Example:
public class TestMainOverriding {

    TestMainOverloading obj = new TestMainOverloading();
    public static void main(String[] args)
    {
        System.out.println("main method of parent class");
    }
}
class ChildTestMainOverriding extends TestMainOverriding
{
     public static void main(String[] args)
    {
        System.out.println("main method of child class");
    }
}
Output:
 main method of child class

 

Explain about System.out.println();

System.out.println();
This is the line we are using from the first day of coding. System is actually a class in the java.lang package. We do not need to import this java.lang.* package, as it is imported by default.
Class System
{
    static PrintStream out;
    .
    .
    .
}
System.out.println("hello");

Conclusion from the above code:

  • System is a class present in java.lang package.
  • out is a static method of PrintStream type.
  • println() is a method present in  java .io.PrintStream class.

What is the difference between Interface and Abstract Class?

  1. When there is only requirement specification provided and there is no clarity on the implementation, then we need to go for an interface to get the high level view of the requirement. This is 100% abstraction. When we know about the implementation partially, then we should go for abstract classes. Abstract classes in this level help the programmer to add the implementation in future.
  2. In interface every method is public and abstract by default, hence interface is pure abstract class. All the methods in abstract class need not to be public and abstract , hence concrete methods also can be used in abstract classes.
  3. The methods in interface can not be declared with the modifiers private, protected, final, static, synchronized, native, strictfp. Whereas, the methods in the abstract classed can be declared with any type of modifiers.
  4. Every variable present inside interface is public , static and final by default.Whereas, the variables inside the abstract class need not be public, static and final.
  5. The variables inside the interfaces cannot be declared with private, protected, transient, volatile. Whereas, the variables in abstract classes can be declared with any type of modifiers. As we cannot create object to an interface, serialization is not possible with interface.
  6. Interface variables should be initialized at the time of declaration, if not we will get a compilation error. For Abstract class variables there is no such kind of restriction. 
  7. We cannot declare instance block or static block inside an interface. Whereas, we can declare instance block and static block inside abstract class.
  8. We cannot declare constructor inside an instance as there is no instance variable in interface. In abstract class, we can declare a constructor.

Interface vs abstract class vs concrete class

The following points make you clear when to use interface, abstract class and concrete class in your java code implementation for a requirement.
  1. When there is only requirement specification provided and there is no clarity on the implementation, then we need to go for an interface to get the high level view of the requirement. This is 100% abstraction. Example: Servlet
  2. When we know about the implementation partially, then we should go for abstract classes. Abstract classes in this level help the programmer to add the implementation in future. Example:Generic Servlet, HTTPServlet
  3. If we know the implementation completely and ready to provide the service with the APIs, then we can go for concrete classes. Example: MyOwnServlet.
At the end of the requirement, we only need concrete classes to expose the API and to provide the services. The Interfaces and the Abstract Classes are used to develop the concrete classes.

String vs StringBuffer vs StringBuilder

The most important question in interviews is when to use String, StringBuffer and StringBuilder.
  1. If the content is fixed and do not change frequently , then we need to use String objects.
  2. If the content is not fixed but thread safety is required, the we need to use StringBuffer Objects.
  3. If the content is not fixed and thread safety is not required, then we can use StringBuilder objects.

Refer:

What is the difference between StringBuffer and StringBuilder?
What is the difference between String and String Buffer?

What is the difference between StringBuffer and StringBuilder?

StringBuffer and StringBuilder both are used for mutability. Both have same methods and constructors but all the methods in StringBuffer are Synchronized whereas, the methods in StringBuilder are not Synchronized.
As the methods in the StringBuffer are synchronized, only one thread can operate on stringbuffer object at a time which gives thread safety, but this reduce performance.Hence wherever performance is more concerned than thread safety, we have to use StringBuilder over StringBuffer.

The difference between StringBuffer and StringBuilder are shown below:
StringBuffer and StringBuilder Differences

what are the various modifiers available in java?

The access modifiers place a vital role in java programming.
The list of various modifiers available in java is as follows:
  1. public
  2. private
  3. protected
  4. <default>
  5. abstract
  6. final
  7. static
  8. native
  9. synchronized
  10. strictfp
  11. transient
  12. volatile
In java there is no such thing called access specifiers and all these are considered as access modifiers.
The modifiers and there applicability on classes, methods, blocks, variables, interfaces, constructors and enums are given below.

Modifiers and their applicability

Important Conclusions:

  1. The modifiers wihich are applicable for inner classes but not outer classes are private, protected, static.
  2. The modifier that is applicable to class but not interface is final
  3. The modifiers that are applicable to classes but not enums are final and abstract.
  4. The modifier which is applicable to only methods and cannot be used anywhere else is native.
  5. The only modifiers which are applicable to constructors are public,private,protected, default.
  6. The only applicable modifier for local variables is final.
We can declare,
  • a class inside a class
  • a class inside an interface
  • an interface inside an interface 
  • an interface inside a class.
The interface which is declared inside a class is always static implicitly.
The interface which is declared inside an interface is always public and static implicitly.
The class which is declared inside an interface is always public and static implicitly.

Illegal Combinations :

 Methods:
  1. If a method is public, we cannot declare it as private or protected.
  2. If a method is abstract, then we cannot declare it as final, static, private, synchronized, strictfp, native.
Variables:
  1. If a variable is public, we cannot declare it as private or protected.
  2. If a variable is final, we cannot declare it as volatile.
Class:
  1. If a class is public, we cannot declare as private or protected. 
  2. If a class is final, we cannot declare as abstract.
This is applicable to inner classes also .
 

what is the difference between ''=='' operator and equals() method in java?

In general, we use == operator to compare references or addresses and equals() method is used to compare contents.

example: 

String s1 = new String("java");
String s2 = new String("java"); 
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

O/P:  
false
true
Here, the == operator compares  the addresses of s1 and s2 which are clearly pointing to different address locations and hence the result of this comparison is false. Whereas, the equals() method compares the contents of s1 and s2 and hence result is true.
 

What is the difference between String and String Buffer?

String objects are "immutable" and String buffer objects are "mutable".

String:

Once we create a string object, we cannot perform any changes on that same string object. If we try to perform any operation on that object, then a new object will get created with those changes. This non changeable behavior of string object is called "immutability". 
example:
String s = new String("Programmers"); // a string object s is created and has a value "programmers". 
s.concat("language"); // new object "Programmers language" will be created and left unassigned to any variable.(will be removed by garbage collector) 
System.out.println(s);   
o/p: Programmers

String Buffer:

Once we creates a string buffer object, we can perform any type of changes on the existing object itself. This changeable behavior of String Buffer objects is called "mutability".
example:
String sb = new String("Programmers"); // a string object s is created and has a value "programmers". 
sb.append("language"); // object  will be modified to "Programmers language"
System.out.println(sb);   
o/p: Programmers language

What is the difference between final, finally and finalize?

The similarity in the names may be one of the reason to ask this question in many number of interviews.

final:  

final is a modifier applicable for classes, methods and variable.
  • If we declare a variable as a final, it will become constant and we cannot perform reassignment to that variable. 
  • If a method is declared final in a class, the method cannot be overridden in the child classes.
  • If a class is declared as final, then the class cannot be extended ie., we cannot create a child class to that class.

finally:

finally is a block always associated with try / catch block to maintain cleanup code.
try
{
   // Risky code
}
catch(Exception e)
{
    //handling part of code
}
finally
{
    //cleanup code(like resource de-allocation)
}

 finalize:

finalize() is a method present in "object" class. finalize is called by garbage collector to perform cleanup activities before destroying an object.

Note:

finally block is meant for cleanup activities related to the try block. The resources which are opened in the try block code are closed in the finally block. Whereas, finalize() method is related to cleanup the resources which are related to the unused objects and is related to garbage collector.