java_interview_questions
java_interview_questions
1. What is java?
Java is an object oriented programming language originally developed by Sun Microsystems of U.S.A in 1991 and
released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS and the various versions of UNIX.
1. Patrick Naughton
2. Ed frank
3. Mike Sheridon
4. Chris warth
No, it is partial Object Oriented Programming Language, because here in java everything is an object except
primitive data types. So we can’t say it is pure.
7. What is a JVM?
It is a software/runtime environment/virtual machine which is used to run the java programs
Difference
Explanation:
Base-1 Base-2
Which method I
display () have to inherit,
display ()
ooooof…I can’t
understand
Child
Compiler
• In Java, JVM always calls the main () method by using main method’s class name, so we have to declare
the main method as static.
(Or)
• Static is an access modifier, and we have to declare the main() method as static then only the JVM can call
the main () method directly without any memory allocation(object creation).
40. How many times a class will be loaded into the memory during a program execution?
A class always loads only once during program execution. The loaded class can be used any number of times by
the program.
50. Does the order of public and static declaration matter in main() method?
No. It doesn't matter but void should always come before main ().
51. Can a source file contain more than one class declaration?
Yes, a single source file can contain any number of Class declarations.
57. Can a class not declared by using any access modifier, can be accessible outside it’s package?
No, it’s not possible. Because if u don’t declare by using any access modifier then that class is only accessible
with a package (its scope becomes package private).
Scope Same Samepack non Same pack Other pack child class and other pack non
class subclass sub class sub child class subclass
Private Yes No No No No
Default Yes Yes Yes No No
Protected Yes Yes Yes Yes No
Public Yes Yes Yes Yes Yes
66. I don't want my class to be inherited by any other class. What should I do?
You should declare your class as final. Then the final class can’t be inherited by other (child) classes.
71. Can you give few examples of final classes defined in Java API?
java.lang.String, java.lang.Math, java.lang.System classes are final classes.
75. I want to print "Hello" even before main() is executed. How will you acheive that?
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the
memory and even before the creation of an object. Hence it will be executed before the main() method. And it
will be executed only once.
82. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided
implementation for method m2. Can I create an object of Class C?
No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C
didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be
instantiated.
87. Why is an Interface be able to extend more than one Interface but a Class can't extend more than one
Class?
We know that Java doesn't allow multiple inheritance, because it has a drawback we have discussed in the
above sections so a Class is restricted to extend only one Class. But while implementing multiple inheritance by
using interfaces we can’t face such a problem, that is why an interface can extend any number of interfaces.
92. Which object oriented Concept is achieved by using overloading and overriding?
We can achieve Polymorphism.
94. Can we define private and protected modifiers for variables in interfaces?
No, all the fields and methods of an interface are by default declared as public. So we can’t declare them as
private or protected.
96. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
98. What is the difference between a static and a non-static inner class?
100. Can we create an inner class object outside the outer class?
Yes we can create an inner class object (it may be a static inner class or non-static inner class) outside the outer
class, If it is not declared as private. If the inner class is private we can’t create object outside the outer class.
101. How do you create an object for non-static inner class object outside the outer class?
We can create an object for non-static inner class object outside the outer class only by using outer class object,
so we have to create outer class object first, then we can create inner class object.
Ex: Outer o=new Outer();
Outer. Inner oi=o.new Inner();
102. How do you create an object for non-static inner class outside the outer class?
We can create an object for static inner class outside the outer class directly without using outer class object.
Observe the below example.
Ex: Outer. Inner oi=new Outer. Inner();
103. Can we use this and super keywords in a static block or static method?
We can’t use this or super or <outerclassname>.this within a static method or static block or static inner class.
108. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity
determines whether an expression is evaluated left-to-right or right-to-left.
109. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
111. Which characters may be used as the second character of an identifier, but not as the first character of an
identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first
character of an identifier.
116. When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.
The left operand is an object reference or null value and the right operand is a class, interface, or array type.
121. What is the difference between inner class and nested class?
When a class is defined within another class, then it becomes inner class. If the access modifier of the inner class is
static, then it becomes nested class.
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-
point operations may take place. In numerical promotion, byte, char, and short values are converted to int values.
The int values are also converted to long values, if necessary. The long and float values are converted to double
values, as required.
124. What is the difference between the prefix and postfix forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form
returns the current value of the expression and then performs the increment operation on that value.
We can write a method in child class which is already existed in base class. It is called as method overriding.
126. What are the rules we have to follow at the time of overriding a method
• Method name must be same
• Type, order, and number of parameters must be same
• Return type must be same
• If the base method is public, child method must be public or higher scope
• If the base method throws an exception, child method must throw same type or child type, or nothing.
127. Can a method be overloaded based on different return type but same argument type?
No, because the methods can be called without using their return type in which case there is ambiguity for the
compiler.
A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In
Java it is done via an implicit call to the no-args constructor as the first statement.
132. What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A
continue statement is used to end the current loop iteration and return control to the loop statement.
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;);
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
Object persistence is the ability of an object to record its state in the file this is called data persistence. So it can be
reproduced in the future, perhaps in another environment.
Transient variable doesn’t support serialization? I.e the value existed in the transient variables can’t be converted
into binary stream.
In Java, processes correspond to a running Java Virtual Machine (JVM) whereas threads live within the JVM and
can be created and stopped by the Java application dynamically at runtime.
A scheduler is the implementation of a scheduling algorithm that manages access of processes and threads to some
limited resource like the processor or some I/O channel.
Each Java program is executed within the main thread; hence each Java application has at least one thread.
Example:
public static void main(String[] args)
{ long id = Thread.currentThread().getId();
String name = Thread.currentThread().getName();
out.println(id);
}
Each thread belongs to a group of threads. The JDK class java.lang.ThreadGroup provides some methods to handle
a whole group of Threads. With these methods we can, for example, interrupt all threads of a group or set their
maximum priority.
The priority of a thread is set by using the method setPriority(int). To set the priority to the maximum value, we use
the constant Thread.MAX_PRIORITY and to set it to the minimum value we use the constant
Thread.MIN_PRIORITY because these values can differ between different JVM implementations.
To stop a thread one can use a volatile reference pointing to the current thread that can be set to null by other threads
to indicate the current thread should stop its execution:
Example:
private static class MyStopThread extends Thread
{ private volatile Thread stopIndicator;
public void start() {
stopIndicator = new Thread(this);
stopIndicator.start();
}
public void stopThread() {
stopIndicator = null;
}
@Override
public void run()
{
Thread thisThread = Thread.currentThread();
while(thisThread == stopIndicator) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
159. Is it possible to convert a normal user thread into a daemon thread after it has been started?
A user thread cannot be converted into a daemon thread once it has been started. Invoking the method
thread.setDaemon(true) on an already running thread instance causes a IllegalThreadStateException.
Examples
Dead Lock: In a multithreaded program, if we do not synchronize multiple threads properly, a deadlock situation
may arise and if such a situation comes, the program simply hangs. Deadlock comes between synchronized threads
only. It occurs when two or more threads wait indefinitely for each other to obtain locks (that is, two threads
depends on each other).
163. Can we get a thread into Runnable state which is in blocked state.
Yes, by calling interrupt() method we can get a thread into Runnable state but an interrupted exception will be
thrown by the JVM.
It is all about making synchronized threads communicate with each other cooperation is a mechanism in which a
thread is paused running in its critical section and another thread is allowed to run (or lock) in the same critical
section to be executed. It is implemented by following methods, which are existed in the java.lang.Object class.
• wait()
• notify()
• notifyAll()
It causes current thread to release the lock and wait until either another thread invokes the notify () method or
notifyAll() method for this object, or a specified amount of time has elapsed.
It makes the parent thread to wait until the present thread completes its task
Yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching
between the threads.
Volatile is a modifier and it is useful in multi threaded program. In multi thread program each program maintains
cache of local variables for fast computing purpose. Updating the value will be done in cache not in main memory.
Declaring a variable volatile means
* There will be no cache maintained by each program that means all the changes made in main memory.
* Access to this variable acts as synchronized block.
174. Can you give me some cases when abnormal condition happens (runtime error occurs)?
There are many cases when abnormal conditions happen during execution of a program such as.
• If you try to read the data from a file which is not existed
• If you try to load a class dynamically, which is not existed
22 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
• Try to establish the connection to the data base by giving wrong URL or userid or password.
• If you try to divide a number by zero.
• When u r trying to parse non integer String into integer etc…
• The direct child classes of Exception class are called as checked exceptions.
• Checked exceptions are checked at compile-time.
• These exceptions are also called as UnReported Exceptions.
2) Unchecked Exception
Throwable.
177. What are the keywords which are used to manage exception handling in Java?
• try
• catch
• finally
• throw
• throws
180. Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch
block OR a finally block.
• We can write a try block, with finally block without using catch block.
finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that
causes the process to abort)
186. Can we write a try block without using catch or finally block.
Yes we can write because in 1.7 version of java a new feature was introduced called try with resources. For that no
need to write catch or finally block with try block.
Forwarding the exception which is occurred in one method to the invoking method is known as exception
propagation.
188. Can we create our own exceptions?
Yes, we can create our own exceptions. If you create an exception by extending Exception class it will be a checked
exception and if we create an exception by extending RuntimeException class then it is called as un-checked
exception.
189. What is string?
It is nothing but collection of characters, to handle string in java we have different types of classes those are.
The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value
can't be changed.
191. What is the difference between String and StringBuffer?
In case of strings, if a string is reassigned with a new value, a new location is created where the new value is stored
and the old location (where old value is stored) is garbage collected. That is, a string value cannot be changed in the
same location. This is called immutable and is an overhead to the processor and a negative point for performance.
In case of a String Buffer, if a value is changed, the location is not changed and in the old location only the
value changed.
Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object
"sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables.
That is why string objects are immutable in java.
There are two ways to create the string object, by string literal and by new keyword.
Ex-1: String str=”MadhuTechSkills”;//using string literal
Ex-2: String str=new String(“MadhuTechSkills”);//using new operator
1. String s1="Welcome"; // object will be created in the string constant pool and its address
stored in s1 variable
2. String s2="Welcome"; // JVM assigns the address the first object to the s2 variable
3. String s3="Welcome"; // JVM assigns the address the first object to the s3 variable also
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
Both are mutable objects but StringBuffer is synchronized whereas StringBuilder is not synchronized.
• You can call the private method from outside the class by changing the runtime behaviour of the class.
• By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private method from any
other class.
import java.lang.reflect.Method;
import static java.lang.System.*;
class One
{ private void sayHello()
{out.println("Hello... MadhuTechSkills");
}
25 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
}
public class Demo
{ public static void main(String[] args)throws Exception
{ Class c= Class.forName("One");
Method m =c.getDeclaredMethod("sayHello");
m.setAccessible(true);
m.invoke(c.newInstance());
}
}
201. What gives Java its 'write once and run anywhere' nature?
The bytecode, Java is compiled to be a byte code which is the intermediate language between source code and
machine code. This byte code is not platform specific and hence can be fed to any platform.
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of
classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.
It is the base class for every class in java. That is the methods and fields existed in the object class will be inherited
by every class in java.
It returns the hashCode value which is generated based on the object’s address. This hashCode value is used to
compare objects but it returns true if both objects addresses are same.
Drawback: it can’t return true if two different objects contains same data.
To compare two object based on the data we have to override the hashCode() method.
It compares two objects based on the address and then returns either true or false.
Drawback: it can’t return true if two different objects contains same data.
To compare two object based on the data we have to override the equals () method.
26 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
206. When you are writing equals() method, which other method you need to override?
hashcode is the right answer. Since equals and hashCode have their contract, so overriding one and not other will
break the contract between them.
Here contract is nothing but in the Collection Framework we have two classes which store key value pairs as
elements called Hashtable and HashMap. These two classes use both the hashCode() method and equals() method
to compare objects.
See the below point to know how these two classes are compare two objects
1. There's no need to call hashCode if (obj1 == obj2)
2. If obj1!=obj2 then there’s a need to call the hashCode method
3. There's no need to call equals if hashCode differs
4. If hashCode is same, there’s a need to call calls the equals method also
209. Which method is automatically invoked if you try to print the object?
Garbage collector is a thread which de-allocates the objects which are in out of scope.
Yes by using gc() method of System class we can call explicitly. Ex: System.gc();
213. Which method will be invoked by the Garbage collector at the time of object destruction?
Collection Collections
It is an interface, which can be used to represent group It is a utility class, existed in java.util package it
of objects contains several utility methods which are used to sort,
search objects etc... of a collection.
List (I): It is the child interface of Collection, if we want to represent a group of individual objects as a single entity,
where duplicates are allowed and insert order must be preserved then we should go for list.
Set (I): It is the child interface of Collection, if we want to represent a group of individual objects as a single entity,
where duplicates are not allowed and insertion order not required. Then we should go for set interface.
• where duplicates are not allowed and insertion order not required
• it accepts null values
A HashSet is unordered and unsorted Set. LinkedHashSet is the ordered version of HashSet.The only
difference between HashSet and LinkedHashSet is that LinkedHashSet maintains the insertion order. When we
iterate through a HashSet, the order is unpredictable while it is predictable in case of LinkedHashSet.
Note: TreeSet is sorted, it supports ascending order.
List Set
1. Duplicates are allowed 1. Duplicates are not allowed
2. Insertion order preserved 2. Insertion order not preserved
29 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
226. What do you know about Queue?
Queue (I): Queue is child interface of Collection; if we want to represent a group of individual objects prior to
processing () then we should go for queue. Usually queue follows first in first out order but Based on our
requirement we can implement our own priority order also.
Ex: before sending a mail we have to store all mail id’s in some data structure, in which order we added mail id’s in
the same order only mail should be delivered for this requirement queue is the best choice.
An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to
their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is
used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not
permit insertion of non-comparable objects (doing so may result in ClassCastException).
A normal Queue will return null when accessed if it is empty, while a BlockingQueue blocks if the queue is empty
until a value is available.
30 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
231. What is PriorityBlockingQueue?
An unbounded blocking queue that uses the same ordering rules as class Priority Queue and supplies blocking
retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource
exhaustion (causing OutOfMemoryError). This class does not permit null elements. A priority queue relying on
natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).
An optionally-bounded blocking queue based on linked nodes. This queue orders elements FIFO (first-in-first-out).
The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that
element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the
queue retrieval operations obtain elements at the head of the queue. Linked queues typically have higher throughput
than array-based queues but less predictable performance in most concurrent applications.
1. It is not child interface of Collection interface but it is the part of Collection Framework
2. If you want to represent a group of objects a key value pairs then we should go for Map
3. Duplicate keys are not allowed but the values can be duplicated
4. Both key and values are objects only
it is the child interface of Map. If we want to represent a group of key, value pairs according to some sorting order of
keys, then we should go for sorted map.
1. In SortedMap the sorting should be based on key but not based on value.
It is the child interface of SortedMap. It defines several methods for Navigation Purposes.
It is the implemented class for Navigable Map interface; it is sorted according to the natural ordering of its keys or
by a Comparator provided at map creation time, depending on which constructor is used.
Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and
backward direction.
class Outer {
private static class Inner {
public static void main(String[] args) {
System.out.println("Hello from Inner!");
}
}
}
257. Can we call a public static method of One class (class is not public) of package p1 in another class of
package p2?
Demo2.java
package p2;
import static java.lang.System.*;
import java.lang.reflect.*;
class Demo2
{ public static void main(String args[])throws Exception
{ Class c=Class.forName("One");
out.println(c.getName());
Method m=c.getMethod("hai");
//out.println(c.newInstance());
m.setAccessible(true);
out.println(m);
out.println(m.invoke(c));
//One o1=new One();
}
}
E:\NUBatch>javac -d . Demo2.java
E:\NUBatch>java p2.Demo2
p1.One
public static java.lang.String p1.One.hai()
Hello
258. Why a class containing a main method doesn't need to be public in Java?
Because the JVM uses reflections concept to call the main method, by using reflections we can bypass the access
privileges.