Sep 10, 2015

51 frequently asked java interview questions and answers for freshers (0-2 Years Experience) - Part 2(Q#11 to Q#20)

In previous post we covered Question from 1 to 10 here java interview questions and answers for freshers - Part 1
11.Have you used transient and volatile variable in Java? When do we use them?/ How synchronization can be achieved using volatile?
Answer: When we deal with serialization in java, suppose we have some field that we do not want to serialize then we make that variable transient. By marking that field transient we hint serialization mechanism that "Don’t bother saving or restoring this variable". On de-serialization transient field value is reset to default one. Transient variable can be declared as follows:
 private transient String field_name;
In multi-threaded environment,any field marked volatile guarantees that other threads will see the most recent value assigned to that field and visibility across the application is maintained.
 private static volatile int serialNumber = 0;
Suppose Thread-1 perform write operation and modify serialNumber, changes are immediately flushed to main memory and other threads (thread-2, thread-3, etc) reads from main memory and see updated value. Please note, this is still valid even if local cache is involved.
In summary, transient keyword is used to turn off serialization on a field-by-field.Transient keyword is alternative to Externalizable interface.Volatile keyword guarantee that in multi-threaded environment all threads reads updated values from memory.

12.What is this and super in Java ?
Answer: "this" refers to current object and "super" refers to base(parent) class. In general,both method call: this.methodName() and methodName() are same, this just indicates that it is called in the context of current object.
Mostly, super keyword is used to call base class constructor from derived(child) class with
appropriate arguments. Following code lines shows use of this and super keyword in java.
class DerivedClass extends ParentClass {
  private int derived_field;
  DerivedClass(int input_parent,int input_derived) {
    super(input_parnet);
    this.derived_field = input_derived;
  }
}

13.What do you mean by String is immutable ?
Answer: Objects of the String class are immutable.Once a string object is created , you cannot modify that object. String objects can be created in string pool(termed as string literals ) and on heap(using new operator). Consider following example,
 String str1 = "InputString1"; // Created in string pool
 String str2 = new String("InputString2"); //Created on Heap memory location
 String str3 = str1 + "Modify"; // New string is generated
Here, str1 is generated in string pool and str2 on heap. When we create str3, str1 is not modified - it is still available in connection pool, a new string is created InputString1Modify and it is referenced by str3.It is good to know, a followup question sometimes asked (may be something related to it):
How many string object/s created by doing this?
 String strObj = new String("INPUT");
Answer is two, one in string pool and another one on Heap. Since, "INPUT" will create a string in string pool and new operator will create a object on Heap.

14.Where do we use  == and equals() ? or Why equals() is good to use for Objects comparison ?
Answer: operator "==" is comparison operator and it returns true if,
- Two variables have same value. i.e: int one = 12; int two = 12; // one == two returns true.
- two reference variable pointing/referring to same object. For example,
  Employee emp1 = new Employee("Nikhil");
  Employee emp2 = emp1;  // emp2 == emp1  returns true, as both referring to same Object.
equals() is used to compare two objects not just references. Lets create a new Employee object and understand equals method: Employee emp3 = new Employee("Ranjan");
emp1.equals(emp3) returns false, since equals does object comparison and both emp1 and emp3 pointing to different object. if we do change the emp2 references and pointing to emp3 then == operator will return true.
Note: Always use equals() for object comparison, == is deceptive.Use == only when dealing with primitives.

15. What is wrapper class in Java? Explain with an example. / How to we convert an string into integer in Java?
Answer:  In order to use primitives (int, float, double, boolean) as Object, wrapper class was introduced. For int - Integer, float- Float, double - Double, etc class were introduced and it is widely used in generics, primitives cannot be used with generics.
Integer intObj = new Integer(456);   //Creates an object on heap
Double doubleObj = new Double(453.9); // Creates an Object on heap
In Java 5, autoboxing/Unboxing was introduced to make int and Integer implicitly controvertible.
int primInt = 456;  // both "primInt.equals(intObj) and printInt == intObj" return true.
Note: In java we have two high-precision arithmetic class : BigInteger and BigDecimal, that falls under wrapper class category, however these classes does not have primitive analogue.
How to we convert an string into integer in Java?
Integer wrapper class can be used to convert string into integer. Consider following code lines:  
String numberAsString = "12";  //12 as string
System.out.println(Integer.parseInt(numberAsString ) + 23); // It displays 35 not "1235"

16. Have you used Java 5 for loop ? Can you write a sample how do we iterate an array of String Object using it ?
Answer: Java SE5 introduced a more succinct for syntax,sometimes termed as  foreach syntax.We  don’t have to create an int to count through a sequence of items—the foreach produces each item for us automatically. It is commonly used to iterate arrays and other containers. Consider following examples:
String strArray[] {"Nikhil","Ranjan","Ritz","CKM"};
  for(String iterator : strArray){
    System.out.print(iterator + " "); //each element is picked one by one

  }
//Output: Nikhil Ranjan Ritz CKM

17.What is difference between overloading and overriding ? Can you explain with an example?
Answer:  In Java, when we say Overloading, it means method overloading (Only two operator :  +  and += is overloaded for strings). In a class,when more than two or more methods with same name  varying number and type of parameters is defined then methods are called overloaded. Signature(no of parameters/type of parameters) of method is different for each method. Return type of overloaded methods can be any thing, it does not decide overloading criteria.
On the other hand, when a derived class redefine base(parent) class method then it is termed as overridden method. Signature of overridden methods MUST be same, else it is not overridden.
Note: Method overloading and overriding are example of polymorphism. Overloading is compile time polymorphism and overriding is run time polymorphism.Let's write sample code to understand overloading and overriding - " code lines speak louder than raw text"
Hide code lines
Method overloading example : sum method is overloaded with different type of parameters.
public class OverloadedMethodExample {

  public int sum(int input1, int input2) {
    return input1 + input2;
  }

  public String sum(String input1, String input2) {
    return input1 + input2;// Operator(+) overloading for string
  }

  public double sum(double input1, double input2) {
    return input1 + input2;
  }

  public static void main(String[] args) {
    OverloadedMethodExample obj = new OverloadedMethodExample();
    System.out.println(obj.sum(1234));
    System.out.println(obj.sum("12""34"));
    System.out.println(obj.sum(45.8723.54));
  }

}
Method overriding example : Here computeInterest method is overridden and signature of method is same in both base class and derived class.
class BankAccount {
  protected Long accountNumber;

  public void setAccountNumber(Long accountNumber) {
    this.accountNumber = accountNumber;
  }

  public Long getAccountNumber() {
    return accountNumber;
  }

  public Double computeInterest(Double principleAmount) {
    return principleAmount + principleAmount * 0.047;

  }
}

class FixedDepositAccount extends BankAccount {
  public Double computeInterest(Double principleAmount) {
    return principleAmount + principleAmount * 0.118;
  }
}

class RecurringDepositAccount extends BankAccount {
  public Double computeInterest(Double principleAmount) {
    return principleAmount + principleAmount * 0.093;
  }
}

public class MethodOverridingExample {
  public static void main(String[] args) {
    BankAccount ba = new BankAccount();
    ba.setAccountNumber(7777777777L);
    BankAccount baf = new FixedDepositAccount();
    baf.setAccountNumber(88888888888L);
    BankAccount bar = new RecurringDepositAccount();
    bar.setAccountNumber(9999999999L);
    System.out.println("Amount of acc. no " + ba.getAccountNumber()
        " is " + ba.computeInterest(1000.00));
    System.out.println("Amount of acc. no" + baf.getAccountNumber()
        " is " + baf.computeInterest(1000.00));
    System.out.println("Amount of acc. no" + bar.getAccountNumber()
        " is " + bar.computeInterest(1000.00));
  }

}

Note: If base class method is marked as static and if you override that method, that is termed as method shadowing not method overriding.For more details click here.

18.What is static keyword  and static block in Java? 
Answer: A class,field and method can be qualified as static in Java. Only with inner classes static keyword can be used(For outer class only accepted modifier are : public , abstract and final).
A field marked as static means, that is class variable and it will be shared by all instance variable.
A method marked as static means that method is class method and class name can be used to call that method.(Not a instance method, it is class method).Only static fields can be used in context of static method. In Java, static block can be created like this :
static {   // Initialization  and setup  };
In a given class, it is the very first thing, that gets executed when that class is referenced(just before first instance of that given class is created). Consider the following sample program, see the output below which suggest that static block is executed first followed by instance variable creation happens. 
public class StaticBlockexample {

  private static int staticCounter;
  static {
    System.out.println("Hello, executed first, default value of "
        "static variable is: " + staticCounter);
  }

  public StaticBlockexample() {
    staticCounter = 1;
  }

  public static void main(String[] args) {
    System.out.println("I executed after static block execution");
    StaticBlockexample obj = new StaticBlockexample();
    System.out.println("static variable value after object creation: "
        + StaticBlockexample.staticCounter);
  }

}
========Sample output:============
Hello, executed first, default value of static variable is: 0
I executed after static block execution
static variable value after object creation: 1

19.What is difference between instance method and class method in Java?
Answer: The methods enclosed within a class without static modifier termed as instance method.
These instance methods are stored in separate logical memory called method area(Perm Gen space) and each object share this method area.
Class methods are marked with modifier static and it is common for all instance of the class. Class method belong to a class and instance method belongs to each instance but method copy is shared.

20. How many .class file generated, when you create a class inside another class and compile it using javac ?
Answer: Class files for all  inner classes (either inside a class or method) inside outermost class will be generated along with outer most class.So , if we have two inner class ineer1 and inner2 inside Outer class, then three class files will be generated such as Outer.class , Outer$Inner1.class, Outer$Inner2.class.

Previous: Part 1(Q#01 to Q#10 ) - Interview Q&A  Next: Part 3(Q#21 to Q#30 ) - Interview Q&A 
Location: Hyderabad, Telangana, India