Java Interview Questions

Can you declare a class as ‘private’?

No, if we declare a class as private, then it is not available to java compiler and hence a compile time error occurs. But, inner class can be declared as private.

What are static methods?

Static methods are methods which do not act upon the instance variables of a class. Static methods are declared as ‘static’.

Reason: JVM executes the static methods and then only it creates the objects.

What are static blocks?

A static block is a block of statements declared as ‘static’,some thing like this:

static{

statements;

}

JVM executes a static block on a highest priority basis. This means JVM first goes to static block even before it looks for the main() method in the program.

Example:

Class test{

static{

system.out.println(“static block”);

}

public static void main(string args[])

{

system.out.println(“static method”);

}

}

Output: static block

static  method

Is it possible to compile and run a java program without writing main() method?

Yes, it is possible by using a static block in the java program.

Object creation in java

We know that the class code along with method code is stored in “method area” of the JVM. When an object is created, the memory is allocated on ‘heap‘. After creation of an object, JVM produces a unique identifier number for the object from the memory address of the object. This reference number is called hashcode number. 

To know the hashcode number of an object, we can use hashcode() method of object class as shown here..

Employee el=new Employee();

System.out.println(e1.hashcode());

Java Heap

The Java Heap Space is the memory “container” of you runtime Java program which provides to your Java program the proper memory spaces it needs (Java Heap, Native Heap) and managed by the JVM itself.

Your Java program life cycle typically looks like this:

– Java program coding (via Eclipse IDE etc.) e.g. HelloWorld.java
– Java program compilation (Java compiler or third party build tools such as Apache Ant, Apache Maven..) e.g. HelloWord.class
– Java program start-up and runtime execution e.g. via your HelloWorld.main() method

The Java Heap space is mainly applicable and important for the third step: runtime execution. For the HotSpot VM, the Java Heap Space is split in 3 silos:

– Java Heap for short & long lived objects (YoungGen & OldGen spaces)
– PermGen space
– Native Heap

Now let’s dissect your HelloWorld.class program so you can better understand.

– At start-up, your JVM will load and cache some of your static program and JDK libraries to the Native Heap, including native libraries, Mapped Files such as your program Jar file(s), Threads such as the main start-up Thread of your program etc.
– Your JVM will then store the “static” data of your HelloWorld.class Java program to the PermGen space (Class metadata, descriptors..)
– Once your program is started, the JVM will then manage and dynamically allocate the memory of your Java program to the Java Heap (YoungGen & OldGen). This is why it is so important that you understand how much memory your Java program needs to you can properly fine-tuned the capacity of your Java Heap controlled via –Xms & -Xmx JVM parameters. Profiling, Heap Dump analysis allow you to determine your Java program memory footprint
– Finally, the JVM has to also dynamically release the memory from the Java Heap Space that your program no longer need; this is called the garbage collection process. This process can be easily monitored via the JVM verbose GC or a monitoring tool of your choice such as JConsole

JVM Architecture with a diagram

Hello pal,

Most of the java beginners donno what is JVM and how the architecture of it will be i.e., JVM Inside..Lets explore what it is..

What is JVM??

In simple words,

  • Java Virtual Machine is not a real hardware machine but a software layer which resembles an hardware platform.
  • JVM converts java byte code into machine language and executes it
  • The byte code can be executed on any platform where jvm exists.

jvm

JVM Inside(JVM Architecture)

JVM-arc1

1. Class loader sub system: JVM’s class loader sub system performs 3 tasks
a. It loads .class file into memory.
b. It verifies byte code instructions.
c. It allots memory required for the program.

2. Run time data area: This is the memory resource used by JVM and it is divided into 5 parts
a. Method area: Method area stores class code and method code.
b. Heap: Objects are created on heap.
c. Java stacks: Java stacks are the places where the Java methods are executed. A Java stack contains frames. On each frame, a separate method is executed.
d. Program counter registers: The program counter registers store memory address of the instruction to be executed by the micro processor.
e. Native method stacks: The native method stacks are places where native methods (for example, C language programs) are executed. Native method is a function, which is written in another language other than Java.

3. Native method interface: Native method interface is a program that connects native methods libraries (C header files) with JVM for executing native methods.

4. Native method library: holds the native libraries information.

5. Execution engine: Execution engine contains interpreter and JIT compiler, which covert byte code into machine code. JVM uses optimization technique to decide which part to be interpreted and which part to be used with JIT compiler. The HotSpot represent the block of code executed by JIT compiler.

StringBuffer Class in Java

StringBuffer:

The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.

Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with out leaving behind a lot of new unused objects.

The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).

It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

Difference: String class objects are immutable and hence their contents cannot be modified. StringBuffer class objects are mutable, so they can be modified. The reason is that StringBuffer is mutable and can expand dynamically in memory. To store characters, we can use append() method or insert() method like

object.append(“Hello”); // add “Hello” to object

object.insert(0,”Hello”); // insert “Hello” starting from 0th position in object.

Example:

public class Test{

    public static void main(String args[]){
       StringBuffer sBuffer = new StringBuffer(" test");
       sBuffer.append(" String Buffer");
       System.ou.println(sBuffer);  
   }
}

This would produce the following result:

test String Buffer

StringBuffer Methods:

Here is the list of important methods supported by StringBuffer class:

SN Methods with Description
1 public StringBuffer append(String s)
Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings etc.
2 public StringBuffer reverse()
The method reverses the value of the StringBuffer object that invoked the method.
3 public delete(int start, int end)
Deletes the string starting from start index until end index.
4 public insert(int offset, int i)
This method inserts an string s at the position mentioned by offset.
5 replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with characters in the specified String.

Here is the list of other methods (Except set methods ) which are very similar to String class:

SN Methods with Description
1 int capacity()
Returns the current capacity of the String buffer.
2 char charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
3 void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum.
4 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this string buffer into the destination character array dst.
5 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
6 int indexOf(String str, int fromIndex) 
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
7 int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
8 int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
9 int length()
Returns the length (character count) of this string buffer.
10 void setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch.
11 void setLength(int newLength)
Sets the length of this String buffer.
12 CharSequence subSequence(int start, int end) 
Returns a new character sequence that is a subsequence of this sequence.
13 String substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.The substring begins at the specified index and extends to the end of the StringBuffer.
14 String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.
15 String toString()
Converts to a string representing the data in this string buffer.

In Simple words:

String is used to manipulate character strings that cannot be changed (read-only and immutable).

StringBuffer is used to represent characters that can be modified.

Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.

You can also use StringBuilder which is similar to StringBuffer except it is not synchronized. The maximum size for either of these is Integer.MAX_VALUE (231 – 1 = 2,147,483,647) or maximum heap size divided by 2

Wrapper Classes in Java

Wrapper classes:

Introduction

Java is an object-oriented language and can view everything as an object. A simple file can be treated as an object (with java.io.File), an address of a system can be seen as an object (with java.util.URL), an image can be treated as an object (with java.awt.Image) and a simple data type can be converted into an object (with wrapper classes). This tutorial discusses wrapper classes. Wrapper classes are used to convert any data type into an object.

The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language. For example, upto JDK1.4, the data structures accept only objects to store. A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

What are Wrapper classes?

As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.

Observe the following conversion.

int k = 100;
Integer it1 = new Integer(k);

The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object it1.

int m = it1.intValue();
System.out.println(m*m); // prints 10000

intValue() is a method of Integer class that returns an int data type.

List of Wrapper classes

In the above code, Integer class is known as a wrapper class (because it wraps around int data type to give it an impression of object). To wrap (or to convert) each primitive data type, there comes a wrapper class. Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.

 

Primitive data type Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Following is the hierarchy of the above classes.

ss52

All the 8 wrapper classes are placed in java.lang package so that they are implicitly imported and made available to the programmer. As you can observe in the above hierarchy, the super class of all numeric wrapper classes is Number and the super class for Character and Boolean is Object. All the wrapper classes are defined as final and thus designers prevented them from inheritance.

Importance of Wrapper classes

There are mainly two uses with wrapper classes.

  1. To convert simple data types into objects, that is, to give object form to a data type; here constructors are used.
  2. To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

The following program expresses the style of converting data type into an object and at the same time retrieving the data type from the object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class WrappingUnwrapping
{
  public static void main(String args[])
  {				                  //  data types
    byte grade = 2;
    int marks = 50;
    float price = 8.6f;       		          // observe a suffix of <strong>f</strong> for float
    double rate = 50.5;
 		                                  // data types to objects		
    Byte g1 = new Byte(grade);                    // wrapping  
    Integer m1 = new Integer(marks);
    Float f1 = new Float(price);
    Double r1 = new Double(rate);
                                                                    // let us print the values from objects	
    System.out.println("Values of Wrapper objects (printing as objects)");
    System.out.println("Byte object g1:  " + g1);
    System.out.println("Integer object m1:  " + m1);
    System.out.println("Float object f1:  " + f1);
    System.out.println("Double object r1:  " + r1);
	        // objects to data types (retrieving data types from objects)
    byte bv = g1.byteValue();                 // unwrapping 
    int iv = m1.intValue();
    float fv = f1.floatValue();
    double dv = r1.doubleValue();
                                                                    // let us print the values from data types	
    System.out.println("Unwrapped values (printing as data types)");
    System.out.println("byte value, bv: " + bv);
    System.out.println("int value, iv: " + iv);
    System.out.println("float value, fv: " + fv);
    System.out.println("double value, dv: " + dv);
  }
}

ss16
As you can observe from the screenshot, constructors of wrapper classes are used to convert data types into objects and the methods of the form XXXValue() are used to retrieve back the data type from the object.

More about Java

Name Convention
class name should begin with uppercase letter and be a noun e.g.String,System,Thread etc.
Interface name should begin with uppercase letter and be an adjective (whereever possible). e.g. Runnable,ActionListener etc.
method name should begin with lowercase letter and be a verb. e.g. main(),print(),println(),actionPerformed() etc.
variable name should begin with lowercase letter e.g. firstName,orderNumber etc.
package name should be in lowercase letter. e.g. java,lang,sql,util etc.
constants name should be in uppercase letter. e.g. RED,YELLOW,MAX_PRIORITY etc.

Instance variable

A variable that is created inside the class but outside the method, is known as instance variable.Instance variable doesn’t get memory at compile time.It gets memory at runtime when object(instance) is created.That is why, it is known as instance variable.

Do u know why we declare static for main method? Whats use of it? what for static keyword used??

Will let you know clearly now..

class First

{

public static void main(string args[])

{

First obj = new First();

}

}

By looking at the code, we can understand that an object could be created only after calling the main() method.But for calling the main() method, first of all we require an object. Now, how is it possible to create an object before calling the main() method? So, we should call the main() method without creating an object. Such methods are called static methods and should be declared as static.

Static methods are methods, which can be called and executed without creating the objects.Since we want to call main() method without using an object, we should declare main() method as static.

Wrapper classes:

Introduction

Java is an object-oriented language and can view everything as an object. A simple file can be treated as an object (with java.io.File), an address of a system can be seen as an object (with java.util.URL), an image can be treated as an object (with java.awt.Image) and a simple data type can be converted into an object (with wrapper classes). This tutorial discusses wrapper classes. Wrapper classes are used to convert any data type into an object.

The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language. For example, upto JDK1.4, the data structures accept only objects to store. A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

What are Wrapper classes?

As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.

Observe the following conversion.

int k = 100;
Integer it1 = new Integer(k);

The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object it1.

int m = it1.intValue();
System.out.println(m*m); // prints 10000

intValue() is a method of Integer class that returns an int data type.

List of Wrapper classes

In the above code, Integer class is known as a wrapper class (because it wraps around int data type to give it an impression of object). To wrap (or to convert) each primitive data type, there comes a wrapper class. Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.

 

Primitive data type Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Following is the hierarchy of the above classes.

ss52

All the 8 wrapper classes are placed in java.lang package so that they are implicitly imported and made available to the programmer. As you can observe in the above hierarchy, the super class of all numeric wrapper classes is Number and the super class for Character and Boolean is Object. All the wrapper classes are defined as final and thus designers prevented them from inheritance.

Importance of Wrapper classes

There are mainly two uses with wrapper classes.

  1. To convert simple data types into objects, that is, to give object form to a data type; here constructors are used.
  2. To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

The following program expresses the style of converting data type into an object and at the same time retrieving the data type from the object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class WrappingUnwrapping
{
  public static void main(String args[])
  {				                  //  data types
    byte grade = 2;
    int marks = 50;
    float price = 8.6f;       		          // observe a suffix of <strong>f</strong> for float
    double rate = 50.5;
 		                                  // data types to objects		
    Byte g1 = new Byte(grade);                    // wrapping  
    Integer m1 = new Integer(marks);
    Float f1 = new Float(price);
    Double r1 = new Double(rate);
                                                                    // let us print the values from objects	
    System.out.println("Values of Wrapper objects (printing as objects)");
    System.out.println("Byte object g1:  " + g1);
    System.out.println("Integer object m1:  " + m1);
    System.out.println("Float object f1:  " + f1);
    System.out.println("Double object r1:  " + r1);
	        // objects to data types (retrieving data types from objects)
    byte bv = g1.byteValue();                 // unwrapping 
    int iv = m1.intValue();
    float fv = f1.floatValue();
    double dv = r1.doubleValue();
                                                                    // let us print the values from data types	
    System.out.println("Unwrapped values (printing as data types)");
    System.out.println("byte value, bv: " + bv);
    System.out.println("int value, iv: " + iv);
    System.out.println("float value, fv: " + fv);
    System.out.println("double value, dv: " + dv);
  }
}

ss16
As you can observe from the screenshot, constructors of wrapper classes are used to convert data types into objects and the methods of the form XXXValue() are used to retrieve back the data type from the object.

StringBuffer:

The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.

Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with out leaving behind a lot of new unused objects.

The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).

It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

Difference: String class objects are immutable and hence their contents cannot be modified. StringBuffer class objects are mutable, so they can be modified. The reason is that StringBuffer is mutable and can expand dynamically in memory. To store characters, we can use append() method or insert() method like

object.append(“Hello”); // add “Hello” to object

object.insert(0,”Hello”); // insert “Hello” starting from 0th position in object.

Example:

public class Test{

    public static void main(String args[]){
       StringBuffer sBuffer = new StringBuffer(" test");
       sBuffer.append(" String Buffer");
       System.ou.println(sBuffer);  
   }
}

This would produce the following result:

test String Buffer

StringBuffer Methods:

Here is the list of important methods supported by StringBuffer class:

SN Methods with Description
1 public StringBuffer append(String s)
Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings etc.
2 public StringBuffer reverse()
The method reverses the value of the StringBuffer object that invoked the method.
3 public delete(int start, int end)
Deletes the string starting from start index until end index.
4 public insert(int offset, int i)
This method inserts an string s at the position mentioned by offset.
5 replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with characters in the specified String.