Welcome!

From the Trenches of the Enterprise Software

Yakov Fain

Subscribe to Yakov Fain: eMailAlertsEmail Alerts
Get Yakov Fain via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Related Topics: Java EE Journal, Java Developer Magazine

J2EE Journal: Article

Secrets Of The Masters: Core Java Job Interview Questions

JDJ Enterprise Editor Yakov Fain Offers 30 Core Java Questions You Might Expect During Job Interviews

JDJ's Enterprise Editor, Yakov Fain (pictured) writes: If you are planning to hit the job market,  you may need to refresh some of the Java basic terms and techniques to prepare yourself for a technical interview. Let me offer you some of the core Java questions that you might expect during the interviews. 

For  most questions  I’ve provided only  short  answers to encourage further research.  I have included only  questions for mid (*) and senior level (**) Java developers. These sample questions could also become handy for people who need to interview Java developers (see also the article "Interviewing Enterprise Java Developers").

Disclaimer. This article has been originally published three or four years ago, hundreds of thousands Java developers have read it, but I still use some of these questions while interviewing Java developers. Guess what? Every other Java developer doesn't now the answers to some of them.

30 Java Interview Questions

* Q1. How could Java classes direct 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 st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

* Q2. What's the difference between an interface and an abstract class?

A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

* Q3. Why would you use a synchronized block vs. synchronized method?

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

* Q4. Explain the usage of the keyword transient?

A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

* Q5. How can you force garbage collection?

A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

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

A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:

Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

* Q7. 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.

* Q8. 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.

* Q9. What's the difference between constructors and other methods?

A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

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

A. Yes. Use this() syntax.

* Q11. Explain the usage of Java packages.

A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

* Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

c:\>java com.xyz.hr.Employee

* Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?

A.There's no difference, Sun Microsystems just re-branded this version.

* Q14. What would you use to compare two String variables - the operator == or the method equals()?

A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

* Q15. 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.

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

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

* Q17. 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.

* Q18. What's the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.

* Q19. When should the method invokeLater()be used?

A. This method is used to ensure that Swing components are updated through the event-dispatching thread.

* Q20. How can a subclass call a method or a constructor defined in a superclass?

A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Comments (176) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Asavari 09/06/06 02:29:00 AM EDT

Hi
I need core java,JDBC,JSP and servlet related material to prepare thoroughly.

Thanx in advance

AShvini 09/05/06 07:51:42 AM EDT

Sir/Madam, I need Core java, J2EE interview questions. I am in java and j2ee field since last 2 years. Thanks. Kindly do the needful.

Regards,
Ashvini

Manish Patel 09/04/06 09:24:47 PM EDT

Sir,

I need J2EE interview questions. I am in java and j2ee field since last 3 years.

Thanks

jo 08/25/06 04:42:46 AM EDT

plz send me java/j2ee/servlets/hibernate/spring/webwork questions.

Swapnali 08/21/06 07:27:54 AM EDT

Hi,
please send me interview questions in core java,jdbc,servlet,jsp,struts

Samrat Banerjea 08/19/06 02:34:05 AM EDT

The saddest part of all these feedback(s) are most of the respondents are simply asking "send me Java* ... questions for n+ yrs".They are not actually adding anything other than that the list goes on increasing. I think they should ask some pertinent questions based on the areas they are working OR intending to work.One way of learning things is by asking Questions to oneself.Experts/Gurus may help us find answers or show us different aspects of things.Should they feed us with the Questions?
Regards,

Praveen 08/18/06 12:02:32 PM EDT

please send java/j2ee questions for 2 yrs exp.

sujit singh 08/17/06 03:14:04 PM EDT

please send j2ee,struts,hibernate,ejb,xml JDBC interview questions for 2 year exp.

usman 08/17/06 08:28:17 AM EDT

Hi,
please send me interview questions in core java,jdbc,servlet,jsp,struts which is generally asked for 2+ years experience

surender 08/05/06 12:20:34 AM EDT

Hi,
please send me interview questions in core java,jdbc,servlet,jsp,struts which is generally asked for 2+ years experience
and aslo ibm,satyam interview questions.

Pranay Bhawsar 08/02/06 07:00:33 AM EDT

Hello Sir,

Pls send me Java 2+ year Questions. Thank You

karthik 08/01/06 03:42:49 AM EDT

i need structs question&answer paper

shahbaz ahmad 07/31/06 02:57:44 AM EDT

Hi,
please send me interview questions in core java,jdbc,servlet,jsp,struts which is generally asked for 2+ years experience.

Shalini Gupta 07/31/06 01:19:09 AM EDT

Hi, Please send the interview questions from CoreJava,Jsp,Servlets,JDBC,Struts which are generally being asked with 2 years experience.

It will be a great help.Can u do this for me.

sabitha 07/28/06 08:14:26 AM EDT

Need interview questions on Javascript

Dennis Bednar 07/15/06 12:43:02 AM EDT

Another gripe that I have with this blog
is that the indentation of the Main.java
source file that I just submitted is
completely lost. All lines appear without
any leading whitespace, even though there
*IS* leading whitespace in lines of my source file.

Dennis Bednar 07/15/06 12:35:54 AM EDT

I have some some suggestions for improving the
answer for Q6.

Please refer to the attached source file,
and read the comments at the top for
all of the gory details.

// Main.java
// dennis bednar 2006-07-14
//
// Lessons:
// While researching this topic (question #6 of 30 from this article):
//
// http://jdj.sys-con.com/read/48839.htm
//
// Q6. How do you know if an explicit object casting is needed?
//
// A. If you assign a superclass object to a variable of a subclass's
// data type, you need to do explicit casting. For example:
// Object a; Customer b; b = (Customer) a;
// When you assign a subclass to a variable having a superclass type,
// the casting is performed automatically.
//-----------------------------------------------------------
//
// Definition:
// RHS = Right Hand Side of an = sign of an assignment statement.
// LHS = Left Hand Side of an = sign of an assignment statement.
//
// ----------------------------------------------------------
//
// MORE INFO regarding A (answer) THAT THE ABOVE ARTICLE DOES NOT SAY:
//
// (A minor issue):
// First of all, the above snippet won't even compile, due to a lack
// of assigning any value to a. The RHS a gets a compile time error
// on the "b = (Customer) a;" assignment.
// This problem is illustrated in Simple1.java file and is fixed
// in the Simple2.java file.
// The simplest way to fix this problem, and what the Yakov article should
// have said is this:
// Object a = null; Customer b; b = (Customer) a;
//
// (A Major issue):
// Furthermore, when you do the
// b = (Customer) a;"
// the a on RHS (right hand side) being cast has to be a null OR a
// reference to a Customer object or an object which is a sub-class of Customer,
// otherwise you will get a ClassCastException at run-time.
// (exception happens when a != null, but a references
// an object that is not a Customer nor a sub-class of Customer).
// Please note that the Main.java code will compile fine, though.
//
// For example, in test1() is okay at run-time, but test2() gets
// a ClassCastException.
//
// In test3() we test with RHS being a null to show that no
// ClassCastException problem will occur like in test2().
//
// In test4() we try a variant of test1(), where we use a sub-class of
// Person, by using the Professor class (Person -> Professor, where
// Base -> Derived).
//
//
// -------------------------------------------------------------
//
// SHORT REVISED SUMMARY ANSWER (what Yakov should have answered)
//
// A. If you assign a superclass object to a variable of a subclass's
// data type, you need to do explicit casting. For example:
// Object a = null; Customer b; b = (Customer) a;
// When you assign a subclass to a variable having a superclass type,
// the casting is performed automatically.
//
// Furthermore, in order to be able to do the assignment, the RHS (a)
// must be either a null, a reference to a Customer object, or a
// reference to an object which is a sub-class of Customer. Otherwise
// at run-time, you will get a ClassCastException.
// (exception happens when a != null, but a references
// an object that is not a Customer nor a sub-class of Customer).
//
public class Main
{
public static void main( String[] argv )
{
// NB: we call test3() *before* test1() because if we called
// test3() last, we would never get there, since
// test2() would halt the program with an Exception
// We added test3() last, and I didn't want to revise
// any comments.
//
// Historically, while writing this module, I wrote
// test1..test4 in that order.
// Similarly, we call test4() before test1() for similar
// reasons.

test3();
test4();
test1();
test2();
}

// test1 runs okay without any problems
// no problems casting (no ClassCastException at run time)
private static void test1()
{
Object root = new Object();
Person p = new Person();

// will print ok, since p ISA person
System.out.println( "test1A: Person: " + p );

root = p; // okay to assign subclass to superclass wo cast

// p = root; // COMMENT_OUT: cuz compile time error wo cast

// but to assign super to sub, requires a cast
// *and* root must be a Person or sub-class of Person,
// otherwise ClassCastException
// Now, since root ISA Person, this is okay.
p = (Person) root;
System.out.println( "test1B: cast test: " + p );
}

// Test2() gets a ClassCastException.
// In test2(), root is an Object, so "p = (Person) root" will get
// ClassCastException at run-time. This proves that Java does
// a run-time sanity check to prevent garbage references from
// being assigned into variables (this helps to prevent other
// future run-time errors ahead of time, which is a very good
// feature of Java).
//
private static void test2()
{
Object root = new Object();
Person p = new Person();

// will print OK, since p ISA person
System.out.println( "test2A: Person: " + p );

p = (Person) root; // ClassCastException, even with cast

// won't even get here, so no way to try this experiment!
//System.out.println( p ); // exception since p !ISA person
}

// test3 executes OK. It is based on test2() except that
// we assign RHS of root and p variables with null instead
// of calling new(). Unlike test2(), there is
// no ClassCastException because the RHS (root) of this statement:
// p = (Person) root;
// is null.
private static void test3()
{
Object root = null;
Person p = null;

// will print OK (as null), since p ISA null value
System.out.println( "test3A: Person: " + p );

p = (Person) root; // !ClassCastException since root==null

// we will now get here, so we can try this experiment
System.out.println( "test3B:" + p ); // prints null
}

// test4 runs okay.
// variant of test1, except that p is a Profess (a sub-class of Person)
private static void test4()
{
Object root = new Object();
Person p = new Professor();

// will print ok, since p ISA Person
System.out.println( "test4A: Person: " + p );

root = p; // okay to assign subclass to superclass wo cast

// p = root; // COMMENT_OUT: cuz compile time error wo cast

// but to assign super to sub, requires a cast
// *and* root must be a Person or sub-class of Person,
// otherwise ClassCastException
// since root ISA Person, this is okay
p = (Person) root;
System.out.println( "test4B: cast test: " + p );
}
}

// Person: a simple empty class without any instance vars"
class Person
{
public String toString()
{
return "PERSON(SIMPLE)";
}
}

// a sub-class of Person, used for test4().
class Professor extends Person
{
}

Dennis Bednar 07/15/06 12:23:27 AM EDT

Strange: 2 posts earlier,
when I pasted my entire source file
this blog erased part of the code that I had
submitted.

The (generics style declaration of:
<, Integer, >

(without commas)

strings were translated into nothing mysteriously. This is the required for List, ArrayList, and LinkedList.

Here are what 2 of the lines should read:

List{Integer} al = new ArrayList{Integer}();
List{Integer} ll = new LinkedList{Integer}();

In the above, change the { (left brace) to < (less than)
In the above, change the } (right brace) to > (greater than).

There is something wacky about this web site that
is preventing me from submitting EXACTLY what I typed
(less than, Integer, greater than). The preview
engine is doing some mysterious translation on
text input that begins with a < sign and ends with a >
sign.

Dennis Bednar 07/15/06 12:00:19 AM EDT

PS: here's the output of running the Main.java program
for my previous post (which I forgot to include):

C:\temp\java\ArrayListVsLinkList>del *.class

C:\temp\java\ArrayListVsLinkList>javac -cp . -Xlint:unchecked -source 1.5 Main.java

C:\temp\java\ArrayListVsLinkList>java -cp . Main
ArrayList=[5, 7, 9, 11]
LinkList =[5, 7, 9, 11]
ArrayList[0]=5
ArrayList[1]=7
ArrayList[2]=9
ArrayList[3]=11
LinkedList[0]=5
LinkedList[1]=7
LinkedList[2]=9
LinkedList[3]=11
ArrayList=[5, 77, 9, 11]
LinkList =[5, 99, 9, 11]

Dennis Bednar 07/14/06 11:57:02 PM EDT

I think the answer to Q26 can be either ArrayList or LinkedList, since both support indexed operations. List is the interface
and both ArrayList and LinkedList are concrete
classes of the List interface.

Proof (compile with JDK 1.5 for Generics):

import java.lang.Integer;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;

public class Main
{
public static void main( String[] argv )
{
List al = new ArrayList();
List ll = new LinkedList();

for (int i = 5; i < 13; i += 2 )
{
// wrapper integer
Integer wi = new Integer( i );

al.add( wi ); // add to end of ArrayList
ll.add( wi ); // add to end of LinkedList
}

// print out both collections
System.out.printf("ArrayList=%s\n", al );
System.out.printf("LinkList =%s\n", ll );

// now access them using an array[index] style
for (int inx = 0; inx < al.size(); ++inx)
{
System.out.printf( "ArrayList[%d]=%d\n", inx, al.get(inx) );
}

// access them using an array style of index
for (int inx = 0; inx < al.size(); ++inx)
{
System.out.printf( "LinkedList[%d]=%d\n", inx, ll.get(inx) );
}

// change ArrayList[1] = 77
// change LinkedList[1] = 99
al.set(1, new Integer( 77) );
ll.set(1, new Integer( 99) );

// print out both collections after modification
System.out.printf("ArrayList=%s\n", al );
System.out.printf("LinkList =%s\n", ll );
}
}

Premila 07/11/06 07:52:54 AM EDT

Hi,
Immediately I want Java&J2ee Interview Questions in 2 yrs of experience level. Thank U.

Yakov Fain 07/09/06 01:34:29 PM EDT

J.T., I've answered your post over here:

http://yakovfain.javadevelopersjournal.com/is_publishing__of_the_technic...

sujit singh 07/09/06 12:58:17 PM EDT

please send j2ee,struts,hibernate,ejb,xml JDBC interview questions for 2 year exp.
sujit412@gmail.com

Haug Bürger 07/09/06 09:44:31 AM EDT

I found a coupe of questions quite unclear or misleading.

Q1: We punish developers who use system out for general classes. Most java programs do not use a console and you reduce the reusability. The logging framework coming with the JDK is exactly designed for this purpose. Or use any other logging framework.

Q6: Do you mean primitive data types or object types. It's like the question I once read. "How fast is a CD ROM? If I drive around with it most likely over 100km/h. Or do you mean the interface performance? The maximum read performance? The performance factor on the box?

Q10: You can not call a constructor! You can use it but not call it. This is a major difference between a method and a constructor. And your answer implies that you mean the constructor of a parent class not a general call.

Q12: This is again misleading. You do not change the OS environment. If you define an environment variable like classpath it simply does not work on Windows environments. What you do is adding it to the known classes of the runtime environment.

Q14: Again a question like "What would you use for cutting?". The anser has to be, "It depends on what you want to cut". Better ask for the difference between == and equals.

Q16: I simply do not understand. Is it an English sentence?

Q28: Ths first part is really misleading because the first part is simply not true. You still nead the garbage collection to get rid of your objects. The only way to minimise is to avoid object creation.

Q29: Give a hint that you want two ansers and that you think about threads.

It is a nice collection of questions.

Regards
Haug

J.T. Wenting 07/09/06 03:42:25 AM EDT

Don't you think people should already know the answers to those questions before applying for a job?

You've given kids with no experience but a faked resume a prime source to cram questions and answers to trick themselves into jobs by writing this, thank you very much for making programmers as a group look bad (by making it possible for even more unqualified people to get programming jobs).

p.subathra 07/08/06 05:56:37 AM EDT

hi,
I need the type of questions asked in an interview for a job in java/j2ee with about 2 years experience.

prasanna 07/07/06 01:25:45 AM EDT

pls forward the list of questions that can be asked for 2+ years exp in java(core,advanced and j2ee)

prathap 07/04/06 10:25:50 AM EDT

Hi,
please send me 1.5+ year exp java/j2ee,jsp/servlets ,JDBC questions for the interview.

Ashish 07/03/06 12:15:08 PM EDT

Hello
Any body out there who can help in getting the objective questions(with answers)for whole java (core and advace and jsp servlet struts ejb)

praveen 07/03/06 11:44:10 AM EDT

i need objective question for jsp,servlet,xml J2ee

Samrat Banerjea 06/29/06 02:27:08 AM EDT

Please note :
question no [3] is actually
[3]is the following a valid statement in java
I had actually given the complete URL of this page, the page optimized this to
[visit link]. Please interpret this to be the whole URL.

Samrat Banerjea 06/29/06 02:19:52 AM EDT

Thank you very much.
Great Questions set{}!!!
___________________________________________
Would you please consider these questions
[1]. is println() of System.out a synchronized method?
[2].How are the two following statements different as to the nature of '+'
(a)int a=0,b=1;
int c = a+b;
(b)System.out.println(a+b);
(c)System.out.println(""+a+b);
[3]is the following a valid statement in java
http://it.sys-con.com/read/48839_f.htm
[4]Is it a good practice to return null or should we return a 'zero-length array'?
[5]What is the type of null ?
[6]When can we throw a new Exception but not explicitly catch it.Is it possible?
[7]What is a root-set in Garbage Collection
[8]I'm iterating over an iterator drawn from a Vector object.However,meanwhile I remove an element from the same Vector object. Will iteration still be continued, or what will happen?
[9].Does Inheritance breaks Encapsulation?
[10].Is there any instance/situation in Java, when circular reference is actually is used?

sujit singh 06/27/06 11:39:28 AM EDT

please send j2ee,struts,hibernate,ejb,xml JDBC interview questions for 2 year exp.

SYS-CON Italy News Desk 06/27/06 08:59:12 AM EDT

If you are planning to hit the job market, you may need to refresh some of the Java basic terms and techniques to prepare yourself for a technical interview. JDJ Enterprise Editor Yakov Fain here offers thirty of the core Java questions that you might expect during the interviews, 20 for mid-level developers and the final ten for senior-level developers. Why not try them and see how well you do?

JDJ News Desk 06/27/06 08:03:52 AM EDT

If you are planning to hit the job market, you may need to refresh some of the Java basic terms and techniques to prepare yourself for a technical interview. JDJ Enterprise Editor Yakov Fain here offers thirty of the core Java questions that you might expect during the interviews, 20 for mid-level developers and the final ten for senior-level developers. Why not try them and see how well you do?

sunil 06/27/06 07:21:22 AM EDT

please send java/j2ee,jsp/servlets ,ejb,xml JDBC interview questions for 2 year exp.

abhishek yadav 06/26/06 01:08:53 AM EDT

please send me 1.5+ year exp java/j2ee,jsp/servlets ,JDBC questions for the interview.

Neeraj Kumar 06/23/06 02:59:40 AM EDT

Hi,

I have 1.5 years exp in java.
plz send me java/j2ee/servlets/jsp/struts/hibernate questions.

Thanks

raj 06/19/06 09:05:36 AM EDT

Tell me about technical questions regarding real time project in Trading,banking,telecom domain..
And also suggest some of the books related to Interview questions on Java projects,Struts,EJB..

Thank You

surya sagar 06/19/06 03:06:04 AM EDT

sir,
Tell me some questions regarding core java that are important for interviews and also suggest me about the books of core java.

S.Nandhini Kumari 06/18/06 04:55:34 AM EDT

Hi.
I have 1 years of experience.I need the type of questions asked in interviews on java .could u plz help me.
Thank you very much.

hari prasad 05/29/06 05:32:44 AM EDT

Hi.
I have 3 years of experiance.I need the type of questions asked in interviews on java/j2ee.could u plz help me.
Thanking very mutch.

rajeev kumar 05/26/06 05:39:35 AM EDT

please send me 1+ year exp java/j2ee,jsp/servlets questions for the interview.

Anil Dudhe 05/24/06 09:00:28 AM EDT

Plz send me objective question for Servlet, JSP, Structs and JMS

kalaivani 05/19/06 09:30:20 AM EDT

Hi,
Please send me some questions from core java. and some important questions from jsp,servlets,struts

It will help for my career.

karthik 05/19/06 01:15:09 AM EDT

Please give me some core java and swing interview question.
thank you

pratyush 05/17/06 11:36:27 PM EDT

hi
i need interview questions for java, j2ee of 2yrs experience.
thank u
bye

Radhika Jonnalagadda 05/15/06 11:24:17 AM EDT

I need help with Java/J2EE interview questions for 5 years experience.Thank you in advance for your help.

Jitendra Soni 05/06/06 07:49:53 AM EDT

Hi,
I need to become a professional in Java/J2EE for this I need some help.
I am a software engineer working in Application Development department using Java technology.

Stephanie 05/03/06 03:53:56 PM EDT

I need the type of questions asked in an interview for a job in java/j2ee with about 2 years experience.

Thanks