Sunday, October 7, 2012

What are some of the new features in latest version of Java


Believe me, this is got to be one of the most common questions across various interviews. Being honest as always pays the dividends here. No fun in saying that you have worked in Java 7, when you haven't.

For the purpose of this post listing below some of the key features (amongst the hundreds released along with )introduced with Java 7


  1. Diamond Operator <> - Gives you the ability to use Generics without declaring the data types both sides of the = operator. E.g. Map> trades = new TreeMap <> ();  instead of Map> trades = new TreeMap> ();
  2. Ability to use String statements with SWITCH - Restricted to just being used with enums and primitives, Java 7 gives us an ability to use switch statements with Strings which is a life saver and helps us to get rid of those long if then else statements.
  3. Numerals with underscore - Again more from a readability perspective you now have an option of declaring 1 million as int temp = 1_000_000 for better readability perspective
  4. Support for extensions in JVM to support dynamic languages

References

Friday, May 13, 2011

In Java when is a singleton not exactly a singleton ?

A wonderful article on Sun/Oracle site, talking about the various situations when a Singleton in Java is actually not a Singleton.


Would highly recommend going through the above article, but the one which actually struck me was that within a given Java VM different classloaders can actually instantiate singletons more than once. E.g. two applications running within a WebSphere Application Server on a Single Java Virtual Machine would instantiate the Singleton (if being used in both the applications) twice as both the applications use their own classloaders wherein the classes loaded by one classloader does not have visibility on the classes loaded by the other classloader.

Sunday, May 1, 2011

In Java what happens when you invoke the run() method directly on a Thread rather than initiating it via Thread.start()

This question can be used to judge the candidate's hands on experience with Java and Threads. Essentially whenever you create your own Thread (either via extending the Thread class or implementing the Runnable interface), you write the logic of the thread in public void run() method and initiate the thread via Thread.start() method which invokes the run method in a separate thread.

Now if you invoke the run() method on the directly, it would still be very well executed but within the thread of the calling class.

Sunday, April 17, 2011

In Java are parameters to methods passed by Value or Passed by reference

Another interesting concept in Java is that whether the parameters to methods are passed by value or passed by reference ?

The correct and sweet answer for this is that everything in Java is passed by value in Java. Period. But it's not as simple as it looks. Let's introspect it further with various possible combinations

Primitives
In Java method invocations, param values are always passed by values, and the same is also demonstrated by the sample code posted below
package com.javainterviewquestion.javaparametercheck;

public class JavaParameterCheck {

public static void main(String args[])
{
JavaParameterCheck javaParamCheck = new JavaParameterCheck();
int a=1;
int b=2;
System.out.println(" Param Values before invoking the method "+a+" and "+b);
javaParamCheck.paramTest(a, b);
System.out.println(" Param Values after invoking the method "+a+" and "+b);
}

public void paramTest(int a, int b)
{
a++;
b++;
}

}

The output of the above sample code is

Param Values before invoking the method 1 and 2
Param Values after invoking the method 1 and 2


Objects

As in Java everything is passed by value , but in case Objects being passed as parameters in the methods the reference of the object is passed by value.Hence any changes done to the object within a method are reflected outside the method too (Only exception being String which is discussed later). E.g. the following code

package com.javainterviewquestion.javaparametercheck;

public class JavaParameterCheck {
public static void main(String args[])
{
JavaParameterCheck javaParamCheck = new JavaParameterCheck();
Employee a = new Employee();
Employee b = new Employee();
b.setName("Second Employee");
System.out.println(" Param Values before invoking the method "+a.getName()+" and "+b.getName());
javaParamCheck.paramTest(a, b);
System.out.println(" Param Values after invoking the method "+a.getName()+" and "+b.getName());
}
public void paramTest(Employee a, Employee b)
{
a.setName("This is first name");
b.setName(" This is second name");
}

}

class Employee
{
String name =" Employee";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

has the following output

Param Values before invoking the method Employee and Second Employee
Param Values after invoking the method This is first name and This is second name


The only exception to the Object are String objects, as String are immutable and any changes to the String result in creation of a new String object (pointing to the new memory location). Hence any changes done to the String objects passed as parameters within the method are not reflected outside the method call. E.g. the following code

package com.javainterviewquestion.javaparametercheck;

public class JavaParameterCheck {
public static void main(String args[])
{
JavaParameterCheck javaParamCheck = new JavaParameterCheck();
String a="First String";
String b="Second String";
System.out.println(" Param Values before invoking the method "+a+" and "+b);
javaParamCheck.paramTest(a, b);
System.out.println(" Param Values after invoking the method "+a+" and "+b);
}
public void paramTest(String a, String b)
{
a=a+"1";
b=b+"2";
}

}

has the following output

Param Values before invoking the method First String and Second String
Param Values after invoking the method First String and Second String

Another confusing scenario while passing Objects as parameters to methods is that what will happen if within the method Objects are reinitialized. In that case since the objects are pointing to a new reference , any changes are not reflected outside the method call. See the code below as sample

package com.javainterviewquestion.javaparametercheck;

public class JavaParameterCheck {
public static void main(String args[])
{
JavaParameterCheck javaParamCheck = new JavaParameterCheck();
Employee a = new Employee();
Employee b = new Employee();
b.setName("Second Employee");
System.out.println(" Param Values before invoking the method "+a.getName()+" and "+b.getName());
javaParamCheck.paramTest(a, b);
System.out.println(" Param Values after invoking the method "+a.getName()+" and "+b.getName());
}
public void paramTest(Employee a, Employee b)
{
a = new Employee();
b = new Employee();
a.setName("This is first name");
b.setName(" This is second name");
}

}

class Employee
{
String name =" Employee";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

The above code gives the output

Param Values before invoking the method Employee and Second Employee
Param Values after invoking the method Employee and Second Employee

Array Of Primitives/Objects
Since array is also an object in java, any changes done in the method are reflected outside the method for primitives as well as Objects. See the below code as sample.

package com.javainterviewquestion.javaparametercheck;

public class JavaParameterCheck {
public static void main(String args[])
{
JavaParameterCheck javaParamCheck = new JavaParameterCheck();
int[] list = {1,2,3};
Employee[] empList = {new Employee(), new Employee(), new Employee()};
String[] stringList = {"a","b","c"};
System.out.println(" Param Values before invoking the method "+list[0]+" and "+list[1]+" and " + empList[0].getName()+" and "+ empList[1].getName()+"and"+stringList[0]+"and"+stringList[1]);
javaParamCheck.paramTest(list,empList,stringList);
System.out.println(" Param Values after invoking the method "+list[0]+" and "+list[1]+" and " + empList[0].getName()+" and "+ empList[1].getName()+"and"+stringList[0]+"and"+stringList[1]);
}
public void paramTest(int[] intlist, Employee[] empList, String[] stringlist)
{
intlist[0]=9;
intlist[1]=10;
empList[0].setName("First name");
empList[1].setName("Second name");
stringlist[0]="First String";
stringlist[1]="Secong Strings";
}

}

class Employee
{
String name =" Employee";

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

The output of the above code would be

Param Values before invoking the method 1 and 2 and Employee and Employeeandaandb
Param Values after invoking the method 9 and 10 and First name and Second nameandFirst StringandSecong Strings

Lists
Here also the behavior would be very much similar to that of Arrays as mentioned above.

Tuesday, April 12, 2011

What are classloaders ? - All About Classloaders

Some related question to this are

  • What are classloaders ?

  • What is the significance of having multiple class loaders in Java ?

  • When multiple web/enterprise J2EE applications are deployed in a single instance of Application Server what role do these multiple classloaders play ?
Classloaders as the name specifies are used for loading classes in Java. Whenever you call the main() method of the Java class the first classs is loaded by the ClassLoader. Bootstrap(primordial) classloader is the minimal classloader which every Java application would be using. The hierachy between the various classloaders in JAVA/J2EE can be displayed as shown below in the diagram.



Class loaders follow a delegation model i.e. they request their parent to load the class (till the top level is reached) and if that does not happen it itself tries to load the class. Classes which are loaded by a classloader are not visible to it's parents or siblings but only to the child. This is how java manages namespace conflicts if multiple applications (using different version of common libraries like log4j, parsers etc.) are loaded in the same instance of the application server.

Monday, April 11, 2011

If an object is stored in a Session and updated will the state be replicated across all the other distributed sessions in the Cluster ?

The simple answer is no. E.g. if you have added "Employee" object in the Session by using the setAttribute and if you update a member of the Employee object e.g. Salary (I really love this part :-) ) , then in that case the update would not be reflected in other Sessions across the cluster.

To ensure that the same happens you would need to invoke the setAttribute method on the Session as this would only trigger the replication to happen across clusters.

Sunday, April 10, 2011

In Java Threads what is difference between the methods sleep, yield and wait ?


  • The sleep method would change the thread to sleep for the amount of time as passed in the parameter. E.g. sleep(1000) would cause the Thread to sleep for 1 second.

  • The wait method would cause the Thread to sleep for the amount of time passed as the parameter, but the Thread could wake up early if it recieves the notify() or notifyAll() method. E.g. if we call the method wait(1000) the Thread goes into sleep for 1 second, but might wake up in 0.5 seconds if it recieves a notify() or notifyAll() call.

  • The yield method changes the state of the object from running to runnable state.
The various possible states of Thread are posted here http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html