Core Java

This page contains extensive list of core java interview questions and answers for mid-senior and senior levels.

1. Can Java thread object invoke start method twice ?

No. We cannot invoke start() method twice. It will throw an exception – java.lang.IllegalThreadStateException

Consider below example

package com.roytuts.java.threads;

public class ThreadInvokeStartTwice extends Thread {

	@Override
	public void run() {
		System.out.println("Thread running : " + Thread.activeCount());
	}

	public static void main(String[] args) {
		ThreadInvokeStartTwice threadInvokeStartTwice = new ThreadInvokeStartTwice();
		threadInvokeStartTwice.start();
		threadInvokeStartTwice.start(); //Exception at this line
	}

}

Output

Exception in thread "main" Thread running : 2
java.lang.IllegalThreadStateException
	at java.lang.Thread.start(Thread.java:705)
	at com.roytuts.java.threads.ThreadInvokeStartTwice.main(ThreadInvokeStartTwice.java:13)

2. What is the difference between Collection and Collections ?

Collection

It is an interface. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

For more information please read http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html

Collections

It is a class. This class consists exclusively of static methods that operate on or return collections. It contains various utility methods like sort(), addAll(), copy() etc.

For more information please read http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html

3. How to search an element in ArrayList ?

Please refer to the example Searching an element in Java ArrayList

4. String vs StringBuffer vs StringBuilder ?

String

It is an immutable object, i.e., once created cannot be changed.
String is a thread safe object as it is an immutable object, i.e., multiple threads cannot access String object simultaneously.
The String object is stored in constant pool area of the String.
Once assigned a value to String object cannot be changed

String s = "Hello, World!"; // The object s is stored in constant pool and its value can not be modified.
s = "Welcome to Hello World!" //new "Welcome to Hello World!" String object is created in constant pool and referenced by the s variable

“Hello, World!” still exists in constant pool area of the String but we lost the reference.

StringBuffer

It is a mutable object, i.e., we can change its value.
The object created through StringBuffer is stored in heap.
It provides synchronized methods and it provides thread safety; so multiple threads can access StringBuffer object simultaneously, though only one thread is allowed to access at a time.
As all methods in StringBuffer are synchronized, so it has drawback on performance and slower than StringBuilder and String object.
The object created through StringBuffer can be changed to String object using toString() method.

StringBuffer stringBuffer = new StringBuffer("Hello, World!");

StringBuilder

It is a mutable object, i.e., we can change its value.
The object created through StringBuilder is stored in heap.
It does not provide any synchronized method, that means it does not provide thread safety; so multiple threads cannot access StringBuilder object simultaneously.
No method in StringBuilder is synchronized, so it is faster that StringBuffer.
The object created through StringBuilder can be changed to String object using toString() method.

StringBuilder stringBuilder = new StringBuilder("Hello, World!");

An example : 

package com.roytuts.java.string;

public class StringStringBufferStringBuilder {

	public static void main(String[] args) {
		String s = "Hello, World!";
		System.out.println(s);
		s = "Welcome to Hello World!";
		System.out.println(s); // we lost reference to "Hello, World!"
		System.out.println();

		StringBuffer stringBuffer = new StringBuffer("Hello, World!");
		System.out.println(stringBuffer);
		System.out.println(stringBuffer.toString()); // convert to String object
		stringBuffer = new StringBuffer("Welcome to Hello World!");
		System.out.println(stringBuffer);
		System.out.println();

		StringBuilder stringBuilder = new StringBuilder("Hello, World!");
		System.out.println(stringBuilder);
		System.out.println(stringBuilder.toString()); // convert to String
														// object
		stringBuilder = new StringBuilder("Welcome to Hello World!");
		System.out.println(stringBuilder);
	}

}

Output

Hello, World!
Welcome to Hello World!

Hello, World!
Hello, World!
Welcome to Hello World!

Hello, World!
Hello, World!
Welcome to Hello World!

5. ClassNotFoundException vs NoClassDefinitionFoundException ?

ClassNotFoundException

Thrown when an application tries to load in a class through its string name using:

The forName method in class Class.
The findSystemClass method in class ClassLoader .
The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

For ClassNotFoundException, it appears that it may stem from trying to make reflective calls to classes at runtime, but classes the program is trying to call do not exist.

ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable.

Example :

package com.roytuts.classexception;

public class ClassNotFoundExceptionTest {

	public static void main(String[] args) {
		try {
			Class.forName("ClassA"); //No definition for ClassA exists
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}

Output

java.lang.ClassNotFoundException: ClassA
	at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at com.roytuts.classexception.ClassNotFoundExceptionTest.main(ClassNotFoundExceptionTest.java:7)

NoClassDefinitionFoundException 

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition exist when the currently executing class was compiled, but the definition can no longer be found.

So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.

NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find.

Example :

package com.roytuts.classexception;

import javax.jms.ConnectionFactory;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class NoClassDefinitionFoundExceptionTest {

	public static void main(String[] args) {
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_BROKER_URL);
	}

}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
	ConnectionFactory cannot be resolved to a type
	ActiveMQConnectionFactory cannot be resolved to a type
	ActiveMQConnection cannot be resolved to a variable

	at com.roytuts.classexception.NoClassDefinitionFoundExceptionTest.main(NoClassDefinitionFoundExceptionTest.java:11)

6. What are different class loaders ?

Please go through http://www.oracle.com/technetwork/articles/javase/classloaders-140370.html