Basic Java Interview Questions
Basic Java Interview Questions
Basic Java Interview Questions
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:
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).
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.
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;
}
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.
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.
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.
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.
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.
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
Class inheritance lets you define the implementation of one class in terms of another’s. Reuse 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.
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
void changeValue(int& a)
{
a++;
}
void main()
{
int b=2;
changeValue(b);
}
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″>
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.
28. What tags are mandatory when creating HTML to display an applet?
2. code, name
Correct answer is d.
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.
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
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.
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.
1. What is the query used to display all tables names in SQL Server (Query analyzer)?
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
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
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).
or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
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.
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.
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.
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.
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.
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.
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.
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.
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.
A: Suggestions:
• Don't put your own stuff under jdk. Create a directory such as c:/myworkarea or c:/liuxia
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
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
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;
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
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.
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:
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){
// 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.
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 method A
void A() {
System.out.println("We are in method: void A()");
}
// output
// We are in contructor: A(int i)
// The i value is 3
// We are in method: void A()
Serialization
• 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
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?
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.
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.
// MakeDir.java
import java.io.*;
This example deals with File, FileInputStream, DataOutputStream, RandomAccessFile. Play with
it; try to understand every bit of the output. IOTest.java
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
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();
}
}
A:
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.
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);
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:
See sample from the Sun: Reading from and Writing to a Socket
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.
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.
// 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
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?
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".
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.
// do something here
ary = null;
//Now all objects in the array are eligible for GC
// even none of their references are null.
}
}
class Test1 {
public static void main(String arg[]) throws Exception{
a = null;
b = null;
// a and b are both eligible for GC now
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;
}
18. How many objects are eligible for GC in the following code after d = null?
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).
A:
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.
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);
}
Simple getSimpleField() {
if( simFld == null ) {
simFld = new Simple();
}
return simFld;
}
protected void finalize()throws Throwable{
System.out.println("Finalize:CombineSimple");
super.finalize();
}
}
csObj = null;
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