100 Core Java Interview Questions PDF
100 Core Java Interview Questions PDF
beginnersbook.com
Home
Contact us
JSP
JSTL
Build Website
Internet
Java Collections
Java I/O
SEO
Tech Pages
SharePoint
WordPress
C Tutorial
OOPs Concepts
in Java Q&A
Inheritance
Polymorphism
Data Encapsulation
Simple
Multi-threaded
Distributed Application
Robust
Security
Q) What is javac ?
It produces the java byte code when *.java is given as input and it is the intermediate representation of your source code that contains
instructions that the java interpreter will execute.
Class
beginnersbook.com/2013/05/java-interview-questions/ 1/25
2/17/14 100+ Core Java Interview Questions
Object
Methods
Inheritance
Polymorphism
Overriding
Abstraction
Encapsulation
Interface
Q) What is class?
Class is nothing but a template, which describes the various properties and functions.
Q) What is an object?
Object has its own properties and functionality; also it’s an instance of the class.
Q) How many times does the garbage collector calls the finalize() method for an object?
The garbage collector calls the finalize() method Only once for an object.
Q) Abstract class?
A class for which object can’t be instantiated/created, such class are called as Abstract class. Also a class, which is, generalized form
that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
Q) Multiple Inheritances?
Inheriting more than one parent class. Java doesn’t supports multiple inheritances whereas c++ supports.
In inheritance, when a child class writes a method with the same name as method in super-class is called method overriding. Method
call on the child class will execute the child class method not the super class method.
Q) What is a WeakHashMap?
a) A hash table map with duplictate keys.
b) A general purpose hash table-based implementation to better store.
c) A hash table-based Map implementation with weak keys.
beginnersbook.com/2013/05/java-interview-questions/ 2/25
2/17/14 100+ Core Java Interview Questions
d) A list with weak references to objects.
Ans is (c). In order for the ClassLoader to execute the main() method, it has to be declared atleast as public, static & void.
Q) Does a static nested class have access to the enclosing class’ non-static methods or instance variables?
No. A static nested class doesn’t have access to the enclosing class’ non-static methods or instance variables.
Q) Polymorphism?
In a class, 2 methods with same name having different number of arguments is called polymorphism. Is also called as function
overloading.
Q) Encapsulation?
Group of Data & functions are said to be an Encapsulation with single entity. Objects should not be allowed to access the properties of
class instead could have separate methods thru which the property can be accessed.
Q) Interface?
Interfaces are a collection of method prototypes, the implementation of which has to be done by a class that inherits it. When it is
declared as public, any class can use the interface. Once an interface3 has been defined, any classes can implements that interface.
When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the
beginnersbook.com/2013/05/java-interview-questions/ 3/25
2/17/14 100+ Core Java Interview Questions
interface chain.
Byte – 8 bit (are esp. useful when working with a stream of data from a network or a file).
Short – 16 bit
Note: Any time you have an integer expression involving bytes, shorts, ints and literal numbers, the entire expression is promoted to int
before the calculation is done.
Q) What is Unicode?
Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters
found in human languages.
Q) What is Literals?
A literal is a value that may be assigned to a primitive or string variable or passed as an argument to a method.
Q) Dynamic Initialization?
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
To create a conversion between two incompatible types, you must use a cast. There are automatic casting and explicit casting.
Q) Arrays?
An array is to store the group of like-typed variables that are referred to by a common name.
Constructors are special methods belonging to a class. These methods are basically used to do initialization of instance variables. They
are automatically called whenever an instance of a class is created.
Q)THIS keyword?
beginnersbook.com/2013/05/java-interview-questions/ 4/25
2/17/14 100+ Core Java Interview Questions
The THIS keyword is a reference to the current object which is automatically created.
Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no
references to an object exist for a long time is called garbage collection.
Pass by value – Changes made to the parameter of the subroutines have no effect on the argument used to call it.
Pass by reference – Changes made to the parameter will affect the argument used to call the subroutine.
Second, is used to access a method of the superclass that has been hidden by a member of a subclass.
A subclass can call a constructor method defined by its super class by using super (parameter-list). Super must always be the first
statement.
This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes.
Object class has the following methods
objectClone () – to creates a new object that is same as the object being cloned.
The star form may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-
time performance.
Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as
toString () and hashCode () on an array. However, length is a data item of an array and not a method. So you have to use
myArray.length.
Q) How can I put all my classes and resources into one file and run it?
Use a JAR file. Put all the files in a JAR, then run the app like this:
beginnersbook.com/2013/05/java-interview-questions/ 5/25
2/17/14 100+ Core Java Interview Questions
Java -jar [-options] jarfile [args...]
Jdk1.1 release consists of Java Unicode character to support the multiple language fonts, along with Event Handling, Java security, Java
Beans, RMI, SQL are the major feature provided.
Q) java.lang.* get imported by default. For using String and Exception classes, you don’t need explicitly to import this
package. The major classes inside this package are
Object class
Math class
String class
Thread classes
Exception classes
Process classes
Class classes
[code language="java"]
When a member is declared as Static, it can be accessed before any objects of its class are created, and without references to any
object.
It allocates the memory once and uses the same until the end of the class.
Final variable – means constant, the value of the variable can’t be changed, its fixed.
Final class – Means can’t be inherited to other class. This type of classes will be used when application required security or someone
beginnersbook.com/2013/05/java-interview-questions/ 6/25
2/17/14 100+ Core Java Interview Questions
don’t want that particular class.
Throwing an exception, in its most basic form is simple. You need to do two things. First, you create an instance of an object that is a
subclass of java.lang.Throwable. Next you use the throw keyword to actually throw the exception.
If you write a method that might throw an exception (and this includes un-handled exceptions that are generated by other methods called
from your method), then you must declare the possibility using a throws statement.
Checked exceptions – describes problems that can arise in a correct program, typically difficulties with the environment such as user
mistakes or I/O problems. These exceptions are not a programming error, rather more likely with the Environment behavior.
Java.lang.Exception is the class used.
Unchecked exception – Exception, which occurs at the runtime, is called Unchecked exception. Java.lang.RuntimeException class is
used. Runtime exception describes the program bugs. Such exceptions arise from things like out-of-bounds a correctly coded program
would avoid array access, Database connection, MalformedURLException, EOFException, NullPointerException, IllegalState
Exception etc and normally this.
The Exceptions classes are derived from Throwable class. The structure is given below.
Java.lang.Throwable class
Java.lang.Error
NumberFormatException – When we try Illegal operation with any data types. For e.g., performing arithmetic on String variable.
NullPointerException – When the Dynamic Variable carries value as “null” during the condition will result in null pointer exception.
ClassCastException – Attempting to use a reference as if it referred to an object of some class – but it doesn’t
IllegalStateException – A method was activated when the object was in a state that violates the method’s precondition.
beginnersbook.com/2013/05/java-interview-questions/ 7/25
2/17/14 100+ Core Java Interview Questions
NegativeArraysizeException – Allocating an array with a negative number of components
Q) finally block?
Irrespective of success or failure of try/catch block, the finally block gets execute. Finally block will best utilized to close your open
database connections, open files etc.
[code language="java"]
Public class ClassName{
public static void main(String a[])
try{
char ch = (char) system.in.read();
if (Character.isJavaIdentifiedPart(ch);
System.out.println(“ is a Identifier”);
if (Character.isJavaIdentifiedStart(ch);
System.out.println(“can be start of Identifier”);
}catch(Exception e){
System.out.println(e);
}
}
}[/code]
Points to remember: Math is a final class. Cannot be override. It can imported from java.lang.*. All the methods( ceil(), floor(), rint(),
round(), random() ) in this class are static and they can be invoked automatically.
This package contains the basic classes, which form as a java’s data structure. Since java doesn’t support Structures, Unions, and
Pointers as in c++, hence this package is used.
Vector – is for growable array. It allows storing different objects of any type.
Q) Wrapper Classes?
Vector and Stack classes allow operation only for object not for data types. Hence some of the data types are wrapped to convert
them into object to put into vector. Such data type wrapper classes are
[code language="java"]
Vector v = new Vector();
int I = 5; //this can’t be added to vector hence need to wrap
Integer ii = new Integer(I);
v.addElement(ii);[/code]
[code language="java"]
v.elementAt(int);
v.insertElementAt(object, int);
removeElementAt(int);
removeAllElements();[/code]
Q) Hashtable ?
Hashtable are used to store key and value pair. User need not to worry about whether the variable is stored rather we just need to
know the key retrieve the corresponding “value”.
Methods are :
[code language="java"]
h1.put(“key”,”value”);
h1.get(“key”);
Sample program to find out the list of all keys from hastable.
[code language="java"]
Enumeration e = h1.keys();
While (e.hasMoreElements())
{
object obj = e.nextElement();
h1.get(obj);
}[/code]
You can't resize an array. Once an array is created, you will not be able to change the length of it. You can allocate a new array, copy
the elements into the new array, and set the reference to the original array to point to the new array -
[code language="java"]
ABC[] arr = new ABC[];
// Below I'm creating a new array with larger size
XYZ[] newarr = new XYZ[5];
beginnersbook.com/2013/05/java-interview-questions/ 9/25
2/17/14 100+ Core Java Interview Questions
System.arraycopy(arr, 0, newarr, 0, arr.length);
arr = newarr;[/code]
A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set
state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at
runtime. JavaBeans are reusable software components.
Unsigned applets are simply not allowed to read or write files on the local file system .
Unsigned applets can, however, read (but not write) non-class files bundled with your applet on the server, called resource files
Q) What is container ?
Container
Panel
Applet
Window
Frame
Dialog
Learning)
[code language="java"]
Frame f = new Frame();
f.setSize(300,200); //ht and width
f.setVisible(true) ; // Frames appears
[/code]
Swing
AWT
Java2D
Drag and Drop
Accessibility
ActionListerner - actionPerformed();
ItemListerner - itemStateChanged();
TextListener - textValueChanged();
Learnings)
Following stage of any applets life cycle, starts with init(), start(), paint(), stop() and destroy().
Q) showStatus() ?–
To display the message at the bottom of the browser when applet is started.
Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event
Handling.
Advantage of adapter: To perform any window listener, we need to include all the methods used by the window listener whether we use
those methods are not in our class like Interfaces whereas with adapter class, its sufficient to include only the methods required to
override. Straight opposite to Interface.
Dialog d = new Dialog(this,”Title”,true) - 3rd parameter indicated whether dialog frame is modal or non-modal.
[code language="java"]
import java.awt.*, java.awt.event.*, java.applet.*;
public class CN extend Applet implements KeyListener {
String msg = “”:
int X= 10, Y =20;
public void init(){
addKeyListener(this);
requestFocus();
}
In concurrent programs, several independent activities happen at the same time. Java models this through an interface, Runnable that
embodies generic activities and a class, Thread that is responsible for the independent execution of Runnable.
Thread Life cycle: Starts with init(), start(), run(), stop() and destroy().
Q) Java Threads
1. interface Runnable
2. abstract class Thread
Q) Synchronization?
I have good news and bad news for you. The bad news is that you can run into big problems when two or more threads share
parameters. Recall that the threads run independently and re likely to interfere during complex operations.
One has to enforce proper synchronization between threads. In Java, synchronized is a keyword applied to methods:
Each Java object has a lock. To execute synchronized code on an object, a thread must own the object's lock. When two threads
execute code synchronized on the same object, only one of them acquires the lock and proceeds. The other is paused until the first
beginnersbook.com/2013/05/java-interview-questions/ 12/25
2/17/14 100+ Core Java Interview Questions
one releases the lock. Thanks to synchronization each thread has a chance to use the object with no meddling from the other thread.
Learning) A thread that waits on an object is automatically woken up by other threads calling notifyAll() on the same
object. wait() is efficient and consumes no CPU cycles. notify() is faster than notifyAll() but it can be dangerous when
several threads wait on the same object. In practice, it is seldom used and I suggest you stick to the safer notifyAll().
[code language="java"]
public synchronized Object getResult()
throws InterruptedException
{
while (result == null)
wait();
return result;
}[/code]
An instance of this class represents a string that can be dynamically modified. A String buffer has a capacity, which is the maximum-
length string it can represent without needing to allocate more memory. A string buffer can grow beyond this as necessary, so usually do
not have worry about capacity.
[code language="java"]
StringBuffer sb = new StringBuffer(“Planetasia”);
sb.insert(3,”xyz”); // plaxyznetasia
sb.append(“abc”); // plaxyznetasiaabc
[/code]
String s1 = “Planetasia”;
String s2 = “bangalore”;
int i = 3;
s1.lastIndexOf(“a”); - will return the position of “a” starting the index at the end.
s1.equals(s2) – String s1 and s2 content will be compared, return true if they are equal.
beginnersbook.com/2013/05/java-interview-questions/ 13/25
2/17/14 100+ Core Java Interview Questions
s1.endsWith, s1.startsWith, s1.equalsIgnoreCase.
Q) trim (). ?
Is a method used to remove the unwanted space in the beginning and end of the variable?
[code langauge="java"]
public class CN
{
public static void main(String a[]){
String s = "Java in two days" ;
StringTokenizer st = new StringTokenizer(s,” “);
int I = st.countToken();
while(st.hasMoreTokens(I))
{
String y = st.nextToken();
System.out.println(y);
}
}
}[/code]
Q) What is the difference between String s = “abc”; and String s = new String(“abc”); ?
As such no big difference, but second statement will take extra memory allocation.
Java Application ---jdbc api---------à JDBC driver Manager ----uses JDBC driver Api to load---à JDBC Driver protocol à DB
Q) Java Soft has defined 4 types of drivers to connect with db thru DB driver?
Type 1 – JDBC-OBDCBridge
Statement – created by method createStatement(). A statement object is used to sending simple sql’s.
PreparedStatement – method prepareStatement() uses. It has potential & efficient than a statement object becoz it has been pre-
compiled and stored it for future use.
Q) The statement interface provides 3 different methods for executing SQL stmts, what are those?
executeUpdate() – Queries like insert, update, delete and also for DDL
beginnersbook.com/2013/05/java-interview-questions/ 14/25
2/17/14 100+ Core Java Interview Questions
execute() - it returns boolean. If true means all select query is operated, if it false DML queries have taken place.
A connection object represents a connection with a database. A connection session includes SQL stmts that are executed and the
results are returned over that connection. A single application can have more connection with a single DB.
[code language="java"]
String Url = "jdbc:odbc:wombat";
Connection con = DriverManager.getConnection(Url,"username","password");[/code]
Test your skills - Guess the answers of Java programs - for Written tests as well as to sharpen the
Java Knowledge
[code language="java"]
public class Test
{
public static void main(String args[])
{
int num = 132;
List ls = new ArrayList();
ls.add(new Object());
ls.add("Welcome");
ls.add(num);
System.out.println(ls.get(1));
}
}[/code]
a) Welcome
b) It will give a Compilation Error!!
c) Runtime Error will occur
d) 132
Ans is (a)
‘Welcome’ gets printed since it is the 2nd object(String object) in the list and ArrayList index starts from 0.
[code language="java"]
public class FClass {
private int final FNUM;
public static void main(String args[]){
System.out.println(new FClass().FNUM);
}
}[/code]
a) 1
b) 0
c) RunTimeException
d) Compile time error.
beginnersbook.com/2013/05/java-interview-questions/ 15/25
2/17/14 100+ Core Java Interview Questions
Ans is (d). private final variable FNUM needs to be initialized (should have some value assigned) since its declared final.
Question -
[code language="java"]
public class MyClass
{
public static void main(String[] args)
{
int[] myArr = new int[]{0,1,2,3,4,5};
System.out.println(myArr[0]+ myArr[5]+myArr[2]);
}
}[/code]
a) 032
b) It will throw a Compilation Error!!
c) 7
d) 172
Ans is (c).
Hint: Array(myArr) index starts from 0.
[code language="java"]
public class final HMap {
private static final Map m = new HMap();
public static void main(String[] args) {
m.put("p1","v1"); //line num:3
m.put("p2","v2");
m = new HMap(); //line num:5
}
}[/code]
a) Yes
b) No, Compilation Error at line 3
c) No, Runtime Error
d) No, Compilation Error at line 5
Ans is (d). Once declared the final variable cannot be initialized again.
Question -
[code language="java"]
import java.io.*;
class Demo
beginnersbook.com/2013/05/java-interview-questions/ 16/25
2/17/14 100+ Core Java Interview Questions
{
Demo() throws IOException
{
throw new IOException();
}
}
What is output?
1. Catch1
2. Catch2
3. Compilation Fail.
4. Runtime Exception
5. Code runs fine with No output
Ans is (2).
Question -
[code language="java"]
class Demo
{
int inum = 10;
}
class Sample extends Demo
{
int inum = 15;
public static void main(String[] args)
{
Sample obj1 = new Sample();
Demo obj2 = new Sample();
beginnersbook.com/2013/05/java-interview-questions/ 17/25
2/17/14 100+ Core Java Interview Questions
System.out.println(obj1.inum);
System.out.println(obj2.inum);
System.out.println(((Demo)obj1).inum );
}
}[/code]
1. 15 10 15
2. 15 15 15
3. 10 10 10
4. 15 10 10
5. 10 15 104
6. Compilation Fails.
7. Runtime Exception.
Ans: (4).
Question -
[code language="java"]
class Test
{
public static void main(String[] args)
{
byte byt1 = -128;
byte byt2 = 128;
System.out.println(byt1+byt2);
}
}[/code]
1. 0
2. 1
3. -1
4. Compilation Fails.
5. Runtime Exception
Ans: (4)
Question -
[code language="java"]
public class A
{
public static void main(String a[])
{
byte byt1 = 1 , byt2 =2, res;
res = byt1 + byt2--;
System.out.println("Ans :"+res);
}
}[/code]
1. 0
2. 1
3. 2
4. 3
5. Compilation Fails.
6. Runtime Exception
beginnersbook.com/2013/05/java-interview-questions/ 18/25
2/17/14 100+ Core Java Interview Questions
Ans: (5)
[code language="java"]
public class A
{
public static void main(String a[])
{
short shr = 2;
int num = shr++ - shr++;
System.out.println(""+num++ + shr);
}
}[/code]
1. 0
2. 1
3. -14
4. -13
5. 3
6. 4
Ans: (3)
Question -
[code language="java"]
public class A
{
public static void main(String a[])
{
int i = 1;
for(;;){}
System.out.println("Hello world");
}
}[/code]
1. String String;
2. Integer Integer;
3. Double Object;
4. int main;
5. int unsigned;
Question -
[code language="java"]
public class Sample
{
int inum = 1;
public static void main(String a[])
{
int inum = 12;
System.out.print( this.inum );
beginnersbook.com/2013/05/java-interview-questions/ 19/25
2/17/14 100+ Core Java Interview Questions
}
}[/code]
Ans: inum is a non-static variable, this cannot be referenced from a static context
Question -
[code language="java"]
public class A extends A1,A2 //Line no: 1
{
public static void main(String a[])
{
System.out.println("Hi");
}
}
1. Runs Fine
2. Compilation Error at Line no: 1
3. Compilation Error at Line no: 2
4. Compilation Error at Line 1 and Line 2.
5. Runtime Exception
Ans: (4)
Question -
[code language="java"]
class Demo
{
static String myMethod(int i)
{
return "int";
}
static String myMethod(float i)
{
return "float";
}
public static void main (String[] args)
{
long num1 = 1;
double num2 = 2;
System.out.print(myMethod(num1)+","+ myMethod(num2));
}
}[/code]
beginnersbook.com/2013/05/java-interview-questions/ 20/25
2/17/14 100+ Core Java Interview Questions
5. None of the above
Ans: (4)
Question -
[code language="java"]
class XYZ
{
{
System.out.println("initializer");
}
public static void main(String a[])
{
System.out.println("hello");
XYZ obj=new XYZ();
}
}[/code]
Ans: (1)
Question -
[code language="java"]
class bike { }
class Demo extends bike
{
public static void main(String[] args)
{
Demo[] a1=new Demo[2];
bike[] a2;
a2=a1; //Line no:3
Test[] a3;
a3=a1; //Line no:5
}
}[/code]
Ans: (4)
Question -
[code language="java"]
beginnersbook.com/2013/05/java-interview-questions/ 21/25
2/17/14 100+ Core Java Interview Questions
class Test
{
static interface I //Line no:1
{
static class Test2{} //Line no:2
}
public static void main(String a[])
{
Test.I.Test2 ob1=new Test.I.Test2(); //Line no:3
System.out.println("object created");
}
}[/code]
Ans: (1)
Question -
[code language="java"]
public static void parse(String str)
{
try
{
float f = Float.parseFloat(str);
}
catch (NumberFormatException nfe)
{
f = 0;
}
finally
{
System.out.println(f);
}
}
Ans: (3)
beginnersbook.com/2013/05/java-interview-questions/ 22/25
2/17/14 100+ Core Java Interview Questions
Question -
[code language="java"]
public class MyThreadClass implements Runnable
{
public void run()
{
System.out.print("thread is running");
}
public static void main(String[] args)
{
Thread th = new Thread(new MyThreadClass());
th.run();
th.run();
th.start();
}
}[/code]
Ans: (5)
Question -
Which modifiers would be valid in the declaration of a main() method so that the class can be run from command line?
Can select multiple options.
1.native
2.protected
3.public
4.final
5.abstract
Question -
1. Object
2. Thread
3. Error
4. Exception
5. Throwable.
6. String
Ans: (6)
beginnersbook.com/2013/05/java-interview-questions/ 23/25
2/17/14 100+ Core Java Interview Questions
shubham
good
Reply
Leave a Comment
Name *
E-mail *
Website
Submit
beginnersbook.com/2013/05/java-interview-questions/ 24/25
2/17/14 100+ Core Java Interview Questions
Follow Me on Google+
Chaitanya Singh
google.com/+ChaitanyaSingh
Follow
504 followers
Popular Tutorials
JSP Tutorial
JSTL Tutorial
Java Collections Tutorial
Java String class and methods
Follow +1
+ 1,333
beginnersbook.com/2013/05/java-interview-questions/ 25/25