Basic Java Interview Questions

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 37
At a glance
Powered by AI
Some common topics covered in Java interviews include OOP concepts, data structures, algorithms, design patterns, concurrency and core Java features.

Questions often focus on OOP concepts like inheritance, polymorphism, abstraction; data structures like lists, trees, hashmaps; algorithms like sorting, searching; design patterns like singleton, factory, observer; and core Java topics like exceptions, I/O, collections framework, JVM internals.

An interface can only declare constants and instance methods but cannot implement default behavior. An abstract class can declare abstract methods that subclasses must implement as well as non-abstract methods with default behavior.

Basic Java interview questions

1. Why do you prefer Java?

Answer: write once ,run anywhere.

2. Name some of the classes which provide the functionality of collation?

Answer: collator, rulebased collator, collationkey, collationelement iterator.

3. Awt stands for? and what is it?

Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated
set of classes to manage user interface components.

4. why a java program can not directly communicate with an ODBC driver?

Answer: Since ODBC API is written in C language and makes use of pointers which Java can not
support.

5. Are servlets platform independent? If so Why? Also what is the most common
application of servlets?

Answer: Yes, Because they are written in Java. The most common application of servlet is to
access database and dynamically construct HTTP response

6.What is a Servlet?

Answer: Servlets are modules of Java code that run in a server application (hence the name
"Servlets", similar to "Applets" on the client side) to answer client requests.

7.What advantages does CMOS have over TTL(transitor transitor logic)? (ALCATEL)

Answer:

• low power dissipation


• pulls up to rail
• easy to interface

8.How is Java unlike C++? (Asked by Sun)


Some language features of C++ have been removed. String manipulations in Java do not allow
for buffer overflows and other typical attacks. OS-specific calls are not advised, but you can still
call native methods. Everything is a class in Java. Everything is compiled to Java bytecode, not
executable (although that is possible with compiler tools).

9.What is HTML (Hypertext Markup Language)?

HTML (HyperText Markup Language) is the set of "markup" symbols or tags inserted in a file
intended for display on a World Wide Web browser. The markup tells the Web browser how to
display a Web page’s words and images for the user.

10.Define class.

Answer: A class describes a set of properties (primitives and objects) and behaviors (methods).

Advanced Java interview questions

1.In Java, what is the difference between an Interface and an Abstract class?

A: An Abstract class declares have at least one instance method that is declared abstract which
will be implemented by the subclasses. An abstract class can have instance methods that
implement a default behavior. An Interface can only declare constants and instance methods, but
cannot implement default behavior.

2. Can you have virtual functions in Java? Yes or No. If yes, then what are virtual
functions?

A: Yes, Java class functions are virtual by default. Virtual functions are functions of subclasses
that can be invoked from a reference to their superclass. In other words, the functions of the
actual object are called when a function is invoked on the reference to that object.

3.Write a function to reverse a linked list p in C++?

A:

Link* reverse_list(Link* p)
{
if (p == NULL)
return NULL;
Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
{
Link* t = p->next;
p->next = h;
h = p;
p = t;
}

return h;
}

4.In C++, what is the usefulness of Virtual destructors?

A:Virtual destructors are neccessary to reclaim memory that were allocated for objects in the
class hierarchy. If a pointer to a base class object is deleted, then the compiler guarantees the
various subclass destructors are called in reverse order of the object construction chain.

5.What are mutex and semaphore? What is the difference between them?

A:A mutex is a synchronization object that allows only one process or thread to access a critical
code block. A semaphore on the other hand allows one or more processes or threads to access a
critial code block. A semaphore is a multiple mutex.

Advanced enterprise Java interview questions

1) What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by
a program so that their resources can be reclaimed and reused. A Java object is subject to
garbage collection when it becomes unreachable to the program in which it is used.

2) Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control the access of multiple
threads to shared resources. Without synchonization, it is possible for one thread to modify a
shared variable while another thread is in the process of using or updating same shared variable.
This usually leads to significant errors.

3) How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components. On


the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized
business logic components.

4) In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures. It helps
them to choose design alternatives that make a system reusuable and avoid alternatives that
compromise reusability through proven techniques as design patterns.

5) Describe 3-Tier Architecture in enterprise application development.

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-
defined set of interfaces. The presentation layer typically consists of a graphical user interfaces.
The business layer consists of the application or business logic, and the data layer contains the
data that is needed for the application.

JSP interview questions

1. What are the most common techniques for reusing functionality in object-oriented

systems?

A: The two most common techniques for reusing functionality in object-oriented systems are class

inheritance and object composition.

Class inheritance lets you define the implementation of one class in terms of another’s. Reuse by

subclassing is often referred to as white-box reuse.

Object composition is an alternative to class inheritance. Here, new functionality is obtained by

assembling or composing objects to get more complex functionality. This is known as black-box

reuse.
2. Why would you want to have more than one catch block associated with a single try

block in Java?

A: Since there are many things can go wrong to a single executed statement, we should have

more than one catch(s) to catch any errors that might occur.

3. What language is used by a relational model to describe the structure of a database?

A: The Data Definition Language.

4. What is JSP? Describe its concept.

A: JSP is Java Server Pages. The JavaServer Page concept is to provide an HTML document

with the ability to plug in content at selected locations in the document. (This content is then

supplied by the Web server along with the rest of the HTML document at the time the document

is downloaded).

5. What does the JSP engine do when presented with a JavaServer Page to process?

A: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become Strings

transmitted to print methods of a PrintWriter object. The JSP tag portions result in calls to

methods of the appropriate JavaBean class whose output is translated into more calls to a println

method to place the result in the HTML document.

Java software engineering interview questions

1. What is the three tier model?


Answer: It is the presentation, logic, backend
2. Why do we have index table in the database?
Answer: Because the index table contain the information of the other tables. It will
be faster if we access the index table to find out what the other contain.
3. Give an example of using JDBC access the database.
Answer:
try
{
Class.forName("register the driver");
Connection con = DriverManager.getConnection("url of db", "username","password");
Statement state = con.createStatement();
state.executeUpdate("create table testing(firstname varchar(20), lastname varchar(20))");
state.executeQuery("insert into testing values(?phu?,'huynh?)");
state.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
4. What is the different of an Applet and a Java Application
Answer: The applet doesn?t have the main function
5. How do we pass a reference parameter to a function in Java?
Answer: Even though Java doesn?t accept reference parameter, but we can
pass in the object for the parameter of the function.
For example in C++, we can do this:

void changeValue(int& a)
{
a++;
}
void main()
{
int b=2;
changeValue(b);
}

however in Java, we cannot do the same thing. So we can pass the


the int value into Integer object, and we pass this object into the
the function. And this function will change the object.

Java applet interview questions

1. What is an Applet? Should applets have constructors?


- Applets are small programs transferred through Internet, automatically installed and run
as part of web-browser. Applets implements functionality of a client. Applet is a dynamic
and interactive program that runs inside a Web page displayed by a Java-capable
browser. We don’t have the concept of Constructors in Applets. Applets can be invoked
either through browser or through Appletviewer utility provided by JDK.

2. What are the Applet’s Life Cycle methods? Explain them? - Following are methods in
the life cycle of an Applet:
o init() method - called when an applet is first loaded. This method is called only
once in the entire cycle of an applet. This method usually intialize the variables to
be used in the applet.
o start( ) method - called each time an applet is started.
o paint() method - called when the applet is minimized or refreshed. This method is
used for drawing different strings, figures, and images on the applet window.
o stop( ) method - called when the browser moves off the applet’s page.
o destroy( ) method - called when the browser is finished with the applet.

3. What is the sequence for calling the methods by AWT for applets? - When an applet
begins, the AWT calls the following methods, in this sequence:
o init()

o start()

o paint()

When an applet is terminated, the following sequence of method calls takes place :

o stop()

o destroy()

4. How do Applets differ from Applications? - Following are the main differences:
Application: Stand Alone, doesn’t need
web-browser. Applet: Needs no explicit installation on local machine. Can be transferred
through Internet on to the local machine and may run as part of web-browser.
Application: Execution starts with main() method. Doesn’t work if main is not there.
Applet: Execution starts with init() method. Application: May or may not be a GUI.
Applet: Must run within a GUI (Using AWT). This is essential feature of applets.

5. Can we pass parameters to an applet from HTML page to an applet? How? - We can
pass parameters to an applet using <param> tag in the following way:
o <param name=”param1″ value=”value1″>

o <param name=”param2″ value=”value2″>


Access those parameters inside the applet is done by calling getParameter() method
inside the applet. Note that getParameter() method returns String value corresponding to
the parameter name.

6. How do we read number information from my applet’s parameters, given that


Applet’s getParameter() method returns a string?
- Use the parseInt() method in the Integer Class, the Float(String) constructor or
parseFloat() method in the Class Float, or the
Double(String) constructor or parseDoulbl() method in the class Double.

7. How can I arrange for different applets on a web page to communicate with each
other?
- Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method
in your applet code to obtain references to the
other applets on the page.

8. How do I select a URL from my Applet and send the browser to that page? - Ask the
applet for its applet context and invoke showDocument() on that context object.
9. URL targetURL;
10. String URLString
11. AppletContext context = getAppletContext();
12. try
13. {
14. targetURL = new URL(URLString);
15. }
16. catch (MalformedURLException e)
17. {
18. // Code for recover from the exception
19. }
20. context. showDocument (targetURL);
21. Can applets on different pages communicate with each other?
- No, Not Directly. The applets will exchange the information at one meeting place either
on the local file system or at remote system.

22. How do I determine the width and height of my application?


- Use the getSize() method, which the Applet class inherits from the Component class in
the Java.awt package. The getSize() method returns the size of the applet as a
Dimension object, from which you extract separate width, height fields. The following
code snippet explains this:
23. Dimension dim = getSize();
24. int appletwidth = dim.width();
25. int appletheight = dim.height();
26. Which classes and interfaces does Applet class consist? - Applet class consists of a
single class, the Applet class and three interfaces: AppletContext, AppletStub, and
AudioClip.

27. What is AppletStub Interface?


- The applet stub interface provides the means by which an applet and the browser
communicate. Your code will not typically implement this interface.

28. What tags are mandatory when creating HTML to display an applet?

1. name, height, width

2. code, name

3. codebase, height, width

4. code, height, width

Correct answer is d.

2. What are the Applet’s information methods?


- The following are the Applet’s information methods: getAppletInfo() method: Returns a
string describing the applet, its author, copyright information, etc. getParameterInfo( )
method: Returns an array of string describing the applet’s parameters.

3. What are the steps involved in Applet development? - Following are the steps
involved in Applet development:

o Create/Edit a Java source file. This file must contain a class which extends
Applet class.

o Compile your program using javac


o Execute the appletviewer, specifying the name of your applet’s source file or html
file. In case the applet information is stored in html file then Applet can be
invoked using java enabled web browser.

29. Which method is used to output a string to an applet? Which function is this
method included in? - drawString( ) method is used to output a string to an applet. This
method is included in the paint method of the Applet.
Java interview questions

1. What is the Collections API? - The Collections API is a set of classes and interfaces
that support operations on collections of objects

2. What is the List interface? - The List interface provides support for ordered collections
of objects.
3. What is the Vector class? - The Vector class provides the capability to implement a
growable array of objects

4. What is an Iterator interface? - The Iterator interface is used to step through the
elements of a Collection

5. Which java.util classes and interfaces support event handling? - The EventObject
class and the EventListener interface support event processing

6. What is the GregorianCalendar class? - The GregorianCalendar provides support for


traditional Western calendars

7. What is the Locale class? - The Locale class is used to tailor program output to the
conventions of a particular geographic, political, or cultural region

8. What is the SimpleTimeZone class? - The SimpleTimeZone class provides support for
a Gregorian calendar

9. What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary class
and is used associate keys with values

10. What is the highest-level event class of the event-delegation model? - The
java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy

11. What is the Collection interface? - The Collection interface provides support for the
implementation of a mathematical bag - an unordered collection of objects that may
contain duplicates

12. What is the Set interface? - The Set interface provides methods for accessing the
elements of a finite mathematical set. Sets do not allow duplicate elements

13. What is the purpose of the enableEvents() method? - The enableEvents() method is
used to enable an event for a particular object. Normally, an event is enabled when a
listener is added to an object for a particular event. The enableEvents() method is used
by objects that handle events by overriding their event-dispatch methods.

14. What is the ResourceBundle class? - The ResourceBundle class is used to store
locale-specific resources that can be loaded by a program to tailor the program’s
appearance to the particular locale in which it is being run.
15. What is the difference between yielding and sleeping? - When a task invokes its
yield() method, it returns to the ready state. When a task invokes its sleep() method, it
returns to the waiting state.

16. When a thread blocks on I/O, what state does it enter? - A thread enters the waiting
state when it blocks on I/O.

17. When a thread is created and started, what is its initial state? - A thread is in the
ready state after it has been created and started.

18. What invokes a thread’s run() method? - After a thread is started, via its start() method
or that of the Thread class, the JVM invokes the thread’s run() method when the thread is
initially executed.

19. What method is invoked to cause an object to begin executing as a separate


thread? - The start() method of the Thread class is invoked to cause an object to begin
executing as a separate thread.

20. What is the purpose of the wait(), notify(), and notifyAll() methods? - The
wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to
wait for a shared resource. When a thread executes an object’s wait() method, it enters
the waiting state. It only enters the ready state after another thread invokes the object’s
notify() or notifyAll() methods.

21. What are the high-level thread states? - The high-level thread states are ready,
running, waiting, and dead

22. What happens when a thread cannot acquire a lock on an object? - If a thread
attempts to execute a synchronized method or synchronized statement and is unable to
acquire an object’s lock, it enters the waiting state until the lock becomes available.

23. How does multithreading take place on a computer with a single CPU? - The
operating system’s task scheduler allocates execution time to multiple tasks. By quickly
switching between executing tasks, it creates the impression that tasks execute
sequentially.

24. What happens when you invoke a thread’s interrupt method while it is sleeping or
waiting? - When a task’s interrupt() method is executed, the task enters the ready state.
The next time the task enters the running state, an InterruptedException is thrown.

25. What state is a thread in when it is executing? - An executing thread is in the running
state

26. What are three ways in which a thread can enter the waiting state? - A thread can
enter the waiting state by invoking its sleep() method, by blocking on I/O, by
unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait()
method. It can also enter the waiting state by invoking its (deprecated) suspend()
method.

27. What method must be implemented by all threads? - All tasks must implement the
run() method, whether they are a subclass of Thread or implement the Runnable
interface.

28. What are the two basic ways in which classes that can be run as threads may be
defined? - A thread class may be declared as a subclass of Thread, or it may implement
the Runnable interface.

29. How can you store international / Unicode characters into a cookie? - One way is,
before storing the cookie URLEncode it. URLEnocder.encoder(str); And use
URLDecoder.decode(str) when you get the stored cookie.

JDBC and JSP interview questions

1. What is the query used to display all tables names in SQL Server (Query analyzer)?

select * from information_schema.tables

2. How many types of JDBC Drivers are present and what are they?- There are 4 types
of JDBC Drivers
o JDBC-ODBC Bridge Driver
o Native API Partly Java Driver
o Network protocol Driver
o JDBC Net pure Java Driver

3. Can we implement an interface in a JSP?- No


4. What is the difference between ServletContext and PageContext?- ServletContext:
Gives the information about the container. PageContext: Gives the information about the
Request
5. What is the difference in using request.getRequestDispatcher() and
context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order to
create it we need to give the relative path of the resource,
context.getRequestDispatcher(path): In order to create it we need to give the absolute
path of the resource.
6. How to pass information from JSP to included JSP?- Using <%jsp:param> tag.
7. What is the difference between directive include and jsp include?- <%@ include>:
Used to include static resources during translation time. JSP include: Used to include
dynamic content or static content during runtime.
8. What is the difference between RequestDispatcher and sendRedirect?-
RequestDispatcher: server-side redirect with request and response objects. sendRedirect
: Client-side redirect with new request and response objects.
9. How does JSP handle runtime exceptions?- Using errorPage attribute of page
directive and also we need to specify isErrorPage=true if the current page is intended to
URL redirecting of a JSP.
10. How do you delete a Cookie within a JSP?

Cookie mycook = new Cookie(\"name\",\"value\");


response.addCookie(mycook);
Cookie killmycook = new Cookie(\"mycook\",\"value\");
killmycook.setMaxAge(0);
killmycook.setPath(\"/\");
killmycook.addCookie(killmycook);

11. How do I mix JSP and SSI #include?- If you’re just including raw HTML, use the
#include directive as usual inside your .jsp file.

<!--#include file="data.inc"-->

But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the
included file. If your data.inc file contains jsp code you will have to use

<%@ vinclude="data.inc" %>

The <!–#include file="data.inc"–> is used for including non-JSP files.

12. I made my class Cloneable but I still get Can’t access protected method clone.
Why?- Some of the Java books imply that all you have to do in order to have your class
support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent
at some point, but that’s not the way it works currently. As it stands, you have to
implement your own public clone() method, even if it doesn’t do anything special and just
calls super.clone().
13. Why is XML such an important development?- It removes two constraints which were
holding back Web developments: dependence on a single, inflexible document type
(HTML) which was being much abused for tasks it was never designed for; the
complexity of full SGML, whose syntax allows many powerful but hard-to-program
options. XML allows the flexible development of user-defined document types. It provides
a robust, non-proprietary, persistent, and verifiable file format for the storage and
transmission of text and data both on and off the Web; and it removes the more complex
options of SGML, making it easier to program for.
14. What is the fastest type of JDBC driver?- JDBC driver performance will depend on a
number of issues:
o the quality of the driver code,
o the size of the driver code,
o the database server and its load,
o network topology,
o the number of times your request is translated to a different API.

In general, all things being equal, you can assume that the more your request and
response change hands, the slower it will be. This means that Type 1 and Type 3 drivers
will be slower than Type 2 drivers (the database calls are make at least three translations
versus two), and Type 4 drivers are the fastest (only one translation).

15. How do I find whether a parameter exists in the request object?

boolean hasFoo = !(request.getParameter(\"foo\") == null


|| request.getParameter(\"foo\").equals(\"\"));

or

boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)

16. How can I send user authentication information while makingURLConnection?-


You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate
headers to HTTP authorization.

Java Interview Questions

1.Are the imports checked for validity at compile time? e.g. will the code containing an
import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above
line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

2.Does importing a package imports the subpackages as well? e.g. Does importing
com.MyTest.* also import com.MyTest.UnitTests.*?

No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes
in the package MyTest only. It will not import any class in any of it's subpackage.

3.What is the difference between declaring a variable and defining a variable?

In declaration we just mention the type of the variable and it's name. We do not initialize it. But
defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are
both definitions.

4.What is the default value of an object reference declared as an instance variable?

null unless we define it explicitly.

5.Can a top level class be private or protected?

No. A top level class can not be private or protected. It can have either "public" or no modifier. If it
does not have a modifier it is supposed to have a default access.If a top level class is declared as
private the compiler will complain that the "modifier private is not allowed here". This means that
a top level class can not be private. Same is the case with protected.

6.What type of parameter passing does Java support?

In Java the arguments are always passed by value .

7.Primitive data types are passed by reference or pass by value?

Primitive data types are passed by value.

8.Objects are passed by value or by reference?


Java only supports pass by value. With objects, the object reference itself is passed by value and
so both the original reference and parameter copy both refer to the same object .

9.What is serialization?

Serialization is a mechanism by which you can save the state of an object by converting it to a
byte stream.

10.How do I serialize an object to a file?

The class whose instances are to be serialized should implement an interface Serializable. Then
you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This
will save the object to a file.

11.Which methods of Serializable interface should I implement?

The serializable interface is an empty interface, it does not contain any methods. So we do not
implement any methods.

12.How can I customize the seralization process? i.e. how can one have a control over the
serialization process?

Yes it is possible to have control over serialization process. The class should implement
Externalizable interface. This interface contains two methods namely readExternal and
writeExternal. You should implement these methods and write the logic for customizing the
serialization process.

13.What is the common usage of serialization?

Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the
state of an object is to be saved, objects need to be serilazed.

14.What is Externalizable interface?

Externalizable is an interface which contains two methods readExternal and writeExternal. These
methods give you a control over the serialization mechanism. Thus if your class implements this
interface, you can customize the serialization process by implementing these methods.

15.What happens to the object references included in the object?


The serialization mechanism generates an object graph for serialization. Thus it determines
whether the included object references are serializable or not. This is a recursive process. Thus
when an object is serialized, all the included objects are also serialized alongwith the original
obect.

16.What one should take care of while serializing the object?

One should make sure that all the included objects are also serializable. If any of the objects is
not serializable then it throws a NotSerializableException.

17.What happens to the static fields of a class during serialization? Are these fields
serialized as a part of each serialized object?

Yes the static fields do get serialized. If the static field is an object then it must have implemented
Serializable interface. The static fields are serialized as a part of every object. But the
commonness of the static fields across all the instances is maintained even after serialization.

Java Packages & Constructors

1. How to start to define my own packages? Any suggestions?

A: Suggestions:

• Don't put your own stuff under jdk. Create a directory such as c:/myworkarea or c:/liuxia

• Create a stem directory, such as com/myco or org/myorg under your c:/myworkarea

• No Java files should be put in your stem directory, only packages


• All your code will start with a package statement, and put them under the corresponding
directories. Examples: package com.myco.somepkg;
package com.myco.somepkg.somesubpkg;

That will be a good start.

2.If I define a class in com.myco package as com/myco/MyClass.java,


How do I compile and run it?

In your c:/myworkarea directory:

javac com/myco/MyClass.java
java com.myco.MyClass

However, this is just to get you started. The better practice is using ant. Start to learn Ant now

3. How to create my own package, how to call my class in another package?

A: Here is a runnable example with detailed explanation for you to play and practice.

Package Usage

4. What are the rules and convention about package name? Why I got an error when I used
WEB-INF as my package name?

A:package name in Java is an identifier, therefore it has to qualify as an identifier first. Read JLS

for rules of Java identifiers JLS 3.8 Identifiers To my limited knowledge of computer
programming languages, I do not know any programming language which allows dash '-' as part
of an identifier. Not in any of the followings: Pascal, c, c++, Fortran, c#, Ada, VB, Lisp, Java, ML,
perl, ... It might be allowed in COBOL, but I'm not sure, since COBOL is a very loose language. I
do not know COBOL. Any COBOL expert here? Help, please! The first problem for WEB-INF as a
package name is dash '-', of course. The second problem is WEB-INF in tomcat or Java web
component develop environment has special meaning, you cannot use it for anything else.In all of
above, we are not talking about convention, but the rules. Read Java coding convention here:

Code Conventions for the JavaTM Programming Language What are the differences?
If you violate the convention only, your code should still compilable/runnable/workable, but not
very good. Another thing you need to remember is that conventions are very subjective. A good
convention in IBM shop might be considered bad in Microsoft or EDS.

Java Constructors

5. How to use super and this Java keywords?

A:

super();
this();

With or without parameters, only one of these is allowed as the first line in your constructor,
nowhere else! However,

super.method1();
this.field4;

do not have the above restrictions in your code.

6. How does the Java default constructor be provided? Is it the same as C++?

A: If a class defined by the code does not have any constructor, compiler will automatically
provide one no-parameter-constructor (default-constructor) for the class in the byte code. The
access modifier (public/private/etc.) of the default constructor is the same as the class itself.
Attention to former C++ programmers: It is very important to previous C++ programmers to
know the differences between C++ and Java. C++ compiler will provide a no-parameter-
constructor (defult-constructor) as long as you did not define one. Java only provide a no-
parameter-constructor when your class does not have any construcor.Can you let me see it?
Oh, yes, in where your class file is, type

javap -private YourClassName

Your C++ programmer will be real happy to see the output very similar to a YourClassName.h Of
course, j2sdk/bin or jre/bin directory must on your path.

7. Why does my following code not compilable?

class Base{
public int i = 0;
public Base(String text){
i = 1;
}
}
public class Sub extends Base{
public Sub(String text){
i = 2;
}
public static void main(String args[]){
Sub sub = new Sub("Hello");
System.out.println(sub.i);
}
}
// Compile error:
// Sub.java:8: cannot resolve symbol
// symbol : constructor Base ()

A:

Because you did not explicitly call super(String) in Sub contructor, a default super() is added.
However, the super class of Sub does not have a Base() constructor. ERROR! How to solve the
problem? Two choices:

1. Explicitly call super(String) in Sub constructor


2. Add a no-param-constructor for Base()

See the following detailed commented code, uncomment either one will work

class Base{
public int i = 0;
/* ----------------- choice #2
public Base() {
// do whatever
}
*/
public Base(String text){
i = 1;
}
}
public class Sub extends Base{
public Sub(String text){

// super(text); //-- choice #1

// problems here!!!
// since if you don't, then a default
// super(); //is generated by compiler

i = 2;
}
public static void main(String args[]){
Sub sub = new Sub("Hello");
System.out.println(sub.i);
}
}
8. Can I specify void as the return type of constructor? It compiles.

A: No, you cannot!

However, why it compiles? Yes, it you code it tricky enough, it will compile without any error
message!Surprised? Proved? Ha, ha, Roseanne is wrong?! Wait a minute, hmmm... it is not a
constructor any more! It is just a method happen to have the same name as the class name Try
the following code! Please! It will be a very very interesting experience and lots of fun too!

public class A {

// this is a constructor of class A


public A(int i) {
System.out.println("We are in contructor: A(int i)");
System.out.println("The i value is " + i);
}

// this is a method A
void A() {
System.out.println("We are in method: void A()");
}

public static void main(String[] args) {

// They are fine here!


A a1 = new A(3);
a1.A();

// Compile time error


// cannot resolve symbol constructor A()
// A a2 = new A();
}
}

// output
// We are in contructor: A(int i)
// The i value is 3
// We are in method: void A()
Serialization

1.What class can be serialized? What cannot?

A: Almost all JDK classes are serializable except

• Classes with only static and/or transient fields. For example, Math, Arrays, etc.
• Classes representing specifics of a virtual machine. For example, Thread, Process,
Runtime, almost all classes in the java.io and many classes in java.net packages are not
serializable

I/O Streams, Reader/Writer

2. Creating a File object does not mean creation of any file or directory, and then when
does the creation of physical file take place?

A: The answer is it depends...

The physical file might be created 10 years ago by one of your long gone colleagues , or will be
created on the next step of running when your program tries to write something onto the not-yet-
exist file by using FileOutputStream or FileWriter.

You can also call createNewFile() of the java.io.File object to create a new, empty file named by
its abstract pathname if and only if a file with this name does not yet exist.

The file might never be created since the program does not have write permission (of
java.io.FilePermission) in that specified directory.

The file might never be created simply because the program never try to do anything on it,
absentminded programmer, of course.

The java.io.File object might just represent a directory, which might not be a file at all.

Read The Java Tutorial It is free. Read javadoc, and compare the exception thrown by File and
FileWriter constructors will help as well.

3. Is it possible to change directory by using File object?


A: No, You cannot change the directory by using a file object.

Instances of the File class are immutable; that is, once created, the abstract pathname
represented by a File object will never change.

However, you can use one File object to find the directory you want, and then create another File
object for the directory you want to go to.

4. How to create a new directory by using File object?

A: Using class File method mkdir() or mkdirs(). See code here:

// MakeDir.java
import java.io.*;

public class MakeDir {


public static void main(String args[]){
// make sure sub-directory "mmm" does not exist
File dir=new File("mmm");
System.out.println(dir.mkdir());// true

// make sure at least two of "hhh\\lll\\nnn" does not exist


File multidir=new File("hhh\\lll\\nnn");
System.out.println(multidir.mkdir()); // false
System.out.println(multidir.mkdirs()); // true

// make sure at least two of "..\\ccc\\ddd\\eee" does not exist


File updir=new File("..\\ccc\\ddd\\eee");
System.out.println(updir.mkdir()); // false
System.out.println(updir.mkdirs()); // true

// If you run the code second time,


// the result will be different. Why?
}
}
5. What are the differences between FileInputStream/FileOutputStream and
RandomAccessFile? Do you have a good example on it?

A: Remember never mixing RandomAccessFile with Streams!!! RandomAccessFile class is more


or less a legacy from c language, the Stream concepts/C++ were not invented then.

This example deals with File, FileInputStream, DataOutputStream, RandomAccessFile. Play with
it; try to understand every bit of the output. IOTest.java

6. What are the difference between File.getAbsolutePath() and File.getCanonicalPath()?


Can they return different result?

A: Find your answer by reading this:

http://java.sun.com/j2se/1.3/docs/api/java/io/File.html

Yes, they can return different results! See the following example. Pay attention to the comments.

import java.io.*;

public class T
{
static void testPath(){
File f1 = new File("/home/jc/../rz/rz.zip"); // file does not exist
File f2 = new File("T.class"); // file in rz dir under /home/rzhang

// no try/catch block needed


// return "/home/jc/../rz/rz.zip" always
System.out.println("Absolute path for f1: " + f1.getAbsolutePath());
// return "/home/rzhang/rz/T.class"
System.out.println("Absolute path for f2: " + f2.getAbsolutePath());

try {
// not compilable if neither try/catch block nor throws present
// return "/home/rz/rz.zip"
System.out.println("Canonical path for f1: " + f1.getCanonicalPath());

// return "/home/rzhang/rz/T.class"
System.out.println("Canonical path for f2: " + f2.getCanonicalPath());
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}

public static void main(String[] args){


T.testPath();
}
}

7. Which one of the following will create an InputStreamReader correctly?

1. new InputStreamReader(new FileInputStream("data"));


2. new InputStreamReader(new FileReader("data"));
3. new InputStreamReader(new BufferedReader("data"));
4. new InputStreamReader("data");
5. new InputStreamReader(System.in);

A:

The leagal constructors for InputStreamReader are


InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String enc)

1. If you compile this line without a try/catch block, you will get a compile error: Exception
java.io.FileNotFoundException must be caught, or it must be declared in the throws
clause of this method.

How to do it correctly?
2. try {
3. new InputStreamReader(new FileInputStream("data"));
4. }
5. catch (java.io.FileNotFoundException fnfe) {
6. }
Answer: If they let you choose one, choose e. If they let you choose two, choose a and e.

7. Error #1: FileReader is not an InputStream.


Error #2: The same problems as a), Exception java.io.FileNotFoundException must be
caught

8. Error #1: BufferedReader is not an InputStream. Error #2: There is no contructor of


BufferedReader to take string as argument.

9. String "data" is not an InputStream.


10. Correct, since System.in is an InputStream.

8. Why only read() methods in ByteArrayInputStream does not throw IOException?

A: You are right, read() methods of all other InputStreams throw IOException except
ByteArrayInputStream.

This is because the entire byte array is in memory; there is no circumstance in which an
IOException is possible.

However, close() and reset() methods of ByteArrayInputStream still can throw IOException.

9. How does InputStream.read() method work? Can you give me some sample code?

A:Here is the sample code; the explanation is in the comments. Make sure you compile it, run it,
and try to understand it.

// TestRead.java
import java.io.*;
public class TestRead {
public static void main(String argv[]) {
try {
byte[] bary = new byte[]{-1, 0, 12, 23, 56, 98, 23, 127, -128};
ByteArrayInputStream bais = new ByteArrayInputStream(bary);
System.out.print("{ ");
while (test(bais)){
System.out.print(", ");
}
System.out.println(" }");
// output: { 255, 0, 12, 23, 56, 98, 23, 127, 128, -1 }
// Notice 2 negative byte value becomes positive
// -1 is added to the end to signal EOF.
}
catch (IOException e) {
System.out.println(e);
}
}
public static boolean test(InputStream is) throws IOException {
// Read one byte at a time and
// put it at the lower order byte of an int
// That is why the int value will be always positive
// unless EOF, which will be -1
int value = is.read();
System.out.print(value);

// return true as long as value is not -1


return value == (value & 0xff);
}
}

10. How to read data from socket? What is the correct selection for the question?

A socket object (s) has been created and connected to a standard Internet service
on a remote network server.
Which of the following gives suitable means for reading ASCII data,
one line at a time from the socket?
A. s.getInputStream();
B. new DataInputStream(s.getInputStream());
C. new ByteArrayInputStream(s.getInputStream());
D. new BufferedReader(new InputStreamReader(s.getInputStream()));
E. new BufferedReader(new InputStreamReader(s.getInputStream()),"8859-1");

A:

A. InputStream does not readLine()


B. DataInputStream.reaLine() deprecated
C. ByteArrayInputStream does not readLine()
D. the only correct answer.
E. encoding put in the wrong place. The correct way is
new BufferedReader(new InputStreamReader(s.getInputStream(), "8859-1"));

See sample from the Sun: Reading from and Writing to a Socket

11.How to use ObjectOutputStream/ObjectInputStream?

A:

A sample code here, which writes to ObjectOutputStream, and reads it back from
ObjectInputStream. The program not only deals with instance object, but also Class object. In
addition, it uses reflection to analyze how it works.

Find it at TestSerialization.java Pretty heavy i/o, serialization, reflection, transient/static stuff, if it


is too over your head, skip it.

12. How to compare two (binary/not) files to see if they are identical?

A:

1) Open 2 streams
2) Compare their length first, if not the same, done
3) If the same lengths, then compare byte to byte, until you find anything not the same, or end-of-
file
4) You get your answer

13. When I use the following code to write to a file, why the file has no data in it?

// WriteFile.java
import java.io.*;
public class WriteFile {
public static void main(String[]args)throws Exception {
FileOutputStream fos = new FileOutputStream("out.txt");
PrintWriter pw = new PrintWriter(fos);
pw.print(true);
pw.println("short content file");
}
}
A:

When you open out.txt, it is an empty file, correct. Try to write a lot of text on to the file, and then
you get something back, but not all of them.

Why? The reason is for efficiency, the JVM or OS tries to buffer the data to reduce the hit of hard
disk or other media. If you do not flush and close, the data might be lost.

I remember when I was coding in Pascal (C?), I had exact the same problem. I learned a lesson
that always closing you file or stream after finishing read/write to it.

If you change you code to the forlowing, everything will be ok!

// WriteFile.java
import java.io.*;
public class WriteFile {
public static void main(String[]args)throws Exception {
FileOutputStream fos = new FileOutputStream("out.txt");
PrintWriter pw = new PrintWriter(fos);
pw.print(true);
pw.println("short content file");
pw.close();
fos.close();
}
}

Garbage Collection

14. Will finalize method of all objects eventually be called?

A: The answer is yes, with an exception of JVM being killed abruptly for internal or external
reasons.

If the your application is terminated normally, the finalize method of all objects eventually will be
called. The simlest way to prove it would be writing a very small application with a few objects
instantialized. All objects in your application have a finalize method with a println("XXX object
finalize method is called now."); in it. Run it and see the result. This is because JVM will take care
of it before normal exit. All objects are eligible for GC and will be GCed before JVM terminates. Of
course, we are not considering the special case that JVM might have a bug. :)
However, what is the exception?

• JVM is killed internally, by


1. System.exit(1);
2. Uncaught Exception being thrown at the top level.
3. You may add more...
• JVM is killed externally, by
1. User use ctrl C or other system commands to kill it on windows, unix, or ...
2. System power off.
3. You may add more...

15. Any class that includes a finalize method should invoke its superclass' finalize method,
why?

A:

The point is that finalize methods are not automatically "chained" - if you subclass a class that
has an important finalize, your finalize method should call it. Obviously if you don't know what the
superclass finalize method does, you should call it anyway, just to be safe.

By contrast, When you create an object with the new keyword, the superclass constructor(s) are
called first. This is automatically "chained".

16. When an object becomes eligible for garbage collection?

A:

The object is no longer referenced or referenced only by objects, which are eligible for
GC.An object becomes eligible for garbage collection when there is no way for any active thread
to reach that object through a reference or chain of references. (An equivalent answer by Jim
Yingst)Set all references to an object to null is sufficient for an object eligible to GC, but not
necessary.

Here are two simple examples with proper comments:

public class Test1{


public static void main(String[] args) {
Object a = new Object();
Object b = a;
a = null;
// the Object is still referred by b.
// which is not eligible for garbage collection.

// an infinite loop here


int i = 0;
while (true){
i = i++;
}
//Using ctrl C to kill it, sorry!
}
}

public class Test2{


public static void main(String[] args) {
Object[] ary = new Object[5];
for (int i=0; i<5; i++) {
ary[i] = new Object();
}

// do something here

ary = null;
//Now all objects in the array are eligible for GC
// even none of their references are null.
}
}

17. Can circular reference prevent objects from be garbage collected?

A: No! Prove by counter example:

class Test1 {
public static void main(String arg[]) throws Exception{

MyObj a = new MyObj("a");


MyObj b = new MyObj("b");
//circular reference here
a.o = b;
b.o = a;

a = null;
b = null;
// a and b are both eligible for GC now

MyObj c = new MyObj("c");


c.o = new MyObj("d"); //when c dies, d dies too.
c = null;

// an infinite loop here


// use ^c to kill it

MyObj[] objAry = new MyObj[1024];


int i = 0;
while (true){
// suggest JVM to GC
System.gc();

// use more memory here


i %= 1024;
objAry[i] = new MyObj("X" + i);

i++;
Thread.sleep(5); // Give CPU some breath time
}
}
}

class MyObj {
MyObj o;
String s;
long[] ary = new long[4096]; // make MyObj big
MyObj(String s) {
this.s = s;
}

protected void finalize() throws Throwable {


// Make GC visible
System.out.println(s + ": I am dying");
super.finalize();
}
}

18. How many objects are eligible for GC in the following code after d = null?

public class Test{


public static void main(String[] args) {
Object a = new Object(); // the object original referenced by object reference a
Object b = new Object();
Object c = new Object();
Object d = new Object();

d=c=b=a;
d=null;
}
}

A:

Just remember that operator = is right associate, and then you should be able to figure out the
answer by yourself. The equivalent statement is d=(c=(b=a)); The example in here following can
be used to get the answer you need too, minor change required.

Answer: Three.
1) After b=a, the object original referenced by b is eligible for GC.
2) After c=(b=a), the object original referenced by c is eligible for GC.
3) After d=(c=(b=a)), the object original referenced by d is eligible for GC.
4) After d=null, nothing new is eligible for GC.
5) The object original referenced by a is not eligible for GC, since it is still referred by references
a, b, c. 6) Make sure you understand the differences between physical object and object
reference (pointer to object).

19. In garbage collection mechanism, what is vendor/platform dependent? What is not?

A:

How GC implemented is vender and platform dependent. Which means:

It is vender and platform dependent that when and in what order the eligible for GC objects
will be GCed.

However, which objects are eligible for GC is independent of implementations. Different vendor
may use different algorithms. What algorithm used to find the objects, which are eligible for GC
does not matter. What really matters is that they use the same principle.

The object is no longer referenced or referenced only by objects, which are eligible for GC.

Unless they have a bug...

20.Can an object be garbage collected, but a field of it is still alive?

A: Sure, as long as it is still referred by something.

Actually, this is used by many design patterns, e.g. Factory Method pattern. See the following
example, read the comments carefully!

// UseSimple.java
class Simple {
void writeSomething(String msg) {
System.out.println("Simple.writeSomething: " + msg);
}

protected void finalize()throws Throwable{


System.out.println("Finalize:Simple");
super.finalize();
}
}
class CombineSimple{
private Simple simFld;

Simple getSimpleField() {
if( simFld == null ) {
simFld = new Simple();
}
return simFld;
}
protected void finalize()throws Throwable{
System.out.println("Finalize:CombineSimple");
super.finalize();
}
}

public class UseSimple {


public static void main(String[] args) {
CombineSimple csObj = new CombineSimple();
Simple simObj = csObj.getSimpleField();

csObj = null;

// Since GC cannot be forced


// we make sure csObj is GCed.
System.gc();
for (int i=0; i<3; i++){
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
System.gc();
}

// The simFld field of csObj will be still alive


// since it is still referred by simObj
simObj.writeSomething("I am still alive!");
}
}

21. What is mark and sweep garbage collection algorithm, is there other algorithms?

A:

The question is out of the scope of SCJP, however, it will help you in job-hunting process. Here is
a beautiful applet, which will give you the basics, and have fun: Heap of Fish, A Simulation of a
Garbage-Collected Heap

You might also like