51 frequently asked Java interview questions and answers for freshers(0-2 Years Experience)- Part 1(Q#01 to Q#10)

A must have tool before going for Java developer interview. The main agenda of this post is to discuss most commonly asked Java interview questions with detailed answer. It consist of 51 Questions, divided into 5 posts - Post 1(Q#1 to Q#10), Post 2(Q#11 to Q#20), Post 3(Q#11 to Q#30), Post 4(Q#31 to Q#40), Post5(Q#41 to Q#51).
1.Why Java termed as platform independent language? Or What makes Java platform independent? Or What do you mean by compile once , Run any where ?
Answer : Platform independent means - compile a java class at any platform (Windows, Linux, etc.) and run/execute it any where without knowing any whereabouts where it was compiled.It is intermediate byte-code(compiled java code/instructions) which makes java a platform independent. Byte-code instructions are generated in such a way that if JRE(Java Runtime Environment) is available then it will be executed smoothly.

2. JDK is platform dependent or platform independent? 
Answer: JDK(Java development kit) is platform dependent. Java is platform independent, not JDK. JDK for Windows,Linux/Unix are different and incompatible with each other.
Note:- JRE is part of JDK, JRE is also platform dependent.

3.Write a simple Java program and execute it from command line ? Or What does 'public static void main ( String args[ ] ) ' stands for?
Answer: Lets write a simple hello world program and understand main method syntax and execution flow:
class FirstProgram
{
  public static void main (String[] args)
  {
    System.out.println("Hello devInline");
  } 

}
FirstProgram is name of the class and it contains main method, from where execution of program starts(unless we have a static block). In a java class, we can have multiple main methods but signature of this main method is unique. It should be public(because main method can be called from any where), static( because main method is executed before creating any instance so , it should be class method), void (it does not return any value to OS as contrast to C program) and main method should have capability of accepting arguments of type String array(Command line arguments are stored in this array). From command line : compile the program using following command : javac FirstProgram.java  and it generates .class file. For running this program we use following command : java FirstProgram

4.What do you mean by PATH and CLASSPATH in Java ? 
Answer: It is one of the fundamental question which is asked even from experienced engineer and some fails to justify. PATH and CLASSPATH are environment variables, PATH is for Operating system and CLASSPATH is for running application/run time environment.
CLASSPATH are used to instruct/communicate run time environment where they should look for user classes/jars.The default value of the classpath is ".", meaning that only the current directory is searched.
PATH environment variable is used to instruct Operating system , where they should look for executables like javac.exe, java.exe, javadoc.exe. A follow-up question popup :
Can we run our java program without specifying PATH environment variable ?
Yes, we can. But every time we have to specify full path of javac, java executables. For example, for compiling our FirstProgram.java we have to do something like this : (From command line)
C:\Java\jdk1.6.0\bin\javac FirstProgram.java , however if you have set PATH variables OS will take care of it and we can directly use javac executables like : javac FirstProgram.java.

5. What is encapsulation and how does make it Java an object oriented language ? / OOP features of Java ?
Answer: In Java, encapsulation is one of the four core features (Inheritance,Polymorphism, Abstraction, Encapsulation) which makes it an Object oriented programming language. The process of combining data with appropriate methods in a single unit is termed as encapsulation, class forms the basis of encapsulation. Ideal way to achieve encapsulation in a class is to make all instance variables private and access each of then using public getter/setter's.
Inheritance: Acquiring properties(variables/methods) of parent class by child class.
Abstraction: Hiding internal complexity/implementation details and just expose the functionality.
Interface and abstract class are used to achieve abstraction in Java.
Polymorphism : Existing multiple at same time. Method overloading and Method overriding are example of polymorphism in Java.

6.What is difference between Interface and Abstract class ?
Answer: Interface and abstract class are two different ways to achieve abstraction in Java. Using Interface we achieve 100% abstraction and using abstract class we can achieve 0 to 100% abstraction. In interface, we only specify signature of method - implementation complexity is left for the user to decide. The interface keyword produces a completely abstract class, one that provides no implementation at all and all the methods are by default abstract in an interface.
Any class having one or more abstract method(it has only a declaration and no method body) then that class is termed as abstract class and the class itself must be qualified as abstract. Please note, in abstract class we can have some method with implementation and some without implementation that's why 0 to 100% abstraction. It’s possible to make a class abstract without including any abstract methods.
Note: Instance of abstract class cannot be created, compiler will throw error, if tried.
Interfaces are implemented and abstract classes are extended by another class.

7. Write a simple program to demonstrate where Interface and Abstract class finds it's uses ?
Answer: Abstract class is used when we have some common implementation that will be shared by all extending class and some methods requires specific implementation for each of the implementing classes. However, interface is used where we need to just specify the functionality of methods and implementation is users responsibility.
Hide code lines
 Interface example:
interface Banking{
// Different account type has different details
public String getAccountDetails(Long accountNumber);   

// Interest and principle amount
public Long getAccumulatedSum(String accountType, Long accountNumber)
}
class RecurringAccount implements Banking{
 public String getAccountDetails(Long accountNumber){
  //implementation.... interest, payment info , etc. 
 }
 public Long getAccumulatedSum(String accountType, Long accountNumber){
  //implementation.... interest rate varies so as calculation... 
 }
}
class FixedDeposit 
implements Banking{
  public String getAccountDetails(Long accountNumber){
  //implementation.... 
 }
 public String getAccumulatedSum(String accountType, Long accountNumber){
  //implementation....
 }
}
Abstract class example:
abstract class Finance{
  public Employee getEmployeeDetails(Long employeeId){
    //implementation - returns Employee Object
  }
  public abstract generateSalarySlip(Employee employee);
}
class ContractEmployee extends Finance{
  public generateSalarySlip(Employee employee){
    //apply specific rules for contract employee and generate salary-slip 
  }
}

class OnSiteEmployee extends Finance{
  public generateSalarySlip(Employee employee){
    //apply specific rules for OnSite employee and generate salary slip 
  }
}
8. What is polymorphism in Java ? Can you explain with it's implementation in Java ?
Answer: The ability of an object to take different forms is termed as Polymorphism.
Polymorphism can be distinguished by when the implementation is considered: statically (at compile time) or dynamically (at run time). Method overloading is an classical example of compile time polymorphism and method overriding is of rum time polymorphism. Lets understand each of them in detail.
Compile time polymorphism / static binding : method overloading in a class is achieved by varying number or type of method parameters. It is compiler's responsibility to resolve or bind one of the overloaded methods with particular object and that method will be executed at run time.
Since, which method will be executed by an object is decided at compile time that's why it is called compile time binding or compile time polymorphism(singe method having different forms).See following code lines for better understanding of method overloading: sum method is overloaded based on different type of parameters and number of parameters.
class MathOperation{
    //.......
  public Long sum(int num1, int num2) {
    return num1+num2;
  }
  public ComplexNum sum(ComplexNum c1,ComplexNum c2){
    return new ComplexNum(c1.x+c2.x, c1.y+c2.y);
  }
  public String sum(String input1, input2){
    return input1+input2;
  }
}
Rum time polymorphism: When child class overrides methods of parent class, it is the type of object which decide which method(parent class or child class) will be executed and decision is taken at run time by JVM(Java virtual machine). 
Note: Compiler validate the method signature being called by an object based on the reference variable however at run time JVM runs method based on object type not reference type.In below example at compile time, compiler validates display() method for pl.displayName(); in ParentClass but at run time executes ChildClass method. Let's understand this intricacy with an example: 
Run time polymorphism/ Dynamic binding - which method being decided based on type of object
class ParentClass {
  protected String name;
  public ParentClass() {
    name = "parenetClass";
  }
  public void displayName() {
    
    System.out.println("Parent class method "+this.name);
  }
}
class ChildClass extends ParentClass {
  public ChildClass() {
    name = "childClass";
  }
  public void displayName() {
    System.out.println("child class method "this.name);
  }
}
public class MainClass {
  public static void main(String[] args) {
    ChildClass cl = new ChildClass();
    ParentClass pl = new ParentClass();
    cl.displayName()/* Displays: child class method childClass */
    pl.displayName()/* Displays: Parent class method parenetClass */
    //parent class reference to child class object.
    pl = cl;
    pl.displayName()/* Displays: child class method childClass */
  }
}
From above example , we can see that even if we refer child class object using parent class reference (pl = cl;), at runtime child class method is executed (It is type of object which gets priority over type of reference).

9.Write a simple program to take input form user and find number is even or odd ?
Answer: The main purpose of  asking this program is to check hands on experience in Java. Focus is on coding style , so try to write with minimum error/gaps.
Hide code lines
import java.util.Scanner;
public class EvenOdd {
  private static Scanner scn;
  public static void main(String[] args) {
    System.out.println("Enter a number for even/odd test:\t");    
    scn = new Scanner(System.in);
    int input = scn.nextInt();
    //even/odd logic here- % is modular division operator 
    if(input%2==0){
      System.out.println(input + " is an even number");
    }else{
      System.out.println(input + " is an odd number");
    }
  }

}

10.In c++ we have constructor/destructor for creating/destroying objects, how it is handled in Java / Object life cycle in Java? 
Answer: In Java, generally we create object using new operator on heap and after that we forget. What does it mean we forget, Java has internal mechanism called garbage collection clean-up activity or destroying unused object. Garbage collection cycle is run by JVM and memory is reclaimed.We can request/hint garbage collection using System.gc() to run GC cycle.There are various ways to create object in Java.
  • Using new operator - Mostly we use new keyword
    EvenOdd objectName = new  EvenOdd ();
  • Using Class.forName() : Here default constructor should be there in class.
    EvenOdd objectName = (EvenOdd Class.forName("pkgName.EvenOdd").newInstance();
  • Using clone(): If we want to create duplicate object ,duplicate of above object created like
    EvenOdd object = (EvenOdd) objectName.clone();
  • Using object deserialization: <anInputStream> is some input stream
    ObjectInputStream inStream = new ObjectInputStream(anInputStream );
    EvenOdd object = (EvenOdd) inStream.readObject();
  • Using classLoader:
    this.getClass().getClassLoader().loadClass("pkgName.EvenOdd").newInstance();
Note: garbage collector is non-deterministic, Sytem.gc() can only request garbage collector to perform garbage collection activity , it depends on collector whether it will run immediately or not.


Next: Part 2(Q#11 to Q#20 )  -Java interview questions and answers for freshers

1 Comments

Previous Post Next Post