2/17/14 100+ Core Java Interview Questions beginnersbook.com/2013/05/java-interview-questions/ 1/25 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
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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 containsinstructions that the java interpreter will execute.
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) 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 can’t be instantiated/created, such class are called as Abstract class. Also a class, which is, generalized formthat 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.
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. Methodcall 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.
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 don’t need to implement anymethods.
Q) What is a transient variable?
transient variables are not included in the process of serialization.They are not the part of the object’s serialized state.
Variables which we don’t 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 doesn’t 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 functionoverloading.
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 ofclass 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 isdeclared as public, any class can use the interface. Once an interface3 has been defined, any classes can implements that interface.
Interfaces are java’s 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
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 intbefore 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 charactersfound 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. Theyare automatically called whenever an instance of a class is created.
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 firststatement.
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 doesn’t have any effect run-time performance.
Q) Why can’t 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 astoString () 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:
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, JavaBeans, 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
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 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
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 throwkeyword.
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 usermistakes 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 programwould 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.
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 java’s data structure. Since java doesn’t support Structures, Unions, andPointers 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
Hashtable are used to store key and value pair. User need not to worry about whether the variable is stored rather we just need toknow 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();
A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and setstate 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.
ContainerPanel
Applet
WindowFrame
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 widthf.setVisible(true) ; // Frames appears
4. yield(): signals its willingness to give up CPU. Control transferred only when there is a ready thread of the same or higher priority.5. wait() vs. notify()
6. 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 class2. 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. create a class implementing Runnable interface.
2. create a Thread instance inside the class (with this as an argument).
3. invoke start() method.
4. 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 shareparameters. 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
1. JUnit (Java Unit Testing) interview questions and answers2. JUnit (Java Unit Testing) interview questions3. JDBC(Java Database Connectivity) interview questions4. Servlet interview questions and answers
5. The difference between regular (non-static) and static methods6. Java Tutorial 3- Compilation and Execution of First Java Program7. How to throw exception in java with example