Professional Documents
Culture Documents
beginnersbook.com
Home
Contact us
JSP
JSTL
Build Website
Internet
Java Collections
Java I/O
SEO
Tech Pages
SharePoint
WordPress
C Tutorial
OOPs Concepts
1/25
2/17/14
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
3/25
2/17/14
interface chain.
(are esp. useful when working with a stream of data from a network or a file).
Short 16 bit
Char 16 bit Unicode
Int
4/25
2/17/14
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
6/25
2/17/14
7/25
2/17/14
8/25
2/17/14
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
10/25
2/17/14
11/25
2/17/14
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g){
g.drawString(msg,X,Y);
}
}[/code]
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.
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
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]
>1
- if s1 is greater than s2
<1
beginnersbook.com/2013/05/java-interview-questions/
13/25
2/17/14
14/25
2/17/14
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
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
{
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
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
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
}
}[/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
21/25
2/17/14
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
beginnersbook.com/2013/05/java-interview-questions/
23/25
2/17/14
shubham
good
Reply
Leave a Comment
Name *
E-mail *
Website
24/25
2/17/14
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
+1
+ 1,333
beginnersbook.com/2013/05/java-interview-questions/
25/25