Java Interview Questions And Answers: Part-3

Java, Java Interview Questions And Answers, java interview questions and answers for freshers and experienced

For More Java Interview Questions: Part-2  Click here.

 

101. Can member inner classes have static members in them?

No, member inner classes can’t have static members in them. They can have only non-static members. But, exception being the static and final field, i.e. member inner class can have static and final field, but it must be initialized at the time of declaration only.

 

102. Can we access all the members of outer class inside a member inner class?

Yes, we can access all the members, both static and non-static, of outer class inside a member inner class.

 

103. Can we declare local inner classes as static?

No. Local inner classes can’t be static.

 

104. Can we use local inner classes outside the method or block in which they are defined?

No. Local inner classes are local to method or block in which they are defined. We can’t use them outside the method or block in which they are defined.

 

105. Can we declare local inner classes as private or protected or public?

No. Local inner classes can’t be declared with access modifiers. They can’t be private or protected or public.

 

106. What is the condition to use local variables inside a local inner class?

The condition is that local variables must be final. We can’t use non-final local variables inside a local inner class.

 

107. What are anonymous inner classes in java?

Anonymous inner classes are the inner classes without a name. You can instantiate an anonymous inner class only once.

 

108. What is the main difference between static and non-static nested classes?

The main difference between static and non-static nested classes is that you need not to instantiate the outer class to access static nested classes. But, to access non-static nested classes, you have to instantiate the outer class.

 

109. What is the difference between final, finally and finalize in java?

final keyword: final is a keyword which is used to make a variable or a method or a class as “unchangeable“.

  1. A variable which is declared as final, its value cannot be changed once it is initialized.

          final int x=50;

          x = 100; //compile time error, value cannot be changed

  1. A method declared as final cannot be overridden or modified in the sub class.
  2. A class declared as final cannot be extended.

finally Block: finally is a block which is used for exception handling along with try and catch blocks. finally block is always executed whether exception is raised or not and raised exception is handled or not. Most of time, this block is used to close the resources like database connection, I/O resources etc.

finalize() Method: finalize() method is a protected method of java.lang.Object class. It is inherited to every class you create in java. This method is called by garbage collector thread before an object is removed from the memory. finalize() method is used to perform some cleanup operations on an object before it is removed from the memory.

 

110. What is the difference between throw, throws and Throwable?

throw: throw is a keyword in java which is used to throw an exception manually. Using throw keyword, you can throw an exception from any method or block. But, that exception must be of type java.lang.Throwable class or its sub classes.

class  demo{

void mymethod() throws Exception    {

        Exception e = new Exception();

        throw e;            //throwing an exception using 'throw'

    }

}

 

throws: throws is also a keyword in java which is used in the method signature to indicate that this method may throw mentioned exceptions. The caller to such methods must handle the mentioned exceptions either using try-catch blocks or using throws keyword.

return_type method_name(parameter_list) throws exception_list
{
     //some statements
}

 

Throwable: Throwable is a super class for all types of errors and exceptions in java. This class is a member of java.lang package. Only instances of this class or its sub classes are thrown by the java virtual machine or by the throw statement. The only argument of catch block must be of this type or its sub classes. If you want to create your own customized exceptions, then your class must extend this class.

class MyException extends Throwable
{
           //Customized Exception class
}

 

111. Difference between Error vs. Exception?

Both java.lang.Error and java.lang.Exception classes are sub classes of java.lang.Throwable class, but there exist some significant differences between them. java.lang.Error class represents the errors which are mainly caused by the environment in which application is running. For example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack overflows.

Whereas java.lang.Exception class represents the exceptions which are mainly caused by the application itself. For example, NullPointerException occurs when an application tries to access null object or ClassCastException occurs when an application tries to cast incompatible class types.

Errors

Exceptions

Errors in java are of type java.lang.Error.

Exceptions in java are of type java.lang.Exception.

All errors in java are unchecked type.

Exceptions include both checked as well as unchecked type.

Errors happen at run time. They will not be known to compiler.

Checked exceptions are known to compiler whereas unchecked exceptions are not known to compiler because they occur at run time.

It is impossible to recover from errors.

You can recover from exceptions by handling them through try-catch blocks.

Errors are mostly caused by the environment in which application is running.

Exceptions are mainly caused by the application itself.

Examples :
java.lang.StackOverflowError, java.lang.OutOfMemoryError

Examples :
Checked Exceptions : SQLException, IOException
Unchecked Exceptions : ArrayIndexOutOfBoundException, ClassCastException, NullPointerException

 

112. Difference between ClassNotFoundException vs. NoClassDefFoundError

ClassNotFoundException

NoClassDefFoundError

It is an exception. It is of type java.lang.Exception.

It is an error. It is of type java.lang.Error.

It occurs when an application tries to load a class at run time which is not updated in the classpath.

It occurs when java runtime system doesn’t find a class definition, which is present at compile time, but missing at run time.

It is thrown by the application itself. It is thrown by the methods like Class.forName(), loadClass() and findSystemClass().

It is thrown by the Java Runtime System.

It occurs when classpath is not updated with required JAR files.

It occurs when required class definition is missing at run time.

 

113. What is an exception?

Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of the program. This exception must be handled properly. If it is not handled, program will be terminated abruptly.

 

114. How the exceptions are handled. Explain exception handling mechanism?

Exceptions in java are handled using try, catch and finally blocks.

try block: The code or set of statements which are to be monitored for exception are kept in this block.

catch block: This block catches the exceptions occurred in the try block.

finally block: This block is always executed whether exception is occurred in the try block or not and occurred exception is caught in the catch block or not.

 

115. Can we keep other statements in between try, catch and finally blocks?

No. We shouldn’t write any other statements in between try, catch and finally blocks. They form a one unit.

 

116. Can we write only try block without catch and finally blocks?

No, it shows compilation error. The try block must be followed by either catch or finally block. You can remove either catch block or finally block but not both.

 

117. There are three statements in a try block – statement1, statement2 and statement3. After that there is a catch block to catch the exceptions occurred in the try block. Assume that exception has occurred in statement2. Does statement3 get executed or not?

No. Once a try block throws an exception, remaining statements will not be executed. Control comes directly to catch block.

 

118. What is unreachable catch block error?

When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to most general ones, i.e. sub classes of Exception must come first and super classes later. If you keep super classes first and sub classes later, compiler will show unreachable catch block error.

 

119. What are run time exceptions, give example?

The exceptions which occur at run time are called as run time exceptions. These exceptions are unknown to compiler. All sub classes of java.lang.RuntimeException and java.lang.Error are run time exceptions. These exceptions are unchecked type of exceptions. For example, NumberFormatException, NullPointerException, ClassCastException, ArrayIndexOutOfBoundException, StackOverflowError etc.

 

120. What is OutOfMemoryError?

OutOfMemoryError is the sub class of java.lang.Error which occurs when JVM runs out of memory.

 

121. What are checked and unchecked exceptions?

Checked exceptions are the exceptions which are known to compiler. These exceptions are checked at compile time only. Hence the name checked exceptions. These exceptions are also called compile time exceptions. Because, these exceptions will be known during compile time.

Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions occur only at run time. These exceptions are also called as run time exceptions. All sub classes of java.lang.RuntimeException and java.lang.Error are unchecked exceptions.

 

122. Can we keep the statements after finally block If the control is returning from the finally block itself?

No, it gives unreachable code error. Because, control is returning from the finally block itself. Compiler will not see the statements after it. That’s why it shows unreachable code error.

 

123. Does finally block get executed If either try or catch blocks are returning the control?

Yes, finally block will be always executed no matter whether try or catch blocks are returning the control or not.

 

124. Can we throw an exception manually? If yes, how?

Yes, we can throw an exception manually using throw keyword.

try
{
NumberFormatException ex = new NumberFormatException();    //Creating an object to NumberFormatException explicitly

throw ex;        //throwing NumberFormatException object explicitly using throw keyword
}
catch(NumberFormatException ex)
{
    System.out.println("object will be caught here");
}

 

 

125. What is re-throwing an exception?

Exceptions raised in the try block are handled in the catch block. If it is unable to handle that exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.

try
{
    String s = null;
    System.out.println(s.length());   //This statement throws NullPointerException
}
catch(NullPointerException ex)
{
    System.out.println("NullPointerException is caught here");
    throw ex;     //Re-throwing NullPointerException
}

 

126. Why it is always recommended that cleanup operations like closing the DB resources to keep inside a finally block?

Because finally block is always executed whether exceptions are raised in the try block or not and raised exceptions are caught in the catch block or not. By keeping the cleanup operations in finally block, you will ensure that those operations will be always executed irrespective of whether exception is occurred or not.

 

127. What is ClassCastException?

ClassCastException is a RuntimeException which occurs when JVM unable to cast an object of one type to another type.

 

128. What is StackOverflowError?

StackOverflowError is an error which is thrown by the JVM when stack overflows.

 

129. Can we override a super class method which is throwing an unchecked exception with checked exception in the sub class?

No. If a super class method is throwing an unchecked exception, then it can be overridden in the sub class with same exception or any other unchecked exceptions but cannot be overridden with checked exceptions.

 

130. What are chained exceptions?

In an application, one exception throws many exceptions, i.e. one exception causes another exception and that exception causes another exception thus forming chain of exceptions. It is better to know where the actual cause of the exception lies. This is possible with chained exceptions feature of the Java.

Chained exceptions are introduced from JDK 1.4. To implement chained exceptions in java, two new constructors and two new methods are added in the Throwable class. They are,

Constructors of Throwable class which support chained exceptions:

1) Throwable (Throwable cause) à where cause is the exception that causes the current exception.

2) Throwable (String msg, Throwable cause) à where msg is the exception message and cause is the exception that causes the current exception.

Methods of Throwable class which support chained exceptions:

1) getCause() method: This method returns actual cause of an exception.

2) initCause(Throwable cause) method: This method sets the cause for the calling exception.

 

131. Which class is the super class for all types of errors and exceptions in java?

java.lang.Throwable is the super class for all types of errors and exceptions in java.

 

132. What is the use of printStackTrace() method?

printStackTrace() method is used to print the detailed information about the exception occurred.

 

133. What is ArrayStoreException? When you will get this exception?

ArrayStoreException is a run time exception which occurs when you try to store non-compatible element in an array object. The type of the elements must be compatible with the type of array object. For example, you can store only string elements in an array of strings. If you try to insert integer element in an array of strings, you will get ArrayStoreException at run time.

 

134. Can you pass the negative number as an array size?

No. You can’t pass the negative integer as an array size. If you pass, there will be no compile time error but you will get NegativeArraySizeException at run time.

 

135. Can you change the size of the array once you define it? OR Can you insert or delete the elements after creating an array?

No. You can’t change the size of the array once you define it. You cannot insert or delete the elements after creating an array. Only you can do is change the value of the elements.

 

136. What is an anonymous array? Give example?

Anonymous array is an array without reference. For example,

System.out.println(new int[]{1,2,3,4,5}.length); //output : 5

 

137. What is the difference between int[] a and int a[]?

Both are the legal methods to declare the arrays in java.

 

138. There are two array objects of int type. One is containing 100 elements and another one is containing 10 elements. Can you assign array of 100 elements to an array of 10 elements?

Yes, you can assign array of 100 elements to an array of 10 elements provided they should be of same type. While assigning, compiler checks only type of the array not the size.

int[] a = new int[10];

int[] a = new int[100];                                          

a = b;  //Compiler checks only type, not the size

 

139. “int a[] = new int[3]{1, 2, 3}” – is it a legal way of defining the arrays?

No. You should not mention the size of the array when you are providing the array contents.

 

140. What are the differences between Array and ArrayList?

Array

ArrayList

Arrays are of fixed length.

ArrayList is of variable length.

You can’t change the size of the array once you create it.

Size of the ArrayList grows and shrinks as you add or remove the elements.

Array does not support generics.

ArrayList supports generics.

You can use arrays to store both primitive types as well as reference types.

You can store only reference types in an ArrayList.

 

141. What are the different ways of copying an array into another array?

There are four methods available in java to copy an array.

1) Using for loop

2) Using Arrays.copyOf() method

3) Using System.arraycopy() method

4) Using clone() method

 

142. What are jagged arrays? Give example?

Jagged arrays in java are the arrays containing arrays of different length. Jagged arrays are also multidimensional arrays. They are also called as ragged arrays.

// Declaring 2-D array with 2 rows
int arr[][] = new int[2][];

// Making the above array Jagged
// First row has 3 columns
arr[0] = new int[3];

// Second row has 2 columns
arr[1] = new int[2];

 

143. How do you check the equality of two arrays?

You can use Arrays.equals() method to compare one dimensional arrays and to compare multidimensional arrays, use Arrays.deepEquals() method.

 

144. What is ArrayIndexOutOfBoundsException? When it occurs?

ArrayIndexOutOfBoundsException is a run time exception which occurs when your program tries to access invalid index of an array, i.e. negative index or index higher than the size of the array.

 

145. How do you sort the array elements?

You can sort the array elements using Arrays.sort() method. This method internally uses quick sort algorithm to sort the array elements.

 

146. While creating the multidimensional arrays, can you specify an array dimension after an empty dimension?

No. You can not specify an array dimension after an empty dimension while creating multidimensional arrays. It gives compile time error.

int[][][] a = new int[][5][];    //Compile time error
int[][][] b = new int[5][][5];   //Compile time error
int[][][] c = new int[][5][5];   //Compile time error

 

147. How do you search an array for a specific element?

You can search an array to check whether it contains the given element or not using Arrays.binarySearch() method. This method internally uses binary search algorithm to search for an element in an array.

 

148. What value does array elements get, if they are not initialized?

They get default values.

 

149. What are the drawbacks of the arrays?

The main drawback of the arrays is that arrays are of fixed size. You can’t change the size of the array once you create it. Therefore, you must know how many elements you want in an array before creating it. You can’t insert or delete the elements once you create an array. Only you can do is change the value of the elements.

 

150. Where does array stored in memory?
Array is created in heap space of JVM memory. Since array is object in Java, even if you create array locally inside a method or block, object is always allocated memory from heap.

 

For More Java Interview Questions: Part-4  Click here.