Interview Questions On Java,Java EE

Enter your email address:

Add to Technorati Favorites
Google PageRank Checker
Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Friday, April 3, 2015

Core Java Interview Questions

Every year many thousand technocrats choose Java careers across the globe,after formally taking Java training classes,courses and/or Java certifications like OCJP etc.While appearing for technical interviews,these budding Java programmers face variety of technical questions, are asked to write code snippets to prove their mettle in relevant topics of Java.They are not only assessed on language basics but also on their familiarity with Java development tools, coding standards and guidelines,optimization of Java code,load tests,securing code through Java obfuscation and many more. It is their performance in these interviews which decides their career fate and is highly dependent on to-the-point and not too verbose answers.

Apart from technical questions, an interviewee faces a spate of personal questions as well.In post, Personal Interview Questions you will find variety of questions asked on personal front.In wired world, it is very important to know where your resources are lying and how credible are they.

This blog intends to provide a consolidated knowledge base for all netizens,budding Java Engineers or experienced ones, interested in Java technology.This blog will primarily focus on 'Core Java' related questions and later on advanced topics in Java EE space,Open source technologies and frameworks and more.At this point this is a nice idea to put a roadmap right away to put all these questions in an organized fashion. In order to access questions list on a particular topic,please click the links associated with it.It will open the questions list in the same browser window and in order to comeback to this page, while going through various posts, you have to click back button in your bowser window.Each answer for a question on various topics will open in a fresh window,while you are through with reading an answer,close the open window in order to comeback to the questions list.If you want to access Master List of Core Java Interview Questions then click here.

Java Language Fundamentals (Click Link To Access Questions' List)
  1. Object Oriented Analysis and Design Basics, UML And Java
  2. Inside JVM
  3. Datatypes,Keywords,Operators and Assignments,Identifies etc.
  4. Declarations and Modifiers,Conversion,Casting and Promotion
  5. Flow control
  6. Assertions
  7. Exception Handling and Garbage Collection
  8. Objects and Classes
Packages and their classes (Click Link To Access Questions' List)
  1. java.lang.*
  2. java.util.*
  4. java.awt.*
Java and Database Access
JFC Swing
Collection APIs

Check more miscellaneous short questions on Core Java with short answers,here.

If you starve for more knowledge on Core Java,you may like to check out online e-books and other resources on Core Java or access all Online Java and Java EE resources. All suggestions,comments are welcome in order to make this space more productive and useful for all its audiences.

Read more on Core Java:
- Short Questions On Core Java
- Interview Questions on Java 5
- Enhancements in Java 7
Continue reading...

Sunday, February 1, 2015

Miscellaneous Core Java Questions With Short Answers

  1. In a Java program, how can you divert program messages to the system console, but error messages, say to a file?

    A. The class 'System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

    Stream stream = new Stream(new FileOutputStream("error.txt"));

  2. How do you know if an explicit object casting is needed?

    A. In order to assign a superclass object to a variable of a subclass,one needs to do explicit casting. For example:

    Person person;
    Man man;
    man = (Man)person;
    While automatic casting happens when you typecast a subclass object as parent class object.

  3. What's the difference between the methods sleep() and wait()

    A. The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

  4. Why would you use a synchronized block vs. synchronized method?

    A. A synchronized blocks place locks for shorter periods than synchronized methods.

  5. Can you write a Java class that could be used both as an applet as well as an application?

    A. Yes. Add a main() method to the applet.

  6. Can you call one constructor from another if a class has multiple constructors

    A. Yes. Use this() syntax.

  7. How will you convert a String array to an ArrayList object?


    String[] stringArray = new String[] {"x", "y", "Z"};
    List list = Arrays.asList(stringArray);

  8. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

    A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

  9. Can an inner class declared inside of a method access local variables of this method?

    A. It's possible if these variables are final.

  10. What can go wrong if you replace && with & in the following code:

    String a=null;
    if (a!=null && a.length()>10) {...}

    A. A single ampersand here would lead to a NullPointerException.

  11. When should the method invokeLater()be used?

    A. To ensure that Swing components are updated through the event-dispatching thread.

  12. What's the difference between a queue and a stack?

    A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

  13. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

    A. Sometimes. But your class may be a descendant of another class and in this case the interface is your only option.

  14. If you're overriding the method equals() of an object, which other method you might also consider?


  15. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?

    A. ArrayList

  16. How would you make a copy of an entire Java object with its state?

    A. Have this class implement Cloneable interface and call its method clone().

  17. How can you minimize the need of garbage collection and make the memory use more effective?

    A. Use object pooling and weak object references.

  18. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

    A. If these classes are threads then consider notify() or notifyAll(). For regular classes one can use the Observer interface.

  19. How will you sort a collection object?

    // Sort

    // Case-insensitive sort
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

    // Reverse-order sort
    Collections.sort(list, Collections.reverseOrder ());

    // Case-insensitive reverse-order sort
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

  20. In a Java class, one has 10 variables. One wants to serialize only 3 variables,how can this be achieved?

    A.Make variables as 'transient' which are not to be serialized.

Continue reading...

Sunday, August 30, 2009

Collection APIs Related Interview Questions

You may like to read following posts before going through the list of questions mentioned on Collections APIs in this post:
  1. Questions on java.util.* and* package

  2. Core Java Questions With Short Answers
Q. How will you synchronize a collection?
A. The code sample given below elaborates on synchronization of various collection objects:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

public class CollectionSynchronization {
public static void main(String[] args) {
Collection collection = Collections.synchronizedCollection(new ArrayList());
List list = Collections.synchronizedList(new ArrayList());
Set set = Collections.synchronizedSet(new HashSet());
Map map = Collections.synchronizedMap(new HashMap());
SortedMap sortedMap = Collections.synchronizedSortedMap(new TreeMap());
SortedSet sortedSet = Collections.synchronizedSortedSet(new TreeSet());
Q. Why is it advisable to override hashCode() method as well, when equals() method is overridden?
A. When equals() method is overridden, then each object must have same hashcode for pair of objects which have equals() method overridden.If the .hashCode() method of your custom class doesn't work the same way your .equals() method works, the results of your code will be erroneous.

Q. If a collection object has duplicate values then how will you convert into a collection having unique values?
A. Here goes the listing:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class CollectionExample {
public static void main(String[] args) {
ArrayList list = new ArrayList();
Set set = new TreeSet(list);
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String str= (String);



Q. How will you address the scenario given below to decide on collection object to work with:
- Multiple keys with multiple values
- Multiple keys with single value
- Single key with multiple values
- Single key with single value
A. In the given scenario, HashMap will be the best choice. As long as the keys are unique, one can enter multiple values in an ArrayList and associate this with a key inside HashMap and retrieve those multiple values from unique key.

Q.How to get a TreeSet from a TreeMap?
A.The possibility of creating a TreeSet from the keyset of TreeMap.Check the example given as below:
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class CollectionExample {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap();
treeMap.put("1", "Apple");
treeMap.put("2", "Mango");
treeMap.put("3", "Guvava");
treeMap.put("4", "Banana");
treeMap.put("5", "Grapes");

Set set = new TreeSet(treeMap.keySet());
Iterator iterator = set.iterator();

while (iterator.hasNext()) {
String str = (String);
System.out.println("" + str);

Q.How a TreeSet different from HashSet?
A.One line answer is : TreeSet contains-> Unique and Ordered/Sorted values(as per natural order or based on Comparator implemented logic).It is backed by TreeMap.

While HashSet contains-> Unique values but not Ordered/Sorted

The example given below will explain the same:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class CollectionExample {
public static void main(String[] args) {
Set hashSet = new HashSet();
Set treeSet = new TreeSet();



private static void addElements(Set aTreeSet) {

The Output is:

HashSet:[2, 4, 6, 1, 7]
TreeSet[1, 2, 4, 6, 7]
Q.A practical problem, I want to choose a collection object which allows me to put only unique values inside it and in the same order as it is coming out of a database, here data from the database can contain duplicate values.What collection object will you choose?

LinkedHashSet uniqueData = new LinkedHashSet(dataFromDB);
Q. What is the initial capacity of Vector?
A. 10. Try out the code given below:

import java.util.Set;
import java.util.Vector;

public class CollectionExample {
public static void main(String[] args) {
Vector vector = new Vector();
int capacity = vector.capacity();
System.out.println("Capacity:" + capacity);

The Output is:

An article on JavaWorld on Collections' API
Continue reading...

Saturday, July 4, 2009

Short Questions On Java

Q.If I am extracting data from database which is have redundancy and not sorted, which collection object will you choose in order to make this data unique and sorted?
A. TreeSet
An Example
import java.util.*;

public class TreeSetExample {

public static void main(final String[] args) {
TreeSet treeset = new TreeSet();
System.out.println("TreeSet with Prez:");
Iterator iterator = treeset.iterator();
while (iterator.hasNext()) {
Object object =;

The Out put of the program is:

TreeSet with Prez:

Q. Is GC a high priority thread?
A. No, it is low priority thread.

Q.Does Java supports multi-dimensional arrays?
A.No, Java supports nested arrays only.

Q. What will a following division return? float value= 200.00/0.0.
A. NAN(Not a Number) instead of Exception

Q. Can local vairables be declared as static ?
A. No, local variables cannot be static. Only member variables be declared as static.

Q.What are the special cases in which serialization cannot happen?
A. There are following scenarios in which serialization cannot happen:

a. Variables are transient.
b. Variables are static.
c. Base class variables are serialized if class itself is serializable.

Q.When a class or interface can be unloaded ?
A. A class or interface can be unloaded if and only if the classloader is unreachable. Though in case of system classes, they may never be unloaded as bootstrap class loader is always reachable.

Q.What are the different states that an object can be in during its life cycle?
A.An object goes through most of the following states during its life cycle, from creation to the point when all the resources associated with it are released for reuse:

-Created-In use (strongly reachable)

Q.Where do we use enums and how are they different from public,static,final constants?
A. If there are constants which are unlikely to change in future then they can be defined using enum. Take four directions EAST,WEST,NORTH,SOUTH for example which will never change and is best suited while defined in enum.
Moreover public static final constants are not typesafe. While enums can be used for switch case scenarios, are serializable.

public enum Direction { EAST, WEST, NORTH, SOUTH }
The detailed answer can be found here.
Continue reading...

Monday, October 8, 2007

Give an example where upcasting takes advantage of polymorphism.

Here it goes:

class Parent { }

class Child extends Parent { }

Child can be referred as an object of type Parent or Child.

Upcasting works like this:

Child aChildObj = new Child();

Parent aParentObj = (Parent)aChildObj;

As aChildObj can be referred to by the class names Child and
Parent,you can say that this upcasting and type extension is the
implementation of polymorphism in Java.

Continue reading...

Tuesday, June 19, 2007

Interview Questions on*

Continue reading...

What are different socket options?

The different Socket options are :


They may be specified in various scenarios e.g. one might like to specify a timeout for read operations, to control the amount of time a connection will linger for before a reset is sent, whether Nagle's algorithm is enabled/disabled, or the send and receive buffers for datagram sockets.

Continue reading...

How can you get the hostname on the basis of IP addres ?

The following snippet of code helps you in finding hostname on the basis of IP address:-

InetAddress inetAddress = 
System.out.println ("Host Name: " 
+ inetAddress.getHostName());

Continue reading...

How do you know who is accessing your server?

In case of TCP protocol i.e. ServerSocket:

Each Socket connection accepted corresponds to who is connecting to your server, that means relevant method calls on ServerSocket will fetch IP address and port of the same.

Socket socket = serverSocket.accept();

// Print IP address and port
System.out.println ("Connecting from : " +
socket.getInetAddress().getHostAddress() + ':' + socket.getPort());

In case of UDP i.e. DatagramSocket

The DatagramPacket received contains all the necessary information:

DatagramPacket datagramPacket = null;

// Receive next packet
datagramSocket.receive ( datagramPacket );

// Print address + port
System.out.println ("Packet received from : " +
datagramPacket.getAddress().getHostAddress() + ':' + datagramPacket.getPort());

Continue reading...

What should I use a ServerSocket or DatagramSocket in my applications?

DatagramSocket accepts only UDP packets, whereas ServerSocket allows TCP connections in an application. It depends on the protocol one implements. Here are few things which one should keep in mind while implementing a new protocol:

-UDP is not a reliable protocol as you may loose data packets over the network so while coding you will have to handle missing packets in your client/server.

-ServerSockets use TCP connections for communication.TCP is safe and reliable protocol and guarantees delivery, all you need is InputStream to read and OutputStream to write over TCP.
Continue reading...

How can you display a particular web page from an applet?

The following code snippet shows you how to achieve that using showPage method is capable of displaying any URL passed to it.

import java.awt.*;
import java.applet.*;

public class TestApplet extends Applet
// Applet code goes here

// Show a page
public void showPage ( String showPage)
URL url = null;

// Create a URL object
url = new URL ( showPage );
catch (MalformedURLException e)
// Invalid URL

// Show URL
if (url != null)
getAppletContext().showDocument (url);

Continue reading...

Friday, May 18, 2007

How is JDO(Java Data Object) different from VO(Value Object) ?

JDO is
- a persistence technology
-allows you to create POJOs (plain old java objects) and persist them to the database
Value objects
-usually referred as data holders but the correct term is DTO:
-represent an abstract design pattern used in conjunction with entity beans, JDBC, and possibly even JDO to overcome commonly found isolation and transactional problems in enterprise apps.
- do not allow you to persist objects - they are simple data holders used to transfer data from the database to the client and back to the database.
Continue reading...

Friday, May 11, 2007

Questions on Assertions

Continue reading...

What situations are best suitable for implementing assertions?

Assertions can best be implemented :
- As Internal Invariants
- As Control flow Invariants
- As Preconditions and Postconditions
- As Class Invariants

Internal Invariants:

Assertions can be used in if-statement construct where asserting an invariant is obvious.
Before assertions were available: the following code snippet could be replaced
if (k % 3 == 0) {
} else if (k % 3 == 1) {
} else { // as is obvious (k % 3 == 2)


if (k % 3 == 0) {
} else if (k % 3 == 1) {
} else {
assert k % 3 == 2 : k;

Another good example for an assertion is a switch statement with no default case. An absence of default indicates that a programmer believes that one of the cases will always be executed. The assumption that a particular variable will have one of a small number of values is an invariant that should be checked with an assertion. For example, suppose the following switch statement appears in a program that handles playing cards:

switch(condition) {
case condition.ONE:

case condition.TWO:

case condition.THREE:

One should add the following default case:

assert false : condition;
If the 'condition' variable takes on another value and assertions are enabled, the assert will fail and an AssertionError will be thrown.

An acceptable alternative is:

throw new AssertionError(condition);

Control flow Invariants

One of the most significant use of assertion is in placing it at any unreachable location. The assertions statement to use is:
assert false;

For example:
void testMethod() {
for (...) {
if (...)
// Execution should never reach this point!!!
Replace the final comment so that the code now reads:

void testMethod() {
for (...) {
if (...)
assert false; // Execution should never reach this point!
According to JLS if a program contains an unreachable code then it faces compile time error,if asserted that it is not reached.Another alternative for this could be throwing AssertionError.

Assertion do not support design by contract facility formally but some level of this feature can be used by using them.The set of preconditions ,postconditions and class invariant give that leverage to implement design by contract.

It means what set of conditions that must be satisfied before executing a method.A public method always guarantees checking of its arguments so use of assertions should be avoided in case of public methods.One can use an assertion to test a nonpublic method's precondition that will be true no matter what a client does with the class.

An assert can be applied in case of multithread blocks or methods which are private to ensure whether a lock on the object is retrieved before actually executing the code within.

The postcondition can be tested with assertions in both public and nonpublic methods. For example, the following public method uses an assert statement to check a post condition:
A simple operation of pushing an element on a stack can have a precondition that the element going to be pushed have a position less than the capacity of the stack and while element being pushed over the stack, it is equally important that new index is equal to old index plus one alongwith surety of an element being pushed on stack.This could be done using assertion as an example shown below:

public void push(int element) {
// precondition
assert num<capacity : "stack is full";
int oldNum = num;
stack[num] = element;
// postcondition
assert num == oldNum+1 && stack[num-1] == element : "problem with counter";

Class Invariants
A class invariant is applicable to every instance of a class at all times, except when an instance is in transition from one consistent state to another. A class invariant can specify the relationships among multiple attributes, and should be true before and after any method completes.

Continue reading...

When assertions should be avoided?

In following situations the assertions should be avoided:
-When assertion becomes a performance issue.It means an assertion should not include too complex logic equalling implementation of a method.
-Do not use assertions in argument checking of public methods.As argument checking is part of a method implementation and if these arguments are erroneous then it will throw runtime exception and assertion failure will not result in any error.

Continue reading...

Explain Assertions with a code example

The main reason of introducing assertions in Java from R1.4 onwards is to reduce the chances of bugs which otherwise would have gone unnoticed, in one's code.In fact, finding and removing bugs is one tedious and not so exciting task.Assertions should be used for scenarios which ideally should never happen in the lifecycle of a program,check assumptions about data structures (such as ensuring that an array is of the correct length), or enforcing constraints on arguments of private methods.Assertions help in a way to block these bugs at the beginning of writing actual logic inside your code that saves lot of efforts,time and most significantly, costs.A simple assertion facility provides a limited form of design-by-contract programming.In design-by-contract programming identification of preconditions and post conditions to a program are must before even starting the coding itself.

Here is simple Java code which uses assertions, here the task is to determine the gender of a person.We have used a switch-case statement to define the over all flow of the logic :

Use J2SE 1.4.x (or later versions) to compile ExampleAssertions, make sure you use the -source option as follows:

javac -source 1.4

If you try to compile your assertion-enabled classes without using the -source 1.4 option, you will get a compiler error saying that assert is a new keyword as of release 1.4. If you now run the program using the command and you enter a valid character, it will work fine. However, if you enter an invalid character, nothing will happen.

This is because, by default, assertions are disabled at runtime.You have to enable assertions to make them work.Use the switch -enableassertion (or -ea) as follows:

java -ea ExampleAssertions
java -enableassertion ExampleAssertions

Following is a sample run:

When assertion fails it throws AssertionError.By default assertions are disabled but once enabled and you wnat to disable them then use switch -diableassertion (or -da).

Diabling assertions for a particular class in a package:

java -da:com.punsoft.acc.Account SavingAccount , this means running class SavingAccount with assertions of Account class disabled.

java -da:com.punsoft.acc... SavingAccount, this means running class SavingAccount with assertions of 'acc' package and its subpackages disabled.

You can use combination of enable and disable assertions.

java -ea:com.punsoft.acc... -da:com.punsoft.view.acc SavingAccountView

If you use the command
java -ea SavingAccount

then assertions are enabled in all classes except system classes. If you wish to turn assertions on or off in system classes, use the switches -enablesystemassertions (or -esa) and -disablesystemassertions (or -dsa).
Continue reading...

How many forms of assertions we have?

There are two forms of assertions:

The first, simpler form is:

assert Expression1 ;
where Expression1 is a boolean expression.
When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
While the second form of the assertion statement is:

assert Expression1 : Expression2 ;

Expression1 is a boolean expression.
Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)

This form is used when the assert statement has to provide a detail message for the AssertionError.The system passes the value of Expression2 to the appropriate AssertionError constructor, and this constructor uses the string representation of the value as the error's detail message. This detail message helps in analysing and diagnosing the assertion failure which ultimately helps in resolving the error.

Continue reading...

What is an Assertion and why using assertion in your program is a good idea ?

In a Java program,several times, one would like to make certain assumptions for executing a program.For example,while taking a square root of a numeric value it has to be assumed that this value should not be negative.An assertion is a statement in the Java programming language that enables to test assumptions about one's program.Assertions are supported from J2SE1.4 and later.A simple exmaple of assertion can be checking of an employee object from being null:

Employee employee = null;

//Get an Employee object

//Ensure we have one
assert emplyee!= null;

This asserts that an employee is not null. If employee is null, an AssertionError is thrown. Any line of code executing after the assert statement can safely assume that employee is not null.

Each assertion is a boolean statement when an assertion executes,it returns true and when it returns false then an error is thrown.So successful execution of an assumption will ensure an error free code.By including assertions in one's program,the following objectives can be achieved:

-The quickest way of identifying and correcting bugs.
-The code becomes less prone to errors hence better maintained against errors and more efficient.
-Better readability of code.

Continue reading...

Monday, May 7, 2007

What is difference between trusted and untrusted applet?

A trusted applet is one which signed by a trusted authority. The trusted applet is installed on the local hard disk, in a directory on the CLASSPATH used by the program that you are using to run the applet. Usually, this is a Java-enabled browser, but it could be the appletviewer, or other Java programs that know how to load applets.

The applet is signed by an identity marked as trusted in your identity database.By default all applets downloaded in client browser are untrusted.
-They cannot read or write files to clients' local file system at all.
-They cannot start a program at client's machine.
-They cannot do network operations i.e. cannot do Socket programming.
-They cannot load libraries and use native codes.
Continue reading...

What is the difference between Java class and bean?

What differentiates Beans from typical Java classes is introspection. The tools that recognize predefined patterns in method signatures and class definitions can "look inside" a Bean to determine its properties and behavior. A Bean's state can be manipulated at the time it is being assembled as a part within a larger application. The application assembly is referred to as design time in contrast to run time. In order for this scheme to work, method signatures within Beans must follow a certain pattern in order for introspection tools to recognize how Beans can be manipulated, both at design time, and run time.
Continue reading...

Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker