Showing posts with label java interview question 2012. Show all posts
Showing posts with label java interview question 2012. Show all posts

Java hot concept : How class loading work in JVM | Class loading concept in Java

 When Class is loaded in Java
Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.

When a Class is initialized in Java
After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.

2) an static method of Class is invoked.
3) an static field of Class is assigned.
4) an static field of class is used which is not a constant variable.
5) if Class is a top level class and an assert statement lexically nested within class is executed.

Reflection can also cause initialization of class. Some methods of java.lang.reflect package may cause class to be initialized. JLS Strictly says that a class should not be initialized by any reason other than above.

How Class is initialized in Java
class loading and initialization in Java - When exampleNow we know what triggers initialization of a class in Java, which is precisely documented in Java language specification. Its also important to know in which order various fields (static and non static), block (static an non static), various classes (sub class and super class) and various interfaces (sub interface, implementation class and super interface) is initialized in Java. Infact many Core Java interview question and SCJP question based on this concept because it affect final value of any variable if its initialized on multiple places. Here are some of the rules of class initialization in Java:

1) Classes are initialized from top to bottom so field declared on top initialized before field declared in bottom
2) Super Class is initialized before Sub Class or derived class in Java
3) If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn't trigger initialization of super class or sub class even if static field is referenced by Type  of Sub Class, Sub Interface or by implementation class of interface.

4) interface initialization in Java doesn't cause super interfaces to be initialized.
5) static fields are initialized during static initialization of class while non static fields are initialized when instance of class is created. It means static fields are initialized before non static fields in Java.

6)non static fields are initialized by constructors in Java. sub class constructor implicitly call super class constructor before doing any initialization, which guarantees that non static or instance variables of super class is initialized before sub class.

Examples of  class initialization in Java:
Here is an example of when class is initialized in Java. In this example we will see which classes are initialized in Java.

/**
 * Java program to demonstrate class loading and initialization in Java.
 */
public class ClassInitializationTest {

    public static void main(String args[]) throws InterruptedException {

        NotUsed o = null; //this class is not used, should not be initialized
        Child t = new Child(); //initializing sub class, should trigger super class initialization
        System.out.println((Object)o == (Object)t);
    }
}

/**
 * Super class to demonstrate that Super class is loaded and initialized before Subclass.
 */
class Parent {
    static { System.out.println("static block of Super class is initialized"); }
    {System.out.println("non static blocks in super class is initialized");}
}

/**
 * Java class which is not used in this program, consequently not loaded by JVM
 */
class NotUsed {
    static { System.out.println("NotUsed Class is initialized "); }
}

/**
 * Sub class of Parent, demonstrate when exactly sub class loading and initialization occurs.
 */
class Child extends Parent {
    static { System.out.println("static block of Sub class is initialized in Java "); }
    {System.out.println("non static blocks in sub class is initialized");}
}

Output:
static block of Super class is initialized
static block of Sub class is initialized in Java
non static blocks in super class is initialized
non static blocks in sub class is initialized
false


Observation:
1) Super class is initialized before sub class in Java.
2) Static variables or blocks are initialized before non static blocks or fields.
3) Not used class is not initialized at all because its not been used, none of the cases mentioned on JLS or above which triggers initialization of class is not happened here.

Let's have a look on another example of class initialization in Java:

/**
 * Another Java program example to demonstrate class initialization and loading in Java.
 */

public class ClassInitializationTest {

    public static void main(String args[]) throws InterruptedException {

       //accessing static field of Parent through child, should only initialize Parent
       System.out.println(Child.familyName);
    }
}

class Parent {
    //compile time constant, accessing this will not trigger class initialization
    //protected static final String familyName = "Lawson";

    protected static String familyName = "Lawson";

    static { System.out.println("static block of Super class is initialized"); }
    {System.out.println("non static blocks in super class is initialized");}
}

Output:
static block of Super class is initialized
Lawson



Observation
1. Here class initialization occurs because static field is accessed which is not a compile time constant. had you declare "familyName" compile time constant using final keyword in Java (as shown in commented section) class initialization of super class would not have occurred.

2) Only super class is initialized even though static field is referenced using sub type.

There is another example of class initialization related to interface on JLS which explains clearly that initialization of sub interfaces does not trigger initialization of super interface. I highly recommend reading JLS 14.4 for understating  class loading and initialization in more detail.

That's all on When a class is initialized and loaded in Java. We have seen clear guidelines form JLS regarding class initialization. We have also seen the order on which super type and sub type are initialized and order of initialization for both static and non static fields and blocks in Java.

Most Asked Java Interview Question in Various Software company in year 2012

Hi Friend , i have attended  java interview at many MNC IT company in Noida ,Delhi, Gurgaon, on basis below listed java interview question which asked many times. 


1) About current project that I am working?
2) Current Role & responsibilities in current project
3) Equals&Hascode?why need to implement these methods? How to implement?
4) How will you test for Equals method using Junit?
5) What is Reflex package in java?
5) What are the Java contracts defined to implement Equals&hashcode
6) What is Synchronization? How will you implement synchronization?
7) what is TreeSet?
8) Difference between ConcurrentHashMap and Synchronized Map? what is the best way to implement?
9) What is the easiest way to implement Sorted Set
10) What are the methods in Object class?
11) Difference between String,StringBuffer,StringBuilder
12) If the same path was given to Global Forward & Action Forward in struts config xml then which one will take the priority.
13) Struts Can have Multiple Struts_Config.xml
14) Where to declare and how declare multiple Struts config xmls
15) How to transfer the bean values between multiple jsps going throw action classes.
16) What is IOC?
17) What is Dependency Injection?
18) What are kinds of Dependency injection in Spring.
19) How to define Criteria?
20) What is SessionFactory?
21) How to get session Ojbect?
22) What is ThreadLocal?
24) what is XETransaction?
25) Difference between Pessimistic Concurrency Control and Optimistic Concurrency Control?
26) Implementation of Optimistic Concurrency Control?
27) what is difference between Local Transaction and Distributed Transaction.

For Answer read www.newserverside.blogspot.com regularly

check parentheses in a string / expression are balanced using Regex / Stack . Find Brackets are matched or not in JAVA Program

One of the interesting  java program given below  that may be asked in core java interview or the same may be given to   students to solve at practical labs

         Write a java program that reads a string (expression) from standard input and find  whether its parentheses "(" , ")" , brackets "[", "]"  and  Braces "{", "}"    are properly balanced or not.  i.e. Every open parentheses"("  , braces "{" and brackets "["  should have closing  parenthesis  ")" , braces "}" and brackets "]" respectively in the right order .   For example, the  program will give output
   true for the following input
              1.   ((29*12)+(54+22))
               2.  {[()()]()}
               3. ((([]{}))((())))
     and false for the following
               1.  [(]).
                2. ((())))
                3.  ((29*12*([5*5+7]*5)) + ((54+22))

Please assume that , '(' , '{' , '[' are open characters and ')' , '}' , ']'  are closing characters . Let us solve the above problem now.
 .
 Method I :   Best way to solve the above problem is using stack data structure .  As we know , stack is a  storage mechanishm that works on  Last -in-First-Out (LIFO) that means  the last item stored on the stack  is the first one to be removed.  For more on Stack , please visit my earlier tutorial Stack a FIFO data structure

How to solve the above problem using stack ?
    1) Read the input string (expression ) from the keyboard
   2) Create a stack object to accept  character only.
    3. Traverse the input string / expression
         a) If the current character is a open (left )  parenthesis '('  or brace '{'  or bracket '['  then push the corresponding closing (right) character (i.e. ')' , '}' , ']')  to the stack. You can push the open chracters.   I have Pushed the closing charaters to the stack instead of left to  reduce the little bit lines of logic.
         b) If the current character is a closing (right) parenthesis ')'  , brace '}' and bracket ']' ,
                         i)  check for the stack is empty , if it is empty , then the parentheses are not balanced  because there is no open characters for the corresponding closing charaters.
                   ii)  if stack is not empty , then check the current character with top character  (get the top character using peek() )  in the stack . If both are equal, then pop the character from the stack and check for the next character.
  4)  Once the traversal of the expression is completed , check for the stack is empty or not . If stack is empty , then parentheses are balanced otherwise not balanced.

The code is as follows .



import java.util.Stack;

import java.util.Scanner;

public class Parentheses1 {



  public static boolean isBalanced1(String exp)  {


      Stack<Character> stack = new Stack<Character>();

 for (int i=0; i<exp.length(); i++) {

  char c = exp.charAt(i);

  switch (c) {

  case '{' : stack.push('}'); break;

  case '(' : stack.push(')'); break;

  case '[' : stack.push(']'); break;

  case ']' : case ')' : case '}' :

   if (stack.isEmpty())

      return false;

   else   if (stack.peek() == c) {

   stack.pop();

   }

   break;

  default : break;

  }

 }

 return stack.isEmpty();

      }

Some of the other tries to solve the above program.

Method II using Regular expression (Regex)  . You can also try without using regex . I have used very simple  regex .  Steps to solve the above problem  are as follows.

1. Remove all characters like digits , operators, etc  except '(', ')' , '{', '}' , '[' , ']' in the expression.
 2. Replace  every occurrence of  '()' , '{}' , '[]'  in the string  with empty string ("")  (i.e  removal of characters)
 3. Repeat the step 2 ,  until you find that nothing has been replaced .
 4. Now check for the expression  is empty or not. If the string is empty , then  parentheses are perfectly  balanced  , otherwise not.

Code is as follows



public static boolean isBalanced2(String exp)  {

String temp="";

while (exp.trim().length() > 0  )

{

exp=exp.replaceAll("[^\\(\\)\\[\\]\\{\\}]", "") ;

exp=exp.replaceAll("\\(\\)", "");

exp=exp.replaceAll("\\{\\}", "");

exp=exp.replaceAll("\\[\\]", "");


if (exp.trim().equals(temp)) break;

temp=exp;

}

if ( exp.trim().length() ==0) return true;

else {

    System.out.println("Unmatched / Unbalanced characters " + exp);

  return false;

     }

   }

Method III :  Using counter . But this method  is not suitable for all situations .   It just checks , whether the expression has equal number of opening and  closing  parentheses or  brackets or braces and does not check the order. For example, consider the following  expression.
  ([{)}]
 The above expression  has the equal number of opening and closing parentheses / brackets / braces . But it is  not in the right order. The right order may be  ([{}])
 This method may be suitable , if you use either   parentheses or  brackets or  braces in the expression.  eg.   ((()(()()))) . Otherwise  the order should be correct, if you use all .

Steps :
              1. Initialize three counters to 0 , one for parentheses, one for braces , and one for bracket
              2. Traverse the expression by a single  character at a time.
  a) If the current character is '(' , '{' , '[' , then   increment the respective counter by one
  b) If the current character is  ')', '}' , ']' , then decrease one from the respective counter variable.
               3. Check whether all the counters are zero or not. If all counters are having 0 , then the parentheses are balanced  , otherwise not . Please always remember limitation using this method.

 Code is as follows.



public static boolean isBalanced3(String exp)  {

int c1=0, c2=0,c3=0;

 for (int i=0; i<exp.length(); i++) {

  char c = exp.charAt(i);

  switch (c) {

  case '{' : c1++; break;

  case '(' : c2++; break;

  case '[' : c3++; break;

  case '}' : c1--; break;

  case ')' : c2--; break;

  case ']' : c3--; break;

  default : break;

  }

     }


if(c1==0 && c2==0 && c3==0)  return true;

else  return false;


      } 

//Main Method to call the above three methods



public static void main(String[] args) {


Scanner sc=new Scanner(System.in).useDelimiter("\n");;
  

String s = sc.next();


 System.out.println("Balanced checking using stack " + isBalanced1(s));

 System.out.println("Balanced checking using regex " + isBalanced2(s));

 System.out.println("Balanced checking using counter " + isBalanced3(s));

    }