You are on page 1of 25

2/17/14

100+ Core Java Interview Questions

beginnersbook.com
Home
Contact us
JSP
JSTL
Build Website
Internet
Java Collections
Java I/O
SEO
Tech Pages
SharePoint
WordPress
C Tutorial
OOPs Concepts

100+ Core Java Interview Questions


by Chaitanya Singh
in Java Q&A

Java OOPs Interview questions


Q) Three Principles of OOPS language?
Inheritance
Polymorphism
Data Encapsulation
Q) Java vs. C ++?
Simple
Multi-threaded
Distributed Application
Robust
Security
Complexities are removed (Pointers, Operator overloading, Multiple inheritance).
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.
Q) What all terms are related to OOPs?
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 its 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) What are two different ways to call garbage collector?
System.gc() OR Runtime.getRuntime().gc().
Q) Can the Garbage Collection be forced by any means?
No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not
guarantee that garbage collection would be done.
Q) Abstract class?
A class for which object cant 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 doesnt supports multiple inheritances whereas c++ supports.
Q) What is the method overriding?
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.
There can be no object of an abstract class.
Constructors or static methods cannot be declared as abstract.
Q) Can this keyword be assigned null value?
No, this keyword cannot have null values assigned to it.
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 option (c).
WeakHashMap is a hash table-based Map implementation with weak keys.
Q) Which of the following lines allow main method to be executed by ClassLoader?
a) public static String main(String a[]);
b) protected static void main(String a[]);
c) final public static void main(String a[]);
d) public static void main();
e) private static void main(String a[]);
f) public void main(String a[]);
Ans is (c). In order for the ClassLoader to execute the main() method, it has to be declared atleast as public, static & void.
Q) Which modifiers a method of local inner class can have?
Only abstract or final keyword is allowed.
Q) Do we need to implement any method of Serializable interface to make an object serializable?
No.In order to make an object serializable we just need to implement the interface Serializable. We dont need to implement any
methods.
Q) What is a transient variable?
transient variables are not included in the process of serialization.
They are not the part of the objects serialized state.
Variables which we dont want to include in serialization are declared as transient.
Q) Does a static nested class have access to the enclosing class non-static methods or instance variables?
No. A static nested class doesnt have access to the enclosing class non-static methods or instance variables.
Q) Which modifiers can be applied to the inner class?
public ,private , abstract, final, protected.
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) Does Java support operator overloading?
Operator overloading is not supported in Java.
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.
Interfaces are javas substitute for multiple inheritances.
Interfaces can be extended.
One interface can inherit another by use of keyword extends.
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.

Core Java Interview Questions


Q) Different Data types in Java.
Byte 8 bit

(are esp. useful when working with a stream of data from a network or a file).

Short 16 bit
Char 16 bit Unicode
Int

32 bit (whole number)

Float 32 bit (real number)


Long 64 bit (Single precision)
Double - 64 bit (double precision)
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.
Q) What is Type casting in Java?
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.
Q) Explain about BREAK stmt in java?
In Java, the break stmt has 3 uses.
First, it terminates a statement sequence in a switch statement.
Second, it can be used to exit a loop
Third, it can be used as go to keyword
Q) What are Constructors?
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.
Q) Garbage collection in java?
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.
Q) Use of finalize() method in java?
FINALIZE () method is used to free the allocated resource.
Q) Explain ways to pass the arguments in Java?
In java, arguments can be passed in 2 ways,
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.
Q) Explain SUPER in Java?
First calls the superclass constructor.
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.
Q) What is a Object class?
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.
boolean determines whether one object is equal to another.
finalize called before an unused object is recycled.
toString () returns a string that describes the object.
Q) What are Packages?
Package is group of multiple classes under one name space.
Q)What is the difference between import java.utilDate and java.util.* ?
The star form may increase the compilation time especially if you import several packages. However it doesnt have any effect runtime performance.
Q) Why cant I do myArray.length () ? Arrays are just objects, right?
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...]


Q) Can I declare a data type inside loop in java?
Any Data type declaration should not be inside the loop.
Q) Advantage over jdk 1.0 vs. jdk 1.1 ?
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 dont need explicitly to import this
package. The major classes inside this package are
Object class
Data type wrapper classes
Math class
String class
System and Runtime classes
Thread classes
Exception classes
Process classes
Class classes
Q) Arrays can be defined in different ways. All ways are right.
[code language="java"]
int arr[] = null;
int arr[][] = new int arr[][];
int [][] arr = new arr [][];
int [] arr [] = new arr[][];[/code]
Q) What is static method means?
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.
Note: It is illegal to refer to any instance variable inside of a static method.
Q) Use of final keyword in Java?
Final methods mean methods cannot be override by any other method.
Final variable means constant, the value of the variable cant be changed, its fixed.
Final class Means cant 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

dont want that particular class.

Exception handling in Java Interview Questions


Q) Exceptions are defined in which java package? OR which package has definitions for all the exception classes?
Java.lang.Exception
This package contains definitions for Exceptions.
Q) What is throw keyword in exception handling?
throw keyword is used to throw the exception manually. While creating user defined exception you would be needing to use throw
keyword.
Q) Can static block throw exception?
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception(Unchecked exceptions), In
order to throw checked exceptions you can use a try-catch block inside it.
Q) throw & throws statement?
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.
Q) Different Exception types?
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.
Q) Interview questions about exception class
The Exceptions classes are derived from Throwable class. The structure is given below.
Java.lang.Throwable class
Java.lang.Exception (Checked Exception)
Java.lang.RuntimeExceptions (Unchecked Exception).
Java.lang.Error
ArrayBoundOutOfException Whenever an array is referenced outside its boundary.
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 doesnt
EmptyStackException Tried to pop or peek from an empty stack
IllegalStateException A method was activated when the object was in a state that violates the methods 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


IOException An input or output error
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.

Java I/O Interview Questions


Q) Write a Small program to read an input from command prompt ?
[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.
An only double data type is the input for math methods.
Q) List of classes under java.util. *?
This package contains the basic classes, which form as a javas data structure. Since java doesnt 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.
StringTokenizer Generating tokens for a given string based on delimiter.
Stack LIFO, FIFO
Date - is depreciated in jdk 1.1, 1.2, use Calendar in-spite
Calender System data and calendar
Enumeration hasMoreElements(); nextElement()
Hashtable Key value pair.
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
Integer, Double, Float, Character etc.
beginnersbook.com/2013/05/java-interview-questions/

8/25

2/17/14

100+ Core Java Interview Questions

For e.g.
[code language="java"]
Vector v = new Vector();
int I = 5; //this cant be added to vector hence need to wrap
Integer ii = new Integer(I);
v.addElement(ii);[/code]
Q) Different methods can operates on Vector are
[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.
Hashtable h1 new Hashtable();
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]
Go through all the
Basic Arithmetic operators like (+, -, *, /, %, ++, --, += ).
Boolean logical operators like (&, |, ^, ||, && )
The ? Operator (ternary operator).
Shift operators (>>, <<, >>>). Very important.
Q) How do I resize an array?
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]
Q) What is a Java Bean?
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.

Applet Interview Questions


Q) How do you do file I/O from an applet?
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 ?
A component capable of holding another component is called as container.
Container
Panel
Applet
Window
Frame
Dialog
Learning)
1. Flow Layout is default for panel.
2. Border Layout is default for Frames.
Q) On Windows, generally frames are invisible, how to make it visible. ?
[code language="java"]
Frame f = new Frame();
f.setSize(300,200); //ht and width
f.setVisible(true) ; // Frames appears
[/code]
Q) JFC Java Foundation Class
Swing
AWT
Java2D
Drag and Drop
Accessibility
Learning) Listeners and Methods?
ActionListerner - actionPerformed();
ItemListerner - itemStateChanged();
TextListener - textValueChanged();
FocusListener - focusLost(); & FocusGained();
beginnersbook.com/2013/05/java-interview-questions/

10/25

2/17/14

100+ Core Java Interview Questions

WindowListener windowActified(); windowDEactified(); windowIconified(); windowDeiconified(); windowClosed(); windowClosing(); windowOpened();


MouseMotionListener - mouseDragged(); & mouseMoved();
MouseListener - mousePressed(); mouseReleased(); mouseEntered(); mouseExited(); mouseClicked();
Learnings)
parseInt to convert string to int.
getBytes string to byte array
Q) Applet Life cycle?
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.
Q) What is the Event handling?
Is irrespective of any component, if any action performed/done on Frame, Panel or on window, handling those actions are called Event
Handling.
Q) What is Adapter class?
Adapter class is an abstract class.
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.
Q) Diaglog can be modal, non-modal dialog.
Dialog d = new Dialog(this,Title,true) - 3rd parameter indicated whether dialog frame is modal or non-modal.
Q) Handling keyboard events?
[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();
}
public void keyPressed(KeyEvent ke){
showStatus(Key Down);
}
public void keyReleased(KeyEvent ke){
showStatus(Key UP);
}
public void keyTyped(KeyEvent ke){
beginnersbook.com/2013/05/java-interview-questions/

11/25

2/17/14

100+ Core Java Interview Questions

msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g){
g.drawString(msg,X,Y);
}
}[/code]

Java Multithreading Interview Questions


Q) Thread?
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().
Learning) Other Thread methods
1.
2.
3.
4.
5.
6.

stop() kills the thread. (Different from Applet.stop().)


sleep(ms): non-busy wait for ms milliseconds, then throws InterruptedExceptions.
setPriority(int pr): lowest = 1, highest = 10 , normal =5
yield(): signals its willingness to give up CPU. Control transferred only when there is a ready thread of the same or higher priority.
wait() vs. notify()
suspend() vs. resume()

Q) Java Threads
1. interface Runnable
2. abstract class Thread
Two different ways to implement threads
Extends Thread class
1. create a subclass of Thread class
2. implement void run() method, which will be the main body of the thread.
3. initiated by start(), and terminates when run() ends.
Implements Runnable interface
1.
2.
3.
4.

create a class implementing Runnable interface.


create a Thread instance inside the class (with this as an argument).
invoke start() method.
initiated by creating the class instance, terminates when run() ends.

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:
public synchronized void someMethod()
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().
If no result is available getResult() waits:
[code language="java"]
public synchronized Object getResult()
throws InterruptedException
{
while (result == null)
wait();
return result;
}[/code]

Interview Questions related to Java Strings?


Q) StringBuffer class ?
An instance of this class represents a string that can be dynamically modified. A String buffer has a capacity, which is the maximumlength 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.
Different methods are
[code language="java"]
StringBuffer sb = new StringBuffer(Planetasia);
sb.insert(3,xyz); // plaxyznetasia
sb.append(abc); // plaxyznetasiaabc
[/code]
Q) Different methods operated on String?
String s1 = Planetasia;
String s2 = bangalore;
int i = 3;
s1.charAt(i); - will find the character at that position.
s1.indexOf(t); - will return the position of t in the string s1.
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.
s1 == s2

- The reference of both the string will be compared.

s1.compareTo(s2) will compare 2 strings and result three possible value


0

if both the strings are equal.

>1

- if s1 is greater than s2

<1

- if s2 is greater than s1.

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?
Q) A small program on StringTokenizer [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.

JDBC(Java to Database Connectvity) Interview Questions


Q) JDBC package contains a set of classes and methods for issuing SQL stmt, table update and calls to stored procedure.
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
Type 2 - Native-API-Partly-Java driver
Type 3 - JDBC-Net-All-Java driver
Type 4 - Native Protocol-All-Java driver
Q) 3 classes for sending sql stmts to DB thru connection object.
Statement created by method createStatement(). A statement object is used to sending simple sqls.
PreparedStatement method prepareStatement() uses. It has potential & efficient than a statement object becoz it has been precompiled and stored it for future use.
CallableStatement - are used to execute the SQL stored procedures.
Q) The statement interface provides 3 different methods for executing SQL stmts, what are those?
executeQuery() Queries like select.
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.
Q) What is Connection in JDBC?
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.
Opening a connection is established with a db to call method DriverManager.getConnection().
Template to create connection on to database located at URL : jdbc:odbc:wombat
[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
Question - What is o/p of following program?
[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.
Question - What is o/p of following program?
[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 - Select methods that correctly overload the following method
[code language="java"]byte sampMethod(short i) throws Exception {...}[/code]
a) int sampMethod(int i) throws IOException{...}
b) protected int sampMethod(short shr) throws FileNotFoundException{...}
c) private String sampMethod(byte byt,short shr) throws Exception{...}
d) char sampMethod(String str) throws RuntimeException{...}
e) int sampMethod(short shr){...}
Ans is (a),(c)& (d)
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.
Question - Will this code compile fine?
[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();
}
}
class test1 extends Demo
{
public static void main(String a[]) throws Exception
{
try
{
test1 aObj = new test1();
}
catch(Exception io)
{
System.out.println("Catch2");
}
}
test1() throws Exception,ClassCastException
{
try{
System.out.println("constructor");
}
catch(Exception io)
{
System.out.println("Catch1");
}
}
}[/code]
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]
Ans: Compilation error. For(;;) forms an Infinite loop
Question - Which of the following are not valid ?
1. String String;
2. Integer Integer;
3. Double Object;
4. int main;
5. int unsigned;
Ans: Nothing is INVALID
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");
}
}
interface I extends I1,I2 {} //Line no: 2
interface I1{}
interface I2{}
class A1{}
class A2{}[/code]
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]
What is the Result ?
1. Prints: float,double
2. Prints: float,float
3. Prints: double,float
4. Compile-time error
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]
What is the Result ?
1.prints hello and initializer
2.prints initializer and hello
3.compile time error
4.runtime error
5.None of the above
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]
What is the Result ?
1. compile time error at line 3
2. compile time error at line 5
3. Runtime exception
4. The code runs fine
5. None of the above
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]
What is the Result ?
1. Print object created.
2. Compilation Error at line 1.
3. Compilation Error at line 2.
4. Compilation Error at line 3.
5. Runtime Exception
6. None of the above
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);
}
}
public static void main(String[] args)
{
parse("invalid");
}[/code]
What is the result?
1. 0.0
2. 0
3. Compilation fails.
4. NumberFormatException is thrown at runtime.
5. ParseException is thrown at runtime.
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]
What is the result?
1. Compilation fails.
2. An exception is thrown at runtime.
3. The code executes and prints "thread is running".
4. The code executes and prints "thread is runningthread is running".
5 The code executes and prints "thread is runningthread is runningthread is running".
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
Ans: (3), (4)
Question Which of the following class can not be extended ?
1. Object
2. Thread
3. Error
4. Exception
5. Throwable.
6. String
Ans: (6)
Tagged as: 100, java, on, questions, than

beginnersbook.com/2013/05/java-interview-questions/

23/25

2/17/14

100+ Core Java Interview Questions

You might like:


1.
2.
3.
4.
5.
6.
7.

JUnit (Java Unit Testing) interview questions and answers


JUnit (Java Unit Testing) interview questions
JDBC(Java Database Connectivity) interview questions
Servlet interview questions and answers
The difference between regular (non-static) and static methods
Java Tutorial 3- Compilation and Execution of First Java Program
How to throw exception in java with example

{ 1 comment read it below or add one }

shubham
good
Reply
Leave a Comment
Name *
E-mail *
Website

Notify me of followup comments via e-mail


Submit

Confirm you are NOT a spammer


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

Join Us On Google Plus


BeginnersBook
Follow

+1

+ 1,333

Copyright 2012 2013 BeginnersBook - All Rights Reserved || Sitemap

beginnersbook.com/2013/05/java-interview-questions/

25/25

You might also like