Sunday, June 8, 2008

projects for college

hai guys this is shyam,


welcome friends if u wanna have college projects dont go for different instiutions and ay the amount and submit dummy projects , if u guys wanna live project..



contact me at 9949300039 shyam.shyre@gmail.com

Monday, August 27, 2007

Free Projects for Companies and Colleges

Design all your various organisation projects and college Library Projects for Absolutely free using the high end java programming ....



For more Details Regarding the Projects and Various Aspects..



Mail me to shyam.shyre@gmail.com

We are here to help you..............

Complete CoreJava and J2ee Faqs and ScJp links

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).
.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.
) 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.
1. What is a JavaBean? (asked by Lifescan inc)
ANSWER: JavaBeans are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java. They are similar to Microsoft’s ActiveX components, but designed to be platform-neutral, running anywhere there is a Java Virtual Machine (JVM).
2. What are the seven layers(OSI model) of networking? (asked by Caspio.com)
ANSWER: 1.Physical, 2.Data Link, 3.Network, 4.Transport, 5.Session, 6.Presentation and 7.Application Layers.
3. What are some advantages and disadvantages of Java Sockets? (asked by Arashsoft.com)
ANSWER:
Advantages of Java Sockets:
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.
Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.
Disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network
Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.
4. What is the difference between a NULL pointer and a void pointer? (asked by Lifescan inc)
ANSWER: A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does).
5. What is encapsulation technique? (asked by Microsoft)
ANSWER: Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state.
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
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.
Can there be an abstract class with no abstract methods in it? - Yes
Can an Interface be final? - No
Can an Interface have an inner class? - Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println(\"inside\");
};
public static void main(String a1[])
{
System.out.println(\"in interfia\");
}
}
}
Can we define private and protected modifiers for variables in interfaces? - No
What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces.
What is a local, member and a class variable? - Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables
What are the different identifier states of a Thread? - The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
What are some alternatives to inheritance? - Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
Why isn’t there operator overloading? - Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
What does it mean that a method or field is “static”? - Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
String hostname =
InetAddress.getByName(\"192.18.97.39\").getHostName();
Difference between JRE/JVM/JDK?
Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.
What is synchronization and why is it important? - With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
Is null a keyword? - The null value is not a keyword.
Which characters may be used as the second character of an identifier,but not as the first character of an identifier? - The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
What modifiers may be used with an inner class that is a member of an outer class? - A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? - Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects.
What restrictions are placed on the location of a package statement within a source code file? - A package statement must appear as the first line in a source code file (excluding blank lines and comments).
What is the difference between preemptive scheduling and time slicing? - Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
What is a native method? - A native method is a method that is implemented in a language other than Java.
What are order of precedence and associativity, and how are they used? - Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
What is the catch or declare rule for method declarations? - If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
Can an anonymous class be declared as implementing an interface and extending a class? - An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.
What gives Java its “write once and run anywhere” nature? - Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.
What are the four corner stones of OOP? - Abstraction, Encapsulation, Polymorphism and Inheritance.
Difference between a Class and an Object? - A class is a definition or prototype whereas an object is an instance or living representation of the prototype.
What is the difference between method overriding and overloading? - Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.
What is a “stateless” protocol? - Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination.
What is constructor chaining and how is it achieved in Java? - A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.
What is passed by ref and what by value? - All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references
Can RMI and Corba based applications interact? - Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.
You can create a String object as String str = “abc”; Why cant a button object be created as Button bt = “abc”;? Explain - The main reason you cannot create a button by Button bt1= “abc”; is because “abc” is a literal string (something slightly different than a String object, by the way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = “abc”;
What does the “abstract” keyword mean in front of a method? A class? - Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract.
How many methods do u implement if implement the Serializable Interface? - The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are
java.rmi.Remote
java.util.EventListener
What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)? - It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use “Timer”, I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in.
What is the difference between logical data independence and physical data independence? - Logical Data Independence - meaning immunity of external schemas to changeds in conceptual schema. Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema.
What is a user-defined exception? - Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.
Describe the visitor design pattern? - Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy.
16.What are the advantages of OOPL?
Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.
17. What do mean by polymorphisum, inheritance, encapsulation?
Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.
18. What do you mean by static methods?
Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.
19. What do you mean by virtual methods?
Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.
20. Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level.
Ans: SELECT Student.name, Student.SID
FROM Student, Level
WHERE Student.SID = Level.SID
AND Level.Level = "freshman"
AND Student.Course = 3;
21. What are the disadvantages of using threads?
Ans: DeadLock.
22. Write the Java code to declare any constant (say gravitational constant) and to get its value
Ans: Class ABC
{
static final float GRAVITATIONAL_CONSTANT = 9.8;
public void getConstant()
{
system.out.println("Gravitational_Constant: " + GRAVITATIONAL_CONSTANT);
}
}
23. What do you mean by multiple inheritance in C++ ?
Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.
24. Can you write Java code for declaration of multiple inheritance in Java ?
Ans: Class C extends A implements B
{
}
What is the difference between an Abstract class and Interface ?
What is user defined exception ?
What do you know about the garbage collector ?
What is the difference between C++ & Java ?
Explain RMI Architecture?
How do you communicate in between Applets & Servlets ?
What is the use of Servlets ?
What is JDBC? How do you connect to the Database ?
In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
What is the difference between Process and Threads ?
What is the difference between RMI & Corba ?
What are the services in RMI ?
How will you initialize an Applet ?
What is the order of method invocation in an Applet ?
When is update method called ?
How will you pass values from HTML page to the Servlet ?
Have you ever used HashTable and Dictionary ?
How will you communicate between two Applets ?
What are statements in JAVA ?
What is JAR file ?
What is JNI ?
What is the base class for all swing components ?
What is JFC ?
What is Difference between AWT and Swing ?
Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ?
How does thread synchronization occurs inside a monitor ?
How will you call an Applet using a Java Script function ?
Is there any tag in HTML to upload and download files ?
Why do you Canvas ?
How can you push data from an Applet to Servlet ?
What are 4 drivers available in JDBC ?
How you can know about drivers and database information ?
If you are truncated using JDBC, How can you know ..that how much data is truncated ?
And What situation , each of the 4 drivers used ?
How will you perform transaction using JDBC ?
In RMI, server object first loaded into the memory and then the stub reference is sent to the client ? or whether a stub reference is directly sent to the client ?
Suppose server object is not loaded into the memory, and the client request for it , what will happen?
What is serialization ?
Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?
What is difference RMI registry and OSAgent ?
To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message should be sent to the client ? What will you do for achieving for this ?
What are the benefits of Swing over AWT ?
Where the CardLayout is used ?
What is the Layout for ToolBar ?
What is the difference between Grid and GridbagLayout ?
How will you add panel to a Frame ?
What is the corresponding Layout for Card in Swing ?
What is light weight component ?
Can you run the product development on all operating systems ?
What is the webserver used for running the Servlets ?
What is Servlet API used for connecting database ?
What is bean ? Where it can be used ?
What is difference in between Java Class and Bean ?
Can we send object using Sockets ?
What is the RMI and Socket ?
How to communicate 2 threads each other ?
What are the files generated after using IDL to Java Compilet ?
What is the difference between an Abstract class and Interface ?
What is user defined exception ?
What do you know about the garbage collector ?
What is the difference between C++ & Java ?
Explain RMI Architecture?
How do you communicate in between Applets & Servlets ?
What is the use of Servlets ?
What is JDBC? How do you connect to the Database ?
In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
What is the difference between Process and Threads ?
What is the difference between RMI & Corba ?
What are the services in RMI ?
How will you initialize an Applet ?
What is the order of method invocation in an Applet ?
When is update method called ?
How will you pass values from HTML page to the Servlet ?
Have you ever used HashTable and Dictionary ?
How will you communicate between two Applets ?
What are statements in JAVA ?
What is JAR file ?
What is JNI ?
What is the base class for all swing components ?
What is JFC ?
What is Difference between AWT and Swing ?
Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ?
How does thread synchronization occurs inside a monitor ?
How will you call an Applet using a Java Script function ?
Is there any tag in HTML to upload and download files ?
Why do you Canvas ?
How can you push data from an Applet to Servlet ?
What are 4 drivers available in JDBC ?
How you can know about drivers and database information ?
If you are truncated using JDBC, How can you know ..that how much data is truncated ?
And What situation , each of the 4 drivers used ?
How will you perform transaction using JDBC ?
In RMI, server object first loaded into the memory and then the stub reference is sent to the client ? or whether a stub reference is directly sent to the client ?
Suppose server object is not loaded into the memory, and the client request for it , what will happen?
What is serialization ?
Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?
What is difference RMI registry and OSAgent ?
To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message should be sent to the client ? What will you do for achieving for this ?
What are the benefits of Swing over AWT ?
Where the CardLayout is used ?
What is the Layout for ToolBar ?
What is the difference between Grid and GridbagLayout ?
How will you add panel to a Frame ?
What is the corresponding Layout for Card in Swing ?
What is light weight component ?
Can you run the product development on all operating systems ?
What is the webserver used for running the Servlets ?
What is Servlet API used for connecting database ?
What is bean ? Where it can be used ?
What is difference in between Java Class and Bean ?
Can we send object using Sockets ?
What is the RMI and Socket ?
How to communicate 2 threads each other ?
What are the files generated after using IDL to Java Compilet ?
What is the difference between CGI and Servlet?
What is meant by a servlet?
What are the types of servlets? What is the difference between 2 types of Servlets?
What is the type of method for sending request from HTTP server ?
What are the exceptions thrown by Servlets? Why?
What is the life cycle of a servlet?
What is meant by cookies? Why is Cookie used?
What is HTTP Session?
What is the difference between GET and POST methods?
How can you run a Servlet Program?
What is the middleware? What is the functionality of Webserver?
What webserver is used for running the Servlets?
How do you invoke a Servelt? What is the difference in between doPost and doGet methods?
What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me their parameter names also?
What are session variable in Servlets?
What is meant by Session? Tell me something about HTTPSession Class?
What is Session Tracking?
Difference between doGet and doPost?
What are the methods in HttpServlet?
What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet?
What is a class? A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
What is a object? An object is a software bundle of variables and related methods.An instance of a class depicting the state and behavior at that particular time in real world.
What is a method? Encapsulation of a functionality which can be called to perform specific tasks.
What is encapsulation? Explain with an example. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessible via the interface of the object
What is inheritance? Explain with an example. Inheritance in object oriented programming means that a class of objects can inherit properties and methods from another class of objects.
What is polymorphism? Explain with an example. In object-oriented programming, polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language
Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed in Java.
What is interpreter and compiler? Java interpreter converts the high level language code into a intermediate form in Java called as bytecode, and then executes it, where as a compiler converts the high level language code to machine language making it very hardware specific
What is JVM? The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)
What are the different types of modifiers? There are access modifiers and there are other identifiers. Access modifiers are public, protected and private. Other are final and static.
What are the access modifiers in Java? There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but programmer cannot specify the friendly identifier explicitly.
What is a wrapper class? They are classes that wrap a primitive data type so it can be used as a object
What is a static variable and static method? What’s the difference between two? The modifier static can be used with a variable and method. When declared as static variable, there is only one variable no matter how instances are created, this variable is initialized when the class is loaded. Static method do not need a class to be instantiated to be called, also a non static method cannot be called from static method.
What is garbage collection? Garbage Collection is a thread that runs to reclaim the memory by destroying the objects that cannot be referenced anymore.
What is abstract class? Abstract class is a class that needs to be extended and its methods implemented, aclass has to be declared abstract if it has one or more abstract methods.
What is meant by final class, methods and variables? This modifier can be applied to class method and variable. When declared as final class the class cannot be extended. When declared as final variable, its value cannot be changed if is primitive value, if it is a reference to the object it will always refer to the same object, internal attributes of the object can be changed.
What is interface? Interface is a contact that can be implemented by a class, it has method that need implementation.
What is method overloading? Overloading is declaring multiple method with the same name, but with different argument list.
What is method overriding? Overriding has same method name, identical arguments used in subclass.
What is singleton class? Singleton class means that any given time only one instance of the class is present, in one JVM.
What is the difference between an array and a vector? Number of elements in an array are fixed at the construction time, whereas the number of elements in vector can grow dynamically.
What is a constructor? In Java, the class designer can guarantee initialization of every object by providing a special method called a constructor. If a class has a constructor, Java automatically calls that constructor when an object is created, before users can even get their hands on it. So initialization is guaranteed.
What is casting? Conversion of one type of data to another when appropriate. Casting makes explicitly converting of data.
What is the difference between final, finally and finalize? The modifier final is used on class variable and methods to specify certain behaviour explained above. And finally is used as one of the loop in the try catch blocks, It is used to hold code that needs to be executed whether or not the exception occurs in the try catch block. Java provides a method called finalize( ) that can be defined in the class. When the garbage collector is ready to release the storage ed for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the objects memory. So finalize( ), gives you the ability to perform some important cleanup at the time of garbage collection.
What is are packages? A package is a collection of related classes and interfaces providing access protection and namespace management.
What is a super class and how can you call a super class? When a class is extended that is derived from another class there is a relationship is created, the parent class is referred to as the super class by the derived class that is the child. The derived class can make a call to the super class using the keyword super. If used in the constructor of the derived class it has to be the first statement.
What is meant by a Thread? Thread is defined as an instantiated parallel process of a given program.
What is multi-threading? Multi-threading as the name suggest is the scenario where more than one threads are running.
What are two ways of creating a thread? Which is the best way and why? Two ways of creating threads are, one can extend from the Java.lang.Thread and can implement the rum method or the run method of a different class can be called which implements the interface Runnable, and the then implement the run() method. The latter one is mostly used as first due to Java rule of only one class inheritance, with implementing the Runnable interface that problem is sorted out.
What is deadlock? Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread. In Java, this resource is usually the object lock obtained by the synchronized keyword.
What are the three types of priority? MAX_PRIORITY which is 10, MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
What is the use of synchronizations? Every object has a lock, when a synchronized keyword is used on a piece of code the, lock must be obtained by the thread first to execute that code, other threads will not be allowed to execute that piece of code till this lock is released.
What is the Collections API? - The Collections API is a set of classes and interfaces that support operations on collections of objects
What is the List interface? - The List interface provides support for ordered collections of objects.
What is the Vector class? - The Vector class provides the capability to implement a growable array of objects
What is an Iterator interface? - The Iterator interface is used to step through the elements of a Collection
Which java.util classes and interfaces support event handling? - The EventObject class and the EventListener interface support event processing
What is the GregorianCalendar class? - The GregorianCalendar provides support for traditional Western calendars
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
What is the SimpleTimeZone class? - The SimpleTimeZone class provides support for a Gregorian calendar
What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values
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
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
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
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.
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.
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.
When a thread blocks on I/O, what state does it enter? - A thread enters the waiting state when it blocks on I/O.
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.
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.
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.
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.
What are the high-level thread states? - The high-level thread states are ready, running, waiting, and dead
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.
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.
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.
What state is a thread in when it is executing? - An executing thread is in the running state
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.
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.
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.
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.
What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. For example, a thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
What are different ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, blocking on I/O, unsuccessfully attempting to acquire an object’s lock, or invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
What’s new with the stop(), suspend() and resume() methods in new JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally.
What method is used to specify a container’s layout? The setLayout() method is used to specify a container’s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout.
Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout.
What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state.
What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. One example of class in Collections API is Vector and Set and List are examples of interfaces in Collections API.
What is the List interface? The List interface provides support for ordered collections of objects. It may or may not allow duplicate elements but the elements must be ordered.
How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
What is the Vector class? The Vector class provides the capability to implement a growable array of objects. The main visible advantage of this class is programmer needn’t to worry about the number of elements in the Vector.
What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection.
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits, ASCII require 7 bits (although the ASCII character set uses only 7 bits, it is usually represented as 8 bits), UTF-8 represents characters using 8, 16, and 18 bit patterns, UTF-16 uses 16-bit and larger bit patterns
What is the difference between yielding and sleeping? Yielding means a thread returning to a ready state either from waiting, running or after creation, where as sleeping refers a thread going to a waiting state from running state. With reference to Java, when a task invokes its yield() method, it returns to the ready state and when a task invokes its sleep() method, it returns to the waiting state
What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as objects. For example, Integer, Double. These classes contain many methods which can be used to manipulate basic data types
Does garbage collection guarantee that a program will not run out of memory? No, it doesn’t. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. The main purpose of Garbage Collector is recover the memory from the objects which are no longer required when more memory is needed.
Name Component subclasses that support painting? The following classes support painting: Canvas, Frame, Panel, and Applet.
What is a native method? A native method is a method that is implemented in a language other than Java. For example, one method may be written in C and can be called in Java.
How can you write a loop indefinitely?
for(;;) //for loop
while(true); //always true
Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection.
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.
What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars.
What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.
What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system.
What is the purpose of the System class? The purpose of the System class is to provide access to system resources.
What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. For example,
try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or not
}
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.
What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its implements clause.
What is JServer and what is it used for? Oracle JServer Option is a Java Virtual Machine (Java VM) which runs within the Oracle database server’s address space. Oracle also provides a JServer Accelerator to compile Java code natively. This speeds up the execution of Java code by eliminating interpreter overhead.
How does one install the Oracle JServer Option?Follow these steps to activate the Oracle JServer/ JVM option:
Make sure your database is started with large java_pool_size (>20M) and shared_pool_size (>50M) INIT.ORA parameter values.
Run the $ORACLE_HOME/javavm/install/initjvm.sql script from SYS AS SYSDBA to install the Oracle JServer Option on a database.
Grant JAVAUSERPRIV to users that wants to use Java:
SQL> GRANT JAVAUSERPRIV TO SCOTT;
The rmjvm.sql script can be used to deinstall the JServer option from your database.
Follow the steps in the Oracle Migrations Guide to upgrade or downgrade the JServer option from one release to
another.
source code into the database? Use the “CREATE OR REPLACE JAVA SOURCE” command or “loadjava” utility. Loaded code can be viewed by selecting from the USER_SOURCE view.
Why does one need to publish Java in the database? Publishing Java classes on the database makes it visible on a SQL and PL/SQL level. It is important to publish your code before calling it from SQL statements or PL/SQL code.
What is JDBC and what is it used for? JDBC is a set of classes and interfaces written in Java to allow other Java programs to send SQL statements to a relational database management system. Oracle provides three categories of JDBC drivers: (a) JDBC Thin Driver (No local Net8 installation required/ handy for applets), (b) JDBC OCI for writing stand-alone Java applications, (c) JDBC KPRB driver (default connection) for Java Stored Procedures and Database JSP’s.
How does one connect with the JDBC Thin Driver?
The the JDBC thin driver provides the only way to access Oracle from the Web (applets). It is smaller and faster than the OCI drivers, and doesn’t require a pre-installed version of the JDBC drivers.
import java.sql.*;
class dbAccess {
public static void main (String args []) throws SQLException
{
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());

Connection conn = DriverManager.getConnection
(\"jdbc:oracle:thin:@hostname:1526:orcl\", \"scott\", \"tiger\");
// @machineName:port:SID, userid, password

Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(\"select BANNER from SYS.V_$VERSION\");
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
stmt.close();
}
}
How does one connect with the JDBC OCI Driver? One must have Net8 (SQL*Net) installed and working before attempting to use one of the OCI drivers.
import java.sql.*;
class dbAccess {
public static void main (String args []) throws SQLException
{
try {
Class.forName (\"oracle.jdbc.driver.OracleDriver\");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Connection conn = DriverManager.getConnection
(\"jdbc:oracle:oci8:@hostname_orcl\", \"scott\", \"tiger\");
// or oci7 @TNSNames_Entry, userid, password

Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(\"select BANNER from SYS.V_$VERSION\");
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
stmt.close();
}
}
How does one connect with the JDBC KPRB Driver? One can obtain a handle to the default or current connection (KPRB driver) by calling the OracleDriver.defaultConenction() method. Please note that you do not need to specify a database URL, username or password as you are already connected to a database session. Remember not to close the default connection. Closing the default connection might throw an exception in future releases of Oracle.
import java.sql.*;
class dbAccess {
public static void main (String args []) throws SQLException
{
Connection conn = (new oracle.jdbc.driver.OracleDriver()).defaultConnection();

Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(\"select BANNER from SYS.V_$VERSION\");
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
stmt.close();
}
}
What is SQLJ and what is it used for? SQLJ is an ANSI standard way of coding SQL access in Java. It provides a Java precompiler that translates SQLJ call to JDBC calls. The idea is similar to that of other Oracle Precompilers.
How does one deploy SQLJ programs? Use the sqlj compiler to compile your *.sqlj files to *.java and *.ser files. The *.ser files contain vendor specific database code. Thereafter one invokes the javac compiler to compile the .java files to *.class files. The *.class and *.ser files needs to be deployed.
What is JDeveloper and what is it used for? JDeveloper is the Oracle IDE (Integrated Development Environment) for developing SQLJ and JDBC programs, applets, stored procedures, EJB’s, JSP’s etc.
What is InfoBus DAC and what is it used for? InfoBus DAC (Data Aware Controls) is a standard Java extension used in JDeveloper to create data aware forms. It replaced the JBCL interface that were used in JDeveloper V1 and V2.
What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN’s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.
What is the difference between ASP and JSP? Active Server Pages (ASP) is a Microsoft standard, which is easier to develop than Java Server Pages (JSP). However ASP is a proprietary technology and is less flexible than JSP. For more information about ASP, see the Oracle ASP FAQ.
How does one invoke a JSP? A JSP gets invoked when you call a *.jsp file from your Web Server like you would call a normal *.html file. Obviously your web server need to support JSP pages and must be configured properly to handle them.
How does a JSP gets executed? The first time you call a JSP, a servlet (*.java) will be created and compiled to a .class file. The class file is then executed on the server. Output produced by the servlet is returned to the web browser. Output will typically be HTML or XML code.
What is a Java Stored Procedure/ Trigger? A Java Stored Procedure is a procedure coded in Java (as opposed to PL/SQL) and stored in the Oracle database. Java Stored procedures are executed by the database JVM in database memory space. Java Stored Procedures can be developed in JDBC or SQLJ. Interfacing between PL/SQL and Java are extremely easy. Please note that Java Stored procedures are by default executed with invokers rights. PL/SQL procedures are by default executed with defines rights.
Java applet interview questions
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.
What are the Applet’s Life Cycle methods? Explain them? - Following are methods in the life cycle of an Applet:
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.
start( ) method - called each time an applet is started.
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.
stop( ) method - called when the browser moves off the applet’s page.
destroy( ) method - called when the browser is finished with the applet.
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:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls takes place :
stop()
destroy()
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.
Can we pass parameters to an applet from HTML page to an applet? How? - We can pass parameters to an applet using tag in the following way:


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.
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.
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.
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.
URL targetURL;
String URLString
AppletContext context = getAppletContext();
try
{
targetURL = new URL(URLString);
}
catch (MalformedURLException e)
{
// Code for recover from the exception
}
context. showDocument (targetURL);
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.
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:
Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();
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.
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.
What tags are mandatory when creating HTML to display an applet?
name, height, width
code, name
codebase, height, width
code, height, width
Correct answer is d.
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.
What are the steps involved in Applet development? - Following are the steps involved in Applet development:
Create/Edit a Java source file. This file must contain a class which extends Applet class.
Compile your program using javac
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.
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 AWT interview questions
What is meant by Controls and what are different types of controls? - Controls are componenets that allow a user to interact with your application. The AWT supports the following types of controls:
Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text components
These controls are subclasses of Component.
Which method of the component class is used to set the position and the size of a component? - setBounds(). The following code snippet explains this:
txtName.setBounds(x,y,width,height);
places upper left corner of the text field txtName at point (x,y) with the width and height of the text field set as width and height.
Which TextComponent method is used to set a TextComponent to the read-only state? - setEditable()
How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a CheckboxGroup.
What methods are used to get and set the text label displayed by a Button object? - getLabel( ) and setLabel( )
What is the difference between a Choice and a List? - Choice: A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. List: A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
What is the difference between a Scollbar and a Scrollpane? - A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.
Which are true about the Container class?
The validate( ) method is used to cause a Container to be laid out and redisplayed.
The add( ) method is used to add a Component to a Container.
The getBorder( ) method returns information about a Container’s insets.
getComponent( ) method is used to access a Component that is contained in a Container.
Answers: a, b and d
Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frame’s font is set to 12-point TimesRoman, the Panel’s font is set to 10-point TimesRoman, and the Button’s font is not set, what font will be used to display the Button’s label?
12-point TimesRoman
11-point TimesRoman
10-point TimesRoman
9-point TimesRoman
Answer: c.
What are the subclasses of the Container class? - The Container class has three major subclasses. They are:
Window
Panel
ScrollPane
Which object is needed to group Checkboxes to make them exclusive? - CheckboxGroup.
What are the types of Checkboxes and what is the difference between them? - Java supports two types of Checkboxes:
Exclusive
Non-exclusive.
In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called as Radio buttons. The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other.
What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default Layout manager for the panel and the panel subclasses? - A layout Manager is an object that is used to organize components in a container. The different layouts available in java.awt are:
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
GridBagLayout:
The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy more
than one row or column of the grid. In addition, the rows and columns may have different sizes.
The default Layout Manager of Panel and Panel sub classes is FlowLayout.
Can I add the same component to more than one container? - No. Adding a component to a container automatically removes it from any previous parent (container).
How can we create a borderless window? - Create an instance of the Window class, give it a size, and show it on the screen.
Frame aFrame = new Frame();
Window aWindow = new Window(aFrame);
aWindow.setLayout(new FlowLayout());
aWindow.add(new Button(\"Press Me\"));
aWindow.getBounds(50,50,200,200);
aWindow.show();
Can I create a non-resizable windows? If so, how? - Yes. By using setResizable() method in class Frame.
Which containers use a BorderLayout as their default layout? Which containers use a FlowLayout as their default layout? - The Window, Frame and Dialog classes use a BorderLayout as their default layout. The Panel and the Applet classes use the FlowLayout as their default layout.
How do you change the current layout manager for a container?
Use the setLayout method
Once created you cannot change the current layout manager of a component
Use the setLayoutManager method
Use the updateLayout method
Answer: a.
What is the difference between a MenuItem and a CheckboxMenuItem?- The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
How do you call a Stored Procedure from JDBC? - The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.
CallableStatement cs =
con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
Is the JDBC-ODBC Bridge multi-threaded? - No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.
Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? - No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
What is cold backup, hot backup, warm backup recovery? - Cold backup (All these files must be backed up at the same time, before the databaseis restarted). Hot backup (official name is ‘online backup’) is a backup taken of each tablespace while the database is running and is being accessed by the users.
When we will Denormalize data? - Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
What is the advantage of using PreparedStatement? - If we are using PreparedStatement the execution time will be less. The PreparedStatement object contains not just an SQL statement, but the SQL statement that has been precompiled. This means that when the PreparedStatement is executed,the RDBMS can just run the PreparedStatement’s Sql statement without having to compile it first.
What is a “dirty read”? - Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.
What is Metadata and why should I use it? - Metadata (’data about data’) is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns
Different types of Transaction Isolation Levels? - The isolation level describes the degree to which the data being updated is visible to other transactions. This is important when two transactions are trying to read the same row of a table. Imagine two transactions: A and B. Here three types of inconsistencies can occur:
Dirty-read: A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong if A rolls back his changes and updates his own changes to the database.
Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B reads the same row again, he will get different data.
Phantoms: A does a query on a set of rows to perform an operation. B modifies the table such that a query of A would have given a different result. The table may be inconsistent.
TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR.
TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-REPEATABLE READ ARE PREVENTED AND PHANTOMS CAN OCCUR.
TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS ARE PREVENTED.
What is 2 phase commit? - A 2-phase commit is an algorithm used to ensure the integrity of a committing transaction. In Phase 1, the transaction coordinator contacts potential participants in the transaction. The participants all agree to make the results of the transaction permanent but do not do so immediately. The participants log information to disk to ensure they can complete In phase 2 f all the participants agree to commit, the coordinator logs that agreement and the outcome is decided. The recording of this agreement in the log ends in Phase 2, the coordinator informs each participant of the decision, and they permanently update their resources.
How do you handle your own transaction ? - Connection Object has a method called setAutocommit(Boolean istrue)
- Default is true. Set the Parameter to false , and begin your transaction
What is the normal procedure followed by a java client to access the db.? - The database connection is created in 3 steps:
Find a proper database URL
Load the database driver
Ask the Java DriverManager class to open a connection to your database
In java code, the steps are realized in code as follows:
Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the form
jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
Class.forName(”my.database.driver”);
Connection conn = DriverManager.getConnection(”a.JDBC.URL”, “databaseLogin”,”databasePassword”);
What is a data source? - A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.
What are collection pools? What are the advantages? - A connection pool is a cache of database connections that is maintained in memory, so that the connections may be reused
How do you get Column names only for a table (SQL Server)? Write the Query. -
select name from syscolumns
where id=(select id from sysobjects where name='user_hdr')
order by colid --user_hdr is the table name
What advantage do Java’s layout managers provide over traditional windowing systems? - Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.
What is the difference between the paint() and repaint() methods? - The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a CheckboxGroup
What is the difference between a Choice and a List? - A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
What interface is extended by AWT event listeners? - All AWT event listeners extend the java.util.EventListener interface.
What is a layout manager? - A layout manager is an object that is used to organize components in a container
Which Component subclass is used for drawing and painting? - Canvas
What are the problems faced by Java programmers who dont use layout managers? - Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system
What is the difference between a Scrollbar and a ScrollPane? (Swing) - A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
What is garbage collection? What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
What kind of thread is the Garbage collector thread? - It is a daemon thread.
What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)
What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object.
What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
What is the base class for Error and Exception? - Throwable
What is the byte range? -128 to 127
What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented.
What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
What is a DatabaseMetaData? - Comprehensive information about the database as a whole.
What is Locale? - A Locale object represents a specific geographical, political, or cultural region
How will you load a specific locale? - Using ResourceBundle.getBundle(…);
What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler - no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
Is JVM a compiler or an interpreter? - Interpreter
When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler
What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator, …)
What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
What is the significance of ListIterator? - You can iterate back and forth.
What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
What is nested class? - If all the methods of a inner class is static then it is a nested class.
What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
What is composition? - Holding the reference of the other class within some other class is known as composition.
What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
What is DriverManager? - The basic service to manage set of JDBC drivers.
What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).
Java Swing interview questions 1) Can a class be it’s own event handler? Explain how to implement this.
Answer: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the actionPerformed method, put the code to perform when the button is pressed.
2) Why does JComponent have add() and remove() methods but Component does not?
Answer: because JComponent is a subclass of Container, and can contain other components and jcomponents.
3) How would you create a button with rounded edges?
Answer: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how would I do that?
Answer: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate. (I don’t know it offhand, but I think it’s "com.sun.ui.motiflookandfeel.MotifTabbedPaneUI" - anything simiar is a good answer.)
5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?
Answer: The Font Class is used to render ‘glyphs’ - the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent)
6) What class is at the top of the AWT event hierarchy?
Answer: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a while.
7) Explain how to render an HTML page using only Swing.
Answer: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane.
8) How would you detect a keypress in a JComboBox?
Answer: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ - but the right answer is ‘add a KeyListener to the JComboBox’s editor component.’
9) Why should the implementation of any Swing callback (like a listener) execute quickly?
A: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
10) In what context should the value of Swing components be updated directly?
A: Swing components should be updated directly only in the context of callback methods invoked from the event dispatch thread. Any other context is not thread safe?
11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?
A: I want to update a Swing component but I’m not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when the update occurs, I’d use invokeLater.
12) If your UI seems to freeze periodically, what might be a likely reason?
A: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is taking a long time to execute thereby blocking the event dispatch thread from processing other UI events.
13) Which Swing methods are thread-safe?
A: The only thread-safe methods are repaint(), revalidate(), and invalidate()
14) Why won’t the JVM terminate when I close all the application windows?
A: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM.
What is the protocol used by server and client ?
Can I modify an object in CORBA ?
What is the functionality stubs and skeletons ?
What is the mapping mechanism used by Java to identify IDL language ?
Diff between Application and Applet ?
What is serializable Interface ?
What is the difference between CGI and Servlet ?
What is the use of Interface ?
Why Java is not fully objective oriented ?
Why does not support multiple Inheritance ?
What it the root class for all Java classes ?
What is polymorphism ?
Suppose If we have variable ‘ I ‘ in run method, If I can create one or more thread each thread will occupy a separate copy or same variable will be shared ?
In servlets, we are having a web page that is invoking servlets username and password ? which is checked in the database ? Suppose the second page also If we want to verify the same information whether it will connect to the database or it will be used previous information?
What are virtual functions ?
Write down how will you create a binary Tree ?
What are the traverses in Binary Tree ?
Write a program for recursive Traverse ?
What are session variable in Servlets ?
What is client server computing ?
What is Constructor and Virtual function? Can we call Virtual function in a constructor ?
Why we use OOPS concepts? What is its advantage ?
What is the middleware ? What is the functionality of Webserver ?
Why Java is not 100 % pure OOPS ? ( EcomServer )
When we will use an Interface and Abstract class ?
What is an RMI?
How will you pass parameters in RMI ? Why u serialize?
What is the exact difference in between Unicast and Multicast object ? Where we will use ?
What is the main functionality of the Remote Reference Layer ?
How do you download stubs from a Remote place ?
What is the difference in between C++ and Java ? can u explain in detail ?
I want to store more than 10 objects in a remote server ? Which methodology will follow ?
What is the main functionality of the Prepared Statement ?
What is meant by static query and dynamic query ?
What are the Normalization Rules ? Define the Normalization ?
What is meant by Servlet? What are the parameters of the service method ?
What is meant by Session ? Tell me something about HTTPSession Class ?
How do you invoke a Servlet? What is the difference in between doPost and doGet methods ?
What is the difference in between the HTTPServlet and Generic Servlet ? Explain their methods ? Tell me their parameter names also ?
Have you used threads in Servlet ?
Write a program on RMI and JDBC using StoredProcedure ?
How do you sing an Applet ?
In a Container there are 5 components. I want to display the all the components names, how will you do that one ?
Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
Tell me the latest versions in JAVA related areas ?
What is meant by class loader ? How many types are there? When will we use them ?
How do you load an Image in a Servlet ?
What is meant by flickering ?
What is meant by distributed Application ? Why we are using that in our applications ?
What is the functionality of the stub ?
Have you used any version control ?
What is the latest version of JDBC ? What are the new features are added in that ?
Explain 2 tier and 3 -tier Architecture ?
What is the role of the webserver ?
How have you done validation of the fields in your project ?
What is the main difficulties that you are faced in your project ?
What is meant by cookies ? Explain ?
.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.

.Does Java provide any construct to find out the size of an object? No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java. 2.Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code...
long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println ("Time taken for execution is " + (end - start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.
3.What are wrapper classes? Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.
4.Why do we need wrapper classes? It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object
. 5.What are checked exceptions? Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
6.What are runtime exceptions? Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
7.What is the difference between error and an exception? An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
8.How to create custom exceptions? Your class should extend class Exception, or some more specific type thereof.
9.If I want an object of my class to be thrown as an exception object, what should I do? The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
10.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object? One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
11.What happens to an unhandled exception? One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
12.How does an exception permeate through the code? An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.
13.What are the different ways to handle exceptions? There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions. 14.What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause?
When should you use which approach? In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
15.Is it necessary that each try block must be followed by a catch block? It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
16.If I write return at the end of the try block, will the finally block still execute? Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
17.If I write System.exit (0); at the end of the try block, will the finally block still execute? No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.
1.How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
2.What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to
significant errors.
3.How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
4.Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of
memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
5.What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters
the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
6.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.
7.What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. 8.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.
9.What is the difference between a while statement and a do statement? A while statement checks at the beginning of a loop to see whether the nextloop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will
always execute the body of a loop at least once.
10.What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. 11.How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used toinvoke a superclass constructor.
12.What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
What is the query used to display all tables names in SQL Server (Query analyzer)?
select * from information_schema.tables
How many types of JDBC Drivers are present and what are they?- There are 4 types of JDBC Drivers
JDBC-ODBC Bridge Driver
Native API Partly Java Driver
Network protocol Driver
JDBC Net pure Java Driver
Can we implement an interface in a JSP?- No
What is the difference between ServletContext and PageContext?- ServletContext: Gives the information about the container. PageContext: Gives the information about the Request
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.
How to pass information from JSP to included JSP?- Using <%jsp:param> tag.
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.
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.
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.
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);
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.

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 is used for including non-JSP files.
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().
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.
What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues:
the quality of the driver code,
the size of the driver code,
the database server and its load,
network topology,
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).
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+)
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.
JDBC Interview Questions
What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection.
How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);
Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code:
Class.forName(”jdbc.DriverXYZ”);
What will Class.forName do while loading drivers? It is used to create an instance of a driver and register it with the
DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS.
The following line of code illustrates the general idea:
String url = “jdbc:odbc:Fred”;
Connection con
= DriverManager.getConnection(url, “Fernanda”, “J8?);
How can you create JDBC statements and what are they?
A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object
Statement stmt = con.createStatement();
How can you retrieve data from the ResultSet?
JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.
ResultSet rs = stmt.executeQuery
(”SELECT COF_NAME, PRICE FROM COFFEES”);
String s = rs.getString(”COF_NAME”);
The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs.
What are the different types of Statements?
Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)
How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a
Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first.
PreparedStatement updateSales =
con.prepareStatement(\"UPDATE COFFEES SET SALES =
? WHERE COF_NAME LIKE ?\");
What does setAutoCommit do?
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.
con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( \"UPDATE COFFEES
SET SALES = ? WHERE COF_NAME LIKE ?\");
updateSales.setInt(1, 50); updateSales.setString(2, \"Colombian\");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement(\"UPDATE COFFEES
SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?\");
updateTotal.setInt(1, 50);
updateTotal.setString(2, \"Colombian\");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
How do you call a stored procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open
Connection object. A CallableStatement object contains a call to a stored procedure.
CallableStatement cs
= con.prepareCall(\"{call SHOW_SUPPLIERS}\");
ResultSet rs = cs.executeQuery();
How do I retrieve warnings?
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these
classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object:
SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
System.out.println(\"n---Warning---n\");
while (warning != null)
{
System.out.println(\"Message: \" + warning.getMessage());
System.out.println(\"SQLState: \" + warning.getSQLState());
System.out.print(\"Vendor error code: \");
System.out.println(warning.getErrorCode());
System.out.println(\"\");
warning = warning.getNextWarning();
}
}
How can you move the cursor in scrollable result sets?
One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs =
stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);
The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?
You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs =
stmt.executeQuery(\"SELECT COF_NAME, PRICE FROM COFFEES\");
srs.afterLast();
while (srs.previous())
{
String name = srs.getString(\"COF_NAME\");
float price = srs.getFloat(\"PRICE\");
System.out.println(name + \" \" + price);
}
How to Make Updates to Updatable Result Sets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
Connection con =
DriverManager.getConnection(\"jdbc:mySubprotocol:mySubName\");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =
stmt.executeQuery(\"SELECT COF_NAME, PRICE FROM COFFEES\");
What is JSP? Describe its concept. JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic
What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.
Page translation: -page is parsed, and a java file which is a servlet is created.
Page compilation: page is compiled into a class file
Page loading : This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.
What is a translation unit? JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.
How is JSP used in the MVC model? JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.
What are context initialization parameters? Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.
What is a output comment? A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
What is a Hidden Comment? A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.
What is a Expression? Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed.
What is a Declaration? It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file.
What is a Scriptlet? A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a .
What are the implicit objects? List them. Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:
request
response
pageContext
session
application
out
config
page
exception
What’s the difference between forward and sendRedirect? When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
What are the different scope values for the ? The different scope values for are:
page
request
session
application
Why are JSP pages the preferred API for creating a web-based client program? Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
Is JSP technology extensible? Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals - encapsulating complex behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
Custom tags require quite a bit more work to set up than do beans.
Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
17. 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.
18.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.
19. What language is used by a relational model to describe the structure of a database?
A: The Data Definition Language.
20. 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).
21.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 th
Junior Java Programmer Interview Questions
What is the purpose of finalization? - The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
What is the difference between the Boolean & operator and the && operator? - If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
How many times may an object’s finalize() method be invoked by the garbage collector? - An object’s finalize() method may only be invoked once by the garbage collector.
What is the purpose of the finally clause of a try-catch-finally statement? - The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
What is the argument type of a program’s main() method? - A program’s main() method takes an argument of the String[] type.
Which Java operator is right associative? - The = operator is right associative.
Can a double value be cast to a byte? - Yes, a double value can be cast to a byte.
What is the difference between a break statement and a continue statement? - A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
What must a class do to implement an interface? - It must provide all of the methods in the interface and identify the interface in its implements clause.
What is the advantage of the event-delegation model over the earlier event-inheritance model? - The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component’s design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.
How are commas used in the intialization and iteration parts of a for statement? - Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.
What is an abstract method? - An abstract method is a method whose implementation is deferred to a subclass.
What value does read() return when it has reached the end of a file? - The read() method returns -1 when it has reached the end of a file.
Can a Byte object be cast to a double value? - No, an object cannot be cast to a primitive value.
What is the difference between a static and a non-static inner class? - A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.
If a variable is declared as private, where may the variable be accessed? - A private variable may only be accessed within the class in which it is declared.
What is an object’s lock and which object’s have locks? - An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.
What is the % operator? - It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
When can an object reference be cast to an interface reference? - An object reference be cast to an interface reference when the object implements the referenced interface.
Which class is extended by all other classes? - The Object class is extended by all other classes.
Can an object be garbage collected while it is still reachable? - A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.
Is the ternary operator written x : y ? z or x ? y : z ? - It is written x ? y : z.
How is rounding performed under integer division? - The fractional part of the result is truncated. This is known as rounding toward zero.
What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? - The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
What classes of exceptions may be caught by a catch clause? - A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
If a class is declared without any access modifiers, where may the class be accessed? - A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
Does a class inherit the constructors of its superclass? - A class does not inherit constructors from any of its superclasses.
What is the purpose of the System class? - The purpose of the System class is to provide access to system resources.
Name the eight primitive Java types. - The eight primitive types are byte, char, short, int, long, float, double, and boolean.
Which class should you use to obtain design information about an object? - The Class class is used to obtain information about an object’s design.
1.What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax


Example 1


Displays in the page source:

2.What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>

A Hidden Comment

<%-- This comment will not be visible to the colent in the page source --%>


3.What is a Expression?
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
4.What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>
5.What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can
1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.
6.What are implicit objects? List them?
Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
request
response
pageContext
session
application
out
config
page
exception
7.Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
8.What are the different scope valiues for the ?
The different scope values for are
1. page
2. request
3.session
4.application
9.Explain the life-cycle mehtods in JSP?
THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
Java and Perl Web programming interview questions
How can we store the information returned from querying the database? and if it is too big, how does it affect the performance? In Java the return information will be stored in the ResultSet object. Yes, if the ResultSet is getting big, it will slow down the process and the performance as well. We can prevent this situation by give the program a simple but specific query statement.
What is index table and why we use it? Index table are based on a sorted ordering of the values. Index table provides fast access time when searching.
In Java why we use exceptions? Java uses exceptions as a way of signaling serious problems when you execute a program. One major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors.
Write a code in Perl that makes a connection to Database.
#!/usr/bin/perl
#makeconnection.pl

use DBI;
my $dbh = DBI->connect('dbi:mysql:test','root','foo')||die "Error opening database:
$DBI::errstrn";
print"Successful connect to databasen";

$dbh->disconnect || die "Failed to disconnectn";
Write a code in Perl that select all data from table Foo?
#!usr/bin/perl
#connect.pl

use DBI;
my ($dbh, $sth, $name, $id);
$dbh= DBI->connect('dbi:mysql:test','root','foo')
|| die "Error opening database: $DBI::errstrn";
$sth= $dbh->prepare("SELECT * from Foo;")
|| die "Prepare failed: $DBI::errstrn";
$sth->execute()
|| die "Couldn't execute query: $DBI::errstrn";
while(( $id, $name) = $sth->fetchrow_array)
{
print "$name has ID $idn";
}
$sth->finish();

$dbh->disconnect
|| die "Failed to disconnectn";
Can we use the constructor, instead of init(), to initialize servlet? - Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
How can a servlet refresh automatically if some new data has entered the database? - You can use a client-side Refresh or Server Push.
The code in a finally clause will never fail to execute, right? - Using System.exit(1); in try block will not allow finally code to execute.
How many messaging models do JMS provide for and what are they? - JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.
What information is needed to create a TCP Socket? - The Local System?s IP Address and Port Number. And the Remote System’s IPAddress and Port Number.
What Class.forName will do while loading drivers? - It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
How to Retrieve Warnings? - SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
while (warning != null)
{
System.out.println(\"Message: \" + warning.getMessage());
System.out.println(\"SQLState: \" + warning.getSQLState());
System.out.print(\"Vendor error code: \");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
How many JSP scripting elements are there and what are they? - There are three scripting language elements: declarations, scriptlets, expressions.
In the Servlet 2.4 specification SingleThreadModel has been deprecated, why? - Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
What are stored procedures? How is it useful? - A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.
How do I include static files within a JSP page? - Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.
Why does JComponent have add() and remove() methods but Component does not? - because JComponent is a subclass of Container, and can contain other components and jcomponents.
How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.
Meaning - Abstract classes, abstract methods
Difference - Java,C++
Difference between == and equals method
Explain Java security model
Explain working of Java Virtual Machine (JVM)
Difference : Java Beans, Servlets
Difference : AWT, Swing
Disadvantages of Java
What is BYTE Code ?
What gives java it's "write once and run anywhere" nature?
Does Java have "goto"?
What is the meaning of "final" keyword?
Can I create final executable from Java?
Explain Garbage collection mechanism in Java
Why Java is not 100% pure object oriented language?
What are interfaces? or How to support multiple inhertance in Java?
How to use C++ code in Java Program?
Difference between "APPLET" and "APPLICATION"
1.What is the difference between an Interface and an Abstract class?
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.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.

3.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.

4.Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

5.What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

6.What is HashMap and Map?
Map is Interface and Hashmap is class that implements that.

7.Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized.


8.Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.


9.Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.


10.What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.


11.What is an Iterators?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.


12.State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
public : Public class is visible in other packages, field is visible everywhere (class must be public too) private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature. protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature. default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.


13.What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.


14.What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.


15.What is final?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
1.What if the main method is declared as private?
The program compiles properly but at runtime it will give "Main method not public." message.
2.What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
3.What if I write static public void instead of public static void?
Program compiles and runs properly.
4.What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".
5.What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
6.If I do not provide any arguments on the command line, then the String array of Main method will be empty of null?
It is empty. But not null.
7.How can one prove that the array is not null but empty?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
8.What environment variables do I need to set on my machine in order to be able to run Java programs?
CLASSPATH and PATH are the two variables.
9.Can an application have multiple classes having main method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
10.Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already defined in the class.
11.Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
12.Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
13.What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
14.What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
15.What are different types of inner classes?
Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.
What is a servlet?
Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.
Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.
What are the general advantages and selling points of Servlets?
A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online
real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.
Which package provides interfaces and classes for writing servlets? javax
What’s the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more
commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet.
The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.
When a servlet accepts a call from a client, it receives two objects. What are they?
ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.
What information does ServletRequest allow access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names
of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods.
What type of constraints can ServletResponse interface set on the client?
It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through
which the servlet can send the reply data.
Explain servlet lifecycle?
Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down.
How does HTTP Servlet handle client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.
Explain the life cycle methods of a Servlet ? The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface? The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.
Explain the directory structure of a web application ? The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory
What are the common mechanisms used for session tracking? Cookies
SSL sessions
URL- rewriting
Explain ServletContext. ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.
What is preinitialization of a servlet? A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
What is the difference between Difference between doGet() and doPost()?A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
http://www.hitechskill.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
What is the difference between HttpServlet and GenericServlet?A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.
1. What are Java key words and reserved words? What are the differences?
A: Key words are reserved words. but not vice versa. See Java Language Keywords for details.
2. What are Java key words this?
A:this is a keyword used in Java/C++ code to refer the current instance object itself.
3. What modifiers should be used for main method? Why could I violate the rule, and it still works?
A:The official modifiers and signature for main method is
public static void main(String[] args){}
You should remember it, and use this for your SCJP test.
However, if you miss public or even use private instead, some JVM might let you launch your Java application without complaining or error messages. Why?

Because some JVMs just make themselves more tolerant then they should be. This kind of practice is very common in Microsoft world. I guess Sun learned something from there. Take a look at stock price movements of both co. on 2001, you will probably understand why.
4. How does Java compiler resolve the ambiguity to decide which methods to call?
A:In the following example, four test() methods, if we pass ambiguous \b{null} to the test, which one should (will) be called? The 3 on top has super/subclass/sub-subclass relationship. The most specific one (down hierarchy) will be called. The 4th with String as a parameter, but it is a sibling of Tester. Ambiguity compile time error results.
class Tester {
void test(Object s) { System.out.println ("Object version"); }
void test(Tester s) { System.out.println ("Tester version"); }
void test(SubTester s) { System.out.println ("SubTester version"); }

// Not compilable any more if you uncomment the line
// since String and Tester are siblings
// void test(String s) { System.out.println ("String version"); }

public static void main (String args[]) {
Tester c = new Tester ();
// Ambiguous, the most specific one which fit will be call
c.test (null); // SubTester version
c.test (new Object()); // Object version
}
}

class SubTester extends Tester{
}
"The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error." Quotation from JLS2
5. Where can I put labels in Java?
A: See the example here. The comments and commented code tells you everything.
public class Test {
// lbla: //compilable Error: identifier expected
public static void main(String[] args) {
// lblb: //compilable Error: A declaration cannot be labeled
Object o = new Object();
int n = 1;

lblc:
if (o instanceof Object) {
while (true) {
n++;
if (n > 5)
break lblc;
System.out.println(n);
}
}

System.out.println("Finished n");

lblx:
for (int i = 3; i < 7; i++){
// skip number 5
if (i==5)
continue lblx;
System.out.println(i);
}

lbly: // legal before another lable
lblz:
{
System.out.println("Watch:");

break lbly;
// compilable Error: statement not reached
//System.out.println("This will never be printed out.");
}
}
}
6. What is the return type of constructor, if any?
A: General answer is constructor has no return type.
It makes sense. Just think of this:
MyObj o = new MyObj();
7. What are the differences between arguments and parameters?
A: In method call point of view, they are the same. The two words used alternatively for historical reasons. The same reason for so many alternatives for method, such as function, procedure, sub, subroutine, ... If you use those words in different context, then that is a different question, I need to find my English dictionary first...
8. Is null the same as void in Java? Can I return null in a void return type method?
A: No! Another No!
void means return nothing. null in Java means it is a reference type, but refers nothing. null and void are very different things. For further interest, read here. 9. What is the difference of null in Java and NULL in C++?
10. Can we put a continue in a switch-case statement?
A: Answer is a hesitated YES, since it can happen in a special case.
// Guess the print out, then run it.
// A good IQ test
public class A {
public static void main(String args[]) {
int x = 0;
while (x < 10) {
System.out.print(" " + x);
switch (x) {
case 5: x += 2;
continue;
case 2: break;
case 7: break;
default: x++;
};
x++;
}
}
}
11. How to compile 2 Java files simultaneously? The two inter-dependent files are sitting on 2 different hard drives.
A: If you are a beginner of Java, please give yourself a break by not doing this. If you're experienced Java programmer, I don't think your boss will ask you to do this.

Keep It Simple and Stupid (KISS). Please!

But if you insist, figure it out! I guess it can be done, and here is something which might help: 12. How to create my own package, how to call my class in another package?
13. What are the rules to name a Java file without public class defined in it?
A: Everyone knows one Java file only can contain one public class, and the file must be named as the name of the public class name. But how about Java file with no public class?

No restrictions on name of Java file without public class defined. If you have a class with a main, you'd better name the file with that class name for your own convenience. However, this is not required. Test this out!
// D.java
class A {}
class B {}
class C {}
class E {
public static void main(String[] args) {
System.out.println("Strange thing in E.");
}
}
class F {
public static void main(String[] args) {
System.out.println("Strange thing in F.");
}
}
It is called D.java. You can run it in 2 ways:
java E //output: Strange thing in E.
java F //output: Strange thing in F.

If you think carefully, there are good reasons for this. Testing is one of them.
14. Why cannot I use private access modifier in my interface definition?
A: See original discussion here .
Everything declared in interface are implicit or explicit public. If you don't put anything there, they are public (not default). No access modifiers other than public allowed.
15. Where can I find Java Grammar?
A: The best answer is to read the JLS, THE JAVA LANGUAGE SPECIFICATION from the source. Java grammar is officially defined there.
For your academic type, there is an interesting site, called Lykkenborg eZine . The author tried to make Java grammar easier to navigate.
1. What is the difference of signed and unsigned integer?
A:It is the interpretation of the first bit of the integer number been represented. If it is signed, the first bit is 0 means it is a positive number, 1 means it is negative. If it is unsigned, the first bit is just another bit, either to add (1) or not to add (0) 2n to the value of the number. n is the bit location, 0 based counted from right to left.

Here is a binary representation of two bytes:
1111 1111 1111 0100
Signed : -12
unsigned: 65524

0000 0000 0000 1100
Signed : 12
unsigned: 12
If you don't understand how the negative number comes out, read the super article Two's complement .

In java, only char is unsigned, others like byte, short, int, long are all signed. In other languages like c/c++, all other types have a unsigned brother, char is always unsigned.
2. Why char range is 0 to 216-1?
A:
0 to 216-1
0 to 65535
0 to 1111 1111 1111 1111
'\u0000' to '\uFFFF'

All of above are equivalent, since char is unsigned 2 byte integer.

For the first one, use your scientific calculator to do a little math. You can use the following to understand it too.
1111 1111 1111 1111 + 1 = 1 0000 0000 0000 0000 = 216
3. The size of long is 64bits and that of float is 32 bits. then how it is possible long to float without type casting it?
eg.
long l=12345678;
float f = l; // ok to compiler
A: Interesting question!!!
The internal representation of integer types (byte, short, char, long) and floating point number (float, double) are totally different. Converting from long to float is not a narrowing conversion. Even it may lose some significant digits. See the following table for details:
Primitive Data Types
type # of bits range default value when it is a class member

Boolean 8, 1 bit used true false false

char 16 '\u0000' '\uFFFF' '\u0000'

byte 8 -128 +127 0

short 16 -32,768 +32,767 0

int 32 -2,147,483,648 +2,147,483,647 0

long 64 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807 0

float 32 -3.40292347E+38 +3.40292347E+38 0.0

double 64 -1.79769313486231570E+308 + 1.79769313486231570E+308 0.0
4. Why char c = 3; compiles, but float f = 1.3; error out?
A: char c = 3; byte b = 300; short s = 300; int i = 30000;

are assignments to integers(signed or unsigned) Compiler will do a range checking to see if those value are in the range of the variable, if it is, ok; otherwise, error out!

float f = 1.3; float f = 1.3f; double d = 1.3;

are assignments to floating numbers. The difference between 1.3d and 1.3f is the precision, not the range. 1.3 is default to double precision number, assigning it to a float will lose precision. It will need a cast!

1.3 is different than 1.30 in physics/science, since different precision implication.

Distance d = 1.3 miles implies d is between 1.25 and 1.35 miles
Distance d = 1.30 miles implies d is between 1.295 and 1.305 miles, which is a lot more precise measurement.

Of course, not everybody follows the convention.
5. Why byte to char, or float to long are narrow conversion defined by JLS?
A:
class My{
static long l;
static float f;
static char c;
static byte b;
public static void main(String[] ss) {
b=c; //not compilable
c=b; //not compilable either

l=f; //not compilable
f=l; //OK
}
}
Since char is 2 bytes unsigned integer, assign it to 1 byte signed integer will possible loss precision. Opposite is true too, since the negative part of byte will be re-interpret to positive and possible loss precision.

The float to long should be more obvious, since its decimal part will be lost.
6. How many bits represent a boolean variable?
A: Since boolean only has 2 states (true, false), one bit is absolutely enough for storing it. However, in memory, we have no way to represent the address of each bit as a variable address / reference, then we have to use one byte (8 bits) to make the variable addressable. In other words, we only use 1 bit, and leave the other 7 bits unused.

To prove this theory, run the following program TestBoolSerialize.java . The output file Bool.tmp and Byte.tmp will be the same size, but Short.tmp will be double the size. You may need to run 1 section a time if you run out your memory.

Don't need to worry too much about internal representation is one beautiful thing of Java. The programmer don't need to actively allocate/return memory like in c/c++. Don't you remember the pain of using sizeof() in c/c++, because of the pointer arithmetic, etc? There is no sizeof() in Java. My above program TestBoolSerialize.java actually does the trick of sizeof() to reveal the secret of Java for you.
7. What is type cast, can you give some simple example?
A: *** type cast ***
Cast the type of a variabe from one type to another, of course, it must be legal in Java/C++ etc. Examples follow:
long l = 300L;
int i = (int)l; // cast a long to an int

class A {}
class B extends A {}

// will compile and run fine
A a = new B();
B b = (B)a; // cast A reference a to a B reference b
// runtime fine since a is actually a B

// will compile fine and ClassCastException will be thrown on runtime
A a = new A();
B b = (B)a; // cast A reference a to a B reference b
// runtime exception will be thrown since a is not really a B
8. How to cast between objects? How about interfaces?
A:
Upper cast from subclass to supercalss, no need to cast, since the ISA relationship. OakTree is a Tree.
Down cast from superclass to subclass, an explicit cast is needed to avoid compile time error. If you cast Tree to OakTree, it would possibly be right, but not necessarily, since this particular Tree actually might be an AppleTree. In that case, a ClassCastException will be thrown out at the run time
If you cast between siblings or even irrelevant classes, a compile time error results, since compiler has the type information of them. for example, if you cast a OakTree to an AppleTree, or even a Furniture, compile will error out.
However, there is a catch, if you cast to an interface, even they are irrelevant, and compiler might let you go without an error.
9. Why this code compiles OK, but throw ClassCastException at runtime?
Base b=new Base();
Sub s=new Sub(); //Sub extends Base
s=(Sub)b;
A:
"Oversea Chinese is a Chinese", but not vise versa.
"Chinese is not necessary an oversea Chinese, but possible."

When you cast super to sub, compiler assume that you know what you were doing, since it is possible. However, runtime will find out b actually is not a Sub.

Since Cat is an Animal, but Animal is not necessary a Cat, but it is possible a Cat.

That is why downcast is allowed on compile time, since compiler assumes you know what you are doing. However, Runtime will find out this Animal is actually not a Cat.

ClassCastException! Big time.
10. What are the differences between char and byte? Why text file can be read back as byte streams?
A:
Everything in computer are represented by 0's and 1's, every eight 0's and 1's can form a byte, that is why everything can be read in as byte streams.
byte is the smallest memory unit addressable.
How to interpret those bytes is the job of operation system, software, etc.
For Java primitive types, char is 16 bits unsigned integer, byte is 8 bits signed integer, short is 16 bits signed integer.
The difference between char and short is the interpretation of the first bit.
11. A case study, why 3 is printed out?
class Test {
public static void main(String[] args) {
Test t = new Test();
t.test(1.0, 2L, 3);
}
void test(double a, double b, short c) {
System.out.println("1");
}
void test(float a, byte b, byte c) {
System.out.println("2");
}
void test(double a, double b, double c) {
System.out.println("3");
}
void test(int a, long b, int c) {
System.out.println("4");
}
void test(long a, long b, long c) {
System.out.println("5");
}
void test(float a, long b, int c) {
System.out.println("6");
}
}

// output: 3
// think why?
A:
Remember the following will help:
3 (integer type) is always default to int in Java.
1.0 (floating point number) is is always default to double in Java.
Explanation correct or wrong:
Wrong! Since 3 is int, int to short needs explicit cast.
Wrong! Since all three parameters are wrong.
Correct! Since numeric promotions are performed on 2nd/3rd parameters.
Wrong! Since 1.0 is double, double to int needs explicit cast.
Wrong! Since double to long needs explicit cast.
Wrong! Since double to float needs explicit cast.
Why hashCode must be the same for two objects equal to each other?A:
This is a complicated question. Let us discuss it slowly.
You must read the javadoc here first. Otherwise, we have no common ground. It is excellent reading too!
HashTable or HashMap are fundamental data structure in computer science. The lookup speed is close to O(1), since we use hashCode to put (store) and look-up (retrieve) elements. See more detailed explanation on HashTable here !
Equal objects must have the same hashCode! It is a must, not a choice. Otherwise, HashTable or HashMap will not work correctly!
Different/unequal objects have different hashCodes or not, which has everything to do with the efficiency of HashTable/HashMap etc. It is a trade-off between time and space. Less collision will make look-up faster (saving time), but will use more memory (wasting space).
The hashCode generation/look-up algorithm usually considers the sparcity of the hashTable to make the decision. However, since memory is so cheap now, people no longer pay too much attention to the algorithm any more, UNTIL you have an OutOfMemoryError, of course.
Since Java made all of these behind the scene, it becomes more obscure to developers. Good or Bad??? I think the answer is BOTH! The good side is making coding easier, the bad side is some programmers don't understand them any more. In real programming life, you might need to code them yourself for efficiency or your application special needs.
2. How to use clone()method, why my code throws CloneNotSupportedException?
A: Make your class implements Cloneable interface, and override the Object.clone() method.If you don't override the Object.clone() method, the code will be compilable, but throws CloneNotSupportedException. Why, see the following code copied from JDK Object.java.
protected native Object clone() throws CloneNotSupportedException;
3. What does clone()
method do?
A:The key concept you need to understand is the default implementation of clone() is a shallow clone(). The primitive type is cloned, for example, the hashCode() (type long) of the original and the clone will have the same value. If you change the clone's primitive type field value, the original will stay the same as before.

But the reference type just clones the same object's reference. Therefore when you make a change in the data member object, the original and the clone will be both changed.

I learned this the hard way. Then I had to write my deepClone() method to do my job.
4.Can we cast an Object to cloneable?
A: Yes or No
It will compile, since compiler does not check interface casting. However, it will throw java.lang.ClassCastException at runtime. Try the following example. See more type cast example here TestCast.java
class T {
public static void main(String[] args) {
Object o = new Object();

// compile ok, throw java.lang.ClassCastException at runtime
Cloneable c = (Cloneable)o;

// not even compilable
// Object o2 = c.clone();
}
}
. 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:
Explicitly call super(String) in Sub constructor
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()
. Is it a must for a abstract class to have a abstract method?
A: No!
All methods defined in interfaces are abstract.
All classes which have abstract method(s) must be declared abstract, but not vice versa.
2. What is modifier for the default constructor implicitly generated by Java compiler?
A: The default constructor implicitly generated by Java compiler should have the same accessibility as the class. i.e. public class will have a public default constructor, package "friendly" class will have package "friendly" constructor, unless you explicitly define it otherwise.See Package usage example for details.
3. Can one object access a private variable of another object of the same class?
A: Yes! One object can access a private variable of another object of the same class. The private field can be accessed from static method of the class through an instance of the same class too.Here is an example:
public class Test1 {
private int i;
Test1(int ii) {
i = ii;
System.out.println("Self: " + i);
// to avoid infinite recursion
if (i != 3) {
Test1 other = new Test1(3);
other.i++;
System.out.println("Other: " + other.i);
}
}

public static void main(String[] args) {
Test1 t = new Test1(5);

// The private field can be accessed from
// static method of the same class
// through an instance of the same class
System.out.println(t.i);
}
}
4. Several questions about static:
a) Can a static variable be declared within a method?
b) Can a static method contain an inner class?
c) Can a static method contain an static inner class?
A:
a) No, not in Java, but yes in C++
b) Yes
c) No
The simplest way to have your doubts clarified is to write a short program, then compile it to see the result. CODE, Code, code, ... please! An example here:
class Test {
void method() {
//static int i = 3; // not compilable
}
static void smethod() {
//static int i = 3; // not compilable
class local {
}
/* not compilable
static class slocal {
}
*/
}
}
5. Why the following code not compilable? Do we need to initial final variable explicitly?
public class Test{
static int sn;
int n;
final static int fsn;
final int fn;
}
A:
The above code is not compilable since final variable fsn and fn are not initialized.Yes, final variable (variables), static or instance, must be initialized explicitly. It can be done by an initializer, static or instance respectively. final instance variables can also be initialized by every constructor.Three choices to make the code right:
public class Test{
static int sn;
int n;
final static int fsn = 3;
final int fn = 6;
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}
{fn =8;}
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}

Test(){
fn =8;
}
Test(int pn){
fn =pn;
}
}
6. Can we declare an object as final? I think I still can change the value of a final object.
A:
final variables cannot be changed.
final methods cannot be overridden.
final classes cannot be inherited. However, there is something easily to be confused. There is no final Object in Java. You cannot even declare an Object in Java, only Object references. We only can have final object reference, which cannot be changed. It is like that the address of your house cannot be changed if it is declared as final. However, you can remodel your house, add a room, etc. Your house is not final, but the reference to your house is final. That is a little confusing. By the way, use finals as much as possible, but do not overuse them of course. It is because compiler knows they are not going to change, the byte code generated for them will be much more efficient.
7. Can we use transient and static to modify the same variable? Does it make any difference in Object serialization?
A: Yes, we can use transient and static to modify the same variable. It Does not make any difference in Object serialization. Since both transient and static variables are not serializable.See your exausting example at TestSerialization.java
8. What happens if we don't declare a constructor as public? Is it a useful strategy somewhere?
A: Following discussion is based on the assumption of that your class is declared as public and at least has some public members, and the other package imports your class or using full-qualified names to use your class.
You cannot construct an instance of the class by using this constructor in another package.
If you have other constructors declared public, you still can construct an instance of the class by using other public constructors in another package.
If all your constructors are not public, then the class cannot be constructed in packages other than the package it was defined.
If the other package gets a reference to it, its public members still can be used. Singleton Design Pattern is a good example for it. We even use private construtor intentionally.
9. In a non-static inner class, static final variables are allowed, but not static variables! why?
A: When a variable is static final, actually, it is not a variable; it is a constant. Compiler will treat it differently.
10. Can final and transient be used together? Why?
A: Yes, they can.
final variables cannot be changed.
final methods cannot be overridden.
final classes cannot be inherited. transient variables cannot be serialized. They are independent of each other. A variable can be final or a constant (an oxymoron, right? ), and transient or not serializable. I actually figured out a good reason not to serialize final variables.Serializing objects are mostly for transferring data. The both side of transferring will know the Class object, know the constants in most of the cases, with the exception of initialized finals in constructors by using the parameter value. Not Serializing the final will certainly save transferring time. Using final and transient together will certainly have some advantages in distributed computing. And, please remember, putting final and transient together is an option, not a requirement.
11. Why null variable can access static member variables or methods?
A: When you call a static data member or method, all it matters is right type. See example here
// ST.java
class ST {
static int n = 3;
static int getInt() {
return n + 35;
}

public static void main(String[] args) {
ST st = null; // st has the type of ST

System.out.println(st.n); // 3
System.out.println(st.getInt());// 38

// the above lines are equivalent to the followings
System.out.println(ST.n); // 3
System.out.println(ST.getInt());// 38
}
}
12. Should we hide private method defined in the superclass by defining the same name and signature method in the subclass?
A: No.
If super class defined a private method, it hides itself; nobody else can see it or use it. That is exactly what private means. It does not need a subclass to define a same name and signature method to be hided!!!If the subclass use the same name and signature to define another method, it does not hide anything, it is just itself and totally irrelevant with the super class same name method. In addition, it should be only considered a bad-coding style, even it is legal.Please read everything about hiding here!
a section in JLS2
13. Why I got IllegalAccessException when I try to use reflection or dynamic proxy to access some package level methods from another package?
A: Why not?
Do you think what you get is the reasonable behavior of Java? OR Do you assume Proxy or reflection should break the rule of Java, and open a backdoor to a class, and let it do something, which it is not supposed to do?
1.What is the difference between String s = "hello"; and String s = new String("hello"); ?
A:Read Sun's explanation here:
2. Why String and StringBuffer works differently, discrimination?
// Test.java
public class Test {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("hello");
System.out.println("String: s1.equals(s2) = " + s1.equals(s2));
System.out.println("StringBuffer: sb1.equals(sb2) = " + sb1.equals(sb2));
}
}

// output
/*
String: s1.equals(s2) = true
StringBuffer: sb1.equals(sb2) = false
*/
A:
Since String class overrides the equals() method of Object class, and StringBuffer does not.
Read here: equals method and check the JDK doc for String and StringBuffer too.
3. How does Java String concatenation, or the overloaded + between different types, work?
A: Go to your JDK1.2.2/JDK1.3 directory, find src.jar, unjar it. Then you can see all source code of JDK.Goto src\java\lang, to find StringBuffer.java and String.java. Search for append in the beginning comments of StringBuffer.java, then follow the lead, you will find out all the secrets you are interested in. "If you give me a fish, You feed me for the day.
If you teach me how to fish, you feed me for life."
4. Why are outputs of these two statements so different?
System.out.println(6 + 4 + " = sum"); // 10 = sum
System.out.println("sum = " + 6 + 4); // sum = 64
A:
Java evaluates the expression inside println(expr) first, then convert it to a String.
When Java evaluates the expression, it follows the left-to-right rule.
"+" operator is overloaded in a very intuitive way just as in most other languages.
In 6 + 4 + " = sum": from left to right, evaluates 6 + 4 first, two integer adds, 10 resulted. Then 10 + " = sum", int plus a String, String concatenation assumed, converts 10 to a string, then ...
In "sum = " + 6 + 4: from left to right, "sum = " + 6, String plus an int, String concatenation assumed, converts 6 to a String, concatenates them together, become "sum = 6". Then repeats the same process with "sum = 6" + 4. You know the answer.
String concatenation process actually is finished by a class StringBuffer. If you want to know the details, read the source code of jdk: StringBuffer.java. It is highly recommended for you to do that.
Methods Overloading and Overriding
5. What is the basic difference between the concept of method overloading and overriding?
A: They are totally irrelevant except the name similarities in two senses.
sense #1: English words overriding and overloading both have "over" inside
sense #2:overloading methods will have the "same name" but different signature. overriding methods will have the "same name" and same signature.
Except these above, there is nothing in common between them. Please read some more from the following QAs.
6. Can overloaded methods in derived class hide the same name methods (with different signature) in base class?
A: When methods are defined with the same name, but different signature, they are just name overloading, nothing can hide anything else. It is irrelevant it is in a derived class or not.
American people drive on the right side.
You are right on this topic.
He will be right back.
English word right is overloaded here, we understand the difference by the context. Compiler understands the method overloading by the signature, which serves the same purpose as context, but more reliable, since compiler is not as intelligent as you are. If derived class (subclass) defines a non-private method with the same name and same signature as the non-private method defined in base class, then it is method overriding, polymorphism comes into play. Late binding/Runtime binding will happen.Never mix these two words overriding and overloading, please.
7.Can overloaded methods be override too? Static binding or dynamic binding?
A: Yes, of course! In compiler point of view, overloaded methods are totally different methods. Because compiler identifies methods by their name and signature, you know overloaded methods must have different signatures.

Derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future. It is compiler's responsibility to check the caller class has the method being called. It is the runtime's responsibility to call the right method along the hierarchy from bottom-up according to the real Object type identified.
8. What are the differences between overloading and overriding? Are they both concepts of polymorphism?
A: No, overloading is NOT a concept of polymorphism.
Let me try a short one about overloading. The approach is like you take the test, cross out something obviously not correct, before you decide what is correct. 3 + 5
3.0 + 5.0
The plus (+) operator is overloaded long before even OO concepts came into play in computer sciences. It is in Fortran (the first high level computer language) for sure.
American drives on the right. British drives on the left.
Maha Anna is right on this topic.
I'll be right back.
These are right angle triangles.
You have the right to disagree with me.
He is a right extremist.
Actually, you can even overload the English word right to mean a dog in certain communication circle. Just thinking a scenario, you name your dog as Right, then in your family, when you or your kids talk about Right, the most of the time, it is referring to the dog. And it is a valid overloading; no body will put you in jail or even criticize you for your use of English word right this way...
...
The English word right is overloaded here. All natural languages are overloaded long before computer even invented. Polymorphism is a very specific OO concept, which has nothing to do with overloading. You really need to read a good OO book to understand it. It is too large a job for me to write about it here. There is so much misunderstanding out there on this topic, a lot of them are in published books. Like Marcus said: "Don't believe everything you read." If you don't believe what you read here by Roseanne, I'm OK.
P.S. The word Polymorphism itself in natural languages can be overloaded too like the Right example in English. You can overload the word polymorphism with whatever meaning you want it to mean. However, I still agree with most computer scientists' narrow and precise definition of polymorphism. If you don't agree with me, no more arguments are needed; we all can rest in peace...
9. When ambiguity exists between method calls, how does compiler resolve it? Why String version of the method is called instead of the Object version in the following example?
// Overloading.java
public class Overloading {

public void method(Object o) {
System.out.println("Object Version");
}

// String is an Object, but a specific Object
public void method(String s) {
System.out.println("String Version");
}

public static void main(String args[]) {
Overloading test = new Overloading();

// null is ambiguous to both methods
// The more specific one is called
test.method(null); // String Version
}
}
A:
The answer is in the comments of above code; just remember that when ambiguity exists between method calls, compiler resolves it by choosing the more specific ones. If it does not work, it will error out.

Why String is more specific than Object?

This is a Basic OO concept about generalization/specialization, read here for more specific information. Here is a brief:

OakTree is a specific Tree.
Cat is a specific Animal.
String is a specific Object.
Subclass ISA specific Baseclass.
10. Can overloaded methods have the same signature but different return type?
A: No, absolutely not!
In any programming languages, Methods overloading only applies to methods with different signatures. If same signature, there is only one method, two return types is impossible for one method. Try 5-10 line of code in Java or C++, you get your answer.Read here from JLS 8.4.7 Overloading

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures.

However, If we have two overloaded methods (which means they have the same name, but different signatures), they can have same/different return types, and/or throw same/different exceptions.
11. Can static method be overridden?
A: No!
The concept of overriding is binding at runtime, or polymorphism. Static is just on the opposite side of the equation, binding at the compile time, polymorphism does not apply to static method.

Methods a Subclass Cannot Override A subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). If you attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program:"
... "Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass. " Quotation from Overriding Methods of The Java Tutorial

See more interesting discussion and sample code here: Can subclass override methods that are declared static in the superclass?
12. Can constructor be overridden?
A: No!
No, constructor cannot be overridden. Constructor must have the same name of the class itself, can never be its ancestor's name. For constructor calling orders, read here: What is the calling order of constructors along the hierarchy, from child up, or from ancestor down?
13. Can you explain the result of the following example? Oh, my!
class Base {
public boolean foo(Base b) {
return true;
}
}
class Sub extends Base {
public boolean foo(Sub s) {
return false;
}
}

public class Test {
public static void main(String argv[]) {
Base bb = new Base();
Base bs = new Sub();
Sub ss = new Sub();

System.out.println(bb.foo(bb)); //true

System.out.println(bs.foo(bs)); //true ???
System.out.println(bs.foo(ss)); //true ???
System.out.println(bs.foo(bb)); //true ???
System.out.println(ss.foo(bs)); //true ???
System.out.println(ss.foo(bb)); //true ???

System.out.println(ss.foo(ss)); //false
}
}
A: The foo methods are overloaded in the Sub. In Base, there is only one foo method, and it is not overridden by the Sub!
Overloading is fundamentally different then overriding. There is no polymorphism or dynamic binding here!!! All decisions are made at compile time!!! See detailed explanation in the same code below, documented!
class Base {
// There is only one foo method in Base!!!
public boolean foo(Base b) {
return true;
}
}
class Sub extends Base {
// differnt signature, method overloading
// there are 2 foo methods in the Sub
public boolean foo(Sub s) {
return false;
}
}

public class Test {
public static void main(String argv[]) {
// bb is a Base ref to the compiler, Base obj at runtime
Base bb = new Base();
// bs is a Base ref to the compiler, Sub obj at runtime
Base bs = new Sub();
// ss is a Sub ref to the compiler, Sub obj at runtime
Sub ss = new Sub();

// All these 4 lines are Base ref
// call Base.foo(Base) method, and only one foo available
// bs is a Base ref, and ss ISA Base ref too
// Everything is fine!!!
System.out.println(bb.foo(bb)); //true
System.out.println(bs.foo(bs)); //true
System.out.println(bs.foo(ss)); //true
System.out.println(bs.foo(bb)); //true

// bb, bs are both Base refs to Compiler
// ss is a Sub ref
// call Sub.foo(Base) which is inherited from Base
System.out.println(ss.foo(bs)); //true
System.out.println(ss.foo(bb)); //true

// no doubt about this one, am I right?
System.out.println(ss.foo(ss)); //false
}
}
Are Java and C++ using the same rules on method overriding/overloading?
14. Are Java and C++ using the same rules on method overriding/overloading?
A: Yes, they are basically the same.
Here are two equivalent class A/B in Java and C++. Compare carefully!
A.java
public class A {
public int mtdA(int x) {
return x + 3;
}
public int mtdB(int x, int y) {
return x + y;
}
}

class B extends A {
/*
$ javac A.java
A.java:23: mtdA(int) in B cannot override mtdA(int) in A;
attempting to use incompatible return type

found : double
required: int
public double mtdA(int x) {
^
1 error

public double mtdA(int x) {
return x + 0.2;
}
*/

// Compiled OK
public double mtdB(int x) {
return x + 0.2;
}
}
A.cpp
class A {
virtual int mtdA(int x) {
return x + 3;
};
virtual int mtdB(int x, int y) {
return x + y;
};
};

class B : public A {
// $ g++ A.cpp
// A.cpp:15: error: conflicting return type specified for `virtual double B::mtdA(int)'
// A.cpp:2: error: overriding `virtual int A::mtdA(int)'
/*
virtual double mtdA(int x) {
return x + 0.2;
};
*/


// OK
virtual double mtdB(int x) {
return x + 0.2;
};
};
. What is abstraction, what is encapsulation? What is the difference?
A: pine tree, apple tree, oak tree....
Abstraction: Tree
They are all trees.
Another way to express the same concepts is generalization and specialization.Capacitor, resister, wire, box, CRT, ...
Encapsulation: television
You don't care what are inside the black box, and how they interact with each other, as long as the television works.
Another way to express the same concepts is information hiding.
2. Why we need to construct a Vector first, then we can call addElement method?
A:
Since addElement(Object) is an instance method of class Vector. If we don't construct a Vector instance first, we cannot call instance method. You may askWhy we define addElement(Object) as instance method?
The answer should be obvious. You might use different Vectors in different parts of your application. Each Vector might add very different Objects. Define addElement as static (class) method does not make any sense.Give you a simple analog, you build a home, which is an instance of Home class, then add a TV to your living room. The addTV() method must be called after you construct your home, in other words, an instance method. Do you want you TV to be a class static variable and used by all home owners. No, you don't, and it is also impossible in reality too.
3. When an instance of subclass is created, is an instance of base class created also? How many objects are created during the process?
A:
Truth: FordCar ISA or "is a" Car.Think:
Which one is generalization/specialization? (Answer: Car is generalization)
Which one should be the base/sub class? (Answer: Car should be the base class)Fact: A FordCar was just made.Questions:
true/false? A Car was just made. (Answer: true)
How many objects (Cars) were created during this process? (Answer: one)
~~~~~~~~~~~~~~~~~~~~~There is only one object, but it contains all of the variables for the entire hierarchy. The reason being that the execution of a constructor causes calls to the constructors all the way back up the hierarchy to java.lang.Object - as each constructor executes, it gets the memory and sets the variables as required for that class.Where I can learn more about this topic?Reading some good Java / C++ / OO books, pay attention to the inheritance (or generalization/specialization) part. This is a big and extremely important topic. Yes, it is more important than learning Java. "Nothing can replace the technique of reading a good book from front to back." Here is an excellent free book:
Bruce Eckel's Thinking in Java, 2nd Edition
4. When we should use static methods, when we should use instance methods? Which one is better?
A: This should depend on what problem you need to solve. If the method is a long complicated scientific calculation, static method is the right way to do it. It makes the method available and easy to be used everywhere. That is exactly what Java Math class does. Go there, and see it.If the method is an individual behavior, such as putOnMakeUp() , it is very cultural/personal dependent. Putting it as static method would be almost meaningless. Of course, you can make a static putOnMakeUp() work fine if you are willing to pass 15 parameters to it, or pass a large struct including all cultural/personal information needed. Ah, we drive our time machine and go back to that magnificent procedural/structural paradigm era...
. Which one of the methods defined in interface or class with the same name will be called?
A: There is no method in interface can be called. Only the actual implementation of that method in class, which implements the interface mentioned, can be called.
2. Can subclass override methods that are declared static in the superclass?
A: No!
Methods a Subclass Cannot Override A subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). If you attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program:"
... "Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass. " Quotation from Overriding Methods of The Java Tutorial
When you should use this kind of "hide" technique?
Don't use it unless your boss gives you the assignment!!! Then you have no choice. Something legal does not mean it is recommended.
Copied from Sun's Code Conventions for the JavaTM Programming Language
Quote:
Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:
An interesting example here:
class Base {
static void doThis() {
System.out.println("Base static doThis()");
}

void doThat() {
System.out.println("Base instance doThat()");
}
}

class Sub extends Base {
// This is static method defined in the Sub class
// which does not override the Base doThis()
// only hide it.
// proved in the Test.main()
static void doThis() {
System.out.println("Sub static doThis()");
}

// This is instance method defined in the Sub class
// which does override the Base doThat()
void doThat() {
System.out.println("Sub instance doThat()");
}
}

public class Test {
public static void main(String[] args) {
// base is an instance of Sub
Base base = new Sub();
// legal cast both at compile and run time
Sub sub = (Sub)base;

base.doThis(); //Base static doThis()
base.doThat(); //Sub instance doThat()

sub.doThis(); //Sub static doThis()
sub.doThat(); //Sub instance doThat()

//Think why, try to understand the following concepts
//static binding : bind at compile time
//Dynamic binding : bind at run time
}
}
3. If subclass overrides the methods in super class, can subclass call the super class method?
A: Yes, you can. However, that is the subclass it self's choice. Outsider does not have this choice. You can see it clearly from the following example.
class Sup
{
void m1()
{
System.out.println("m1 in super");
}
}

class Sub extends Sup{
void m1()
{
super.m1();
System.out.println("m1 in sub");
}
}

public class T{
public static void main(String arg[])
{
new Sub().m1();
}
}
4. What is hide(a variable or a static method) means in computer languages (such as Java)? Should we do that?
A: Hide basic is a scope issue, when we have the same name in a smaller/more local scope, the smaller scope one will hide the upper ones. Here is a real life example: If you call your daughter Oprah Winfrey, then in your home, or in your daughter's kindergarten, people talk about Oprah Winfrey will refer to your daughter. The popular talk show host Oprah Winfrey will be hidden, unless you refer her as talk show host Oprah Winfrey. This example tells you three things: 1) Hiding is a scope issue. 2) Hiding cannot be complete/absolute. 3) Hiding is not good practice, since it causes confusion.My suggestion is don't call your daughter Oprah Winfrey, or don't practice hiding in your Java or C# or ... programming.The followings are two Java programs to illustrate the hiding concepts.
// hiding a instanse variable
class A {
int i = 3;
void method1() {
// this i will hide the member i
// bad coding practice
int i =5;
System.out.println(i); //5

// however, it can still be accessed by using this.i
System.out.println(this.i); //3
}
}

// hiding a static method
class A {
static void method1() {
System.out.println("in class A's static method1");
}
}

class B extends A {
// this will hide the static method1 in class A
static void method1() {
System.out.println("in class B's static method1");
}

public static void main(String[] args) {
// since we are in class B's scope
// call method1 directory will refer to B's method1,
// A's method1 is hidden
method1(); //in class B's static method1

// However, we still can call A's method1 even in B's territory
A.method1(); //in class A's static method1
}
}
5. Why the call to xy.amethod() calls amethod() in X instead of amethod() in Y in the following code?
class X {
public static void jout(String s) {
System.out.println(s);
}
static void amethod() {
jout("In X, amethod()");
}
}
class Y extends X {
static void amethod() {
jout("In Y, amethod()");
}
}
class Z extends Y {
static void amethod() {
jout("In Z. amethod()");
}
}
public class Test
public static void main (String[] args) {
X xy = new Y();
X xz = new Z();
Y yz = new Z();

xy.amethod();
xz.amethod();
yz.amethod();
}
}
A:
All three amethod()s here are static methods. static method is Class method, which has nothing to do with your object instantiation, dynamic binding, or polymorphism, whatsoever. In other words, the 3 line of codexy.amethod();
xz.amethod();
yz.amethod();can be replaced by the following 3 lines without causing any changes:X.amethod();
X.amethod();
Y.amethod();Since compiler interprets them exactly like this. xy and xz are reference type of X. yz is reference type of Y.Just remember "static is not dynamic" probably will help some.
6. When base class calls a method, how could the run time knows to called the overridden method in the derived class? The object is not even constructed yet.
A: Why? From the language theory, it is called deferred binding or dynamic binding or binding at run time. Compiler leaves the decision to run time. To make the decision at run time, you don't need the object built first. The only thing you need to know is the type of the actual object. In Java, the Class (not class) objects are loaded to the memory when it is first used. The run time knows it before any instance is constructed. In C++, the class methods virtual table is there for the same purpose. As you probably know, in C++, method are default to static binding, only virtual methods are dynamically bound. In Java, methods are default to dynamic binding, unless they are declared as static, private, or final.
7. Does private method defined in base class participate polymorphism, if the derived class has a same name method?
A: No, private method defined in any class will never participate polymorphism.
If you want to confuse yourself, your boss, and your co-worker (and you might get fired for that too), and define same name private methods along the hierarchy, the compiler will treat them individually, as no relationship at all. If you call private method in your class, the method will be bound at compile time (not runtime).See the following example:
// Base.java
public class Base {
public static void main(String[] args) {
Sub sub = new Sub();
System.out.println(sub.g()); // 20, not -100
}

private int f() {
return 20;
}

protected int g() {
// statc bound with Base.f()
// compiler does not know any derived class has f() or not
// and does not care either
return f();
}
}

class Sub extends Base {
// f() here has nothing to do with Base.f()!!!
// In real world programming, never do this!!!
public int f() {
return -100;
}
}
8. What kind of Java methods does not participate polymorphism?
A: Polymorphism for Java method is always there except the following three situations: 1) The method is declared as final
2) The method is declared as private
3) The method is declared as static In those three cases, static binding will be performed by the compiler. Compiler does not have the knowledge, nor care about the method was, is, or will be overridden by none, one, or many subclass(es). The decision is made by the runtime, which is called dynamic binding. See next question, which discuss the same topic in a different angle.
9. What methods in Java is static bound? Please compare with c++ too.
A: static, private, final methods are static bound.
Those 3 methods does not participate polymorphism. In other words, they are not allowed to be overridden. In c++, virtual function can be overridden, others not.
virtual in C++ --> nothing in Java
nothing in C++ --> final in Java
10. Do we need an object reference to call a static method?
A: No, not quite. See the following example.
MyClass t = null;
// the following two are equivalent
t.aStaticMethod();//OK
MyClass .aStaticMethod();//perfect
It is the class type; it doesn't need a "reference variable ". You can use a object reference to call a static method, of course, provided it has the right type. However, you don't have to. The above example clearly said that. t is not referring to anything but null, but has a MyClass type. If you know the old procedural programming, static method is equivalent to that, except in Java, we have a class Class. In Java, we can write magnificent old procedural program without any OO concepts by using all static methods. (No object reference at all).
11. What is the calling order of constructors along the hierarchy, from child up, or from ancestor down?
A:The order is from child up. However, the super() is always implicitly or explicitly called as the first statement before any code in the child being executed. This might cause some confusion here. If you put a print statement in each of the constructor, the ancestor one will be output first. The following code will illustrate how it works.This is called LIFO, which one is called the first, will be finished the last. The child is called first, but it call its parent as the first statement, and the immediate parent will call its parent as the first statement too, and so on. Therefore the far ancestor, which is the Object will finish its constructor the first, then its immediate child, and so on. That is why the print statements will finish from the ancestor down. The calling stack is working this way. Last In, First Out (LIFO)
public class Child extends Parent {
public Child() {
// super() is implicitly called here
System.out.println("Child");
}
public static void main(String[] args) {
new Child();
}
}
class Parent extends GrantParent{
public Parent() {
// super is explicitly called here
super("Mother's parent");
System.out.println("Parent");
}
}
class GrantParent{
public GrantParent(String sWhosPrt) {
System.out.println("GrantParent: " + sWhosPrt);
}
}

// output
// GrantParent: Mother's parent
// Parent
// Child
12.What is the static, instance initialization, constructor header, and code execution order? Why the radius prints out as 0 instead of 1 in the following code?
//Ex from Bruce Eckel's Book "Thinking In Java"
abstract class Glyph {
abstract void draw();
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println(
"RoundGlyph.RoundGlyph(), radius = " + radius);
}
void draw() {
System.out.println("RoundGlyph.draw(), radius = " + radius);
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
//Output is:
//Glyph() before draw()
//RoundGlyph.draw(), radius = 0
//Glyph() after draw()
//RoundGlyph.RoundGlyph(), radius=5
A:
The execution order is:
static variable initialization and static block executes only once when the class is loaded to the memory by JVM.
When constructor is called, the constructor header executes first before instance variable initialization and instance block execution.
instance variable initialization and instance block execute.
Code in the constructor executes.
This is exactly what happened in your example (except no static stuff). The RoundGlyph constructor header executes first, which implicitly called default constructor of Glyph super(). The radius has not initialized yet; the value is 0. Then the radius is initialized to 1. Then the code in the RoundGlyph() constructor executes and changed radius value to 5. This kind of hair splitting trick, we'd better not know it, or don't tell your boss you know it. I probably learned from Mughal and Rasmussen's book, which I gave away after the test. Today, I wrote a little code to prove that I remembered it right. I usually do not pay a lot of attention to what is going to be on the SCJP test like Marcus Green does, however, it is quite safe to say, questions like this will NOT be on your test.Warning: Don't try this at work!
13. Constructor or not constructor? Please explain why the output of the following code is null?
public class My {
String s;
public void My(){
s = "Constructor";
}
public void go() {
System.out.println(s);
}
public static void main(String args[]) {
My m = new My();
m.go();
}
}
//output : null
A:
public void My() is not a constructor. The default constructor is called. s is still null by default.Constructor is not supposed to have a return type, even a void type. If it has, then it is not a constructor, but a method, which happens to have the same name as the class name. This is a tricky question just for testing your Java knowledge. Using class name as your method name is not considered as good code practice at work!
14. Base b = new SubBase(); How the compiler/Runtime to resolve the addresses of methods calls, Fields?
// TestBinding.java
class Base {
String s = "string in Base";
void init(){
System.out.println("init() call in Base");

}
}
class SubBase extends Base{
String s = "string in SubBase";
void init(){
System.out.println("init() call in SubBase");

}
}

public class TestBinding {
public static void main(String[] args) {
Base b = new SubBase();

// static binding on instance fields
System.out.println(b.s); //string in Base

// dynamic binding on instance methods
b.init(); //init() call in SubBase
}
}
A:
The above example plus comments actually told everything you need to know.When a field of an object is accessed using a reference, it is the type of the reference declared, which determines, which variable will actually be accessed.
Static Binding -- Bind at compile time: The addressing of the field is determined at compile time.

When a method is invoked on an object using a reference, it is the class of the current object denoted by the reference, not the type of the reference that determines which method implementation will be executed.
Dynamic Binding -- Bind at run time: The addressing of the method is determined at run time.Notice to C++ programmer: In C++, only virtual methods (functions) are bound at run time. In Java, methods are default to dynamic binding, unless they are declared as static, private, or final.
15. If I remove the init() from the Base in the above question, I got a compile error: ""method init() not found class Base". Why?
A: It will make you understand dynamic binding or polymorphism much better. If you remove init() from Base class, you actually take init() out of the polymorphism between Base and SubBase class. Compiler only know b is refer to a Base class, which does not have the method init(), compile time error!!! The Java compiler does not know, nor care who, when, where, how some other class is going to extends the Base class, there are some different named methods defined in them. And one of them happens to be called init(). They are totally irrelevant to the Base class.Remember SubBase ISA Base. Compiler does not care which child/grandchild/grand grandchild down the hierarchy b is actually referring to, and which init() it should call. However, they all have an init() (polymorphism). It is a runtime decision. Dynamic Binding.Dynamic binding, or binding at runtime only for those methods defined in Base class, either inherited or overridden by the subclass. The override can be already happened now or will happen in the future, the compiler does not care.
16. Here is another tricky code example for you to cracking on! Cover up the explanation to see you can explain it or not.
class Base {
int x = 3;
public Base (){}
public void showx(){
System.out.println("In base, x = " + x);
}
}
class SubBase extends Base {
int x = 2;
public void showx() {
System.out.println("In SubBase, x = " + x);
}
}

public class BindingTest {

public static void main (String args[]){
Base b = new SubBase();
b.showx();
System.out.println("In Main, the (?) x = " + b.x);
}
}

// output
/*
In SubBase, x = 2
In Main, the (?) x = 3
*/
A: Danger: Do not try this at work!
1) In main(), b.x is bound at compile time, since b is declared as Base, x is 3.
2) In main(), b.showx() is bound at runtime, since b is actually a SubBase. the SubBase.showx() will be called.
3) In SubBase, call of x in method showx() is bound at the compile time, in class SubBase, x is 2. This is a typical tricky question, good for you cracking the concepts, but never write it on your job. You would be fired for that, no kidding!!!
Why cannot we synchronized public object to lock the memory for avoiding multi-thread access?
A:synchronized has nothing to do with locking memory, but controlling access to a block of code, which may access and change the memory/database/file contents, the integrity of which might be compromized by multi-thread simultaneous access or changes. Here, I intentionally missed how synchronized works, uses what kind of working mechanism. Read other part of the FAQ for that, please. public/private/protected access modifiers have no relationship with synchronized, even they share a word "access". They are for encapsulation, in other words, information sharing or hiding. Like your family, you may want certain information to be public, some to be known only by your relatives or close friends, some to be kept only to your family members. Some might be kept to yourself only, hoho, a secret. They are different concepts and serve different purposes.
2. I found this statement about thread in some tutorial on Internet, Is it true?
The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.
A: Absolutely wrong!
The correct one:
JVM creates one user thread for running a program. This thread is called main thread. The main method of the class is called from the main thread. It dies when the main method ends. If other user threads have been spawned from the main thread, program keeps running even if main thread dies. Basically a program runs until all the user threads (non-daemon threads) are dead.This is actually most GUI (Swing) application works. The main thread creates a thread for the GUI frame work; then it finishes and becomes dead. The GUI will still running until the user closes it or something else kills it. Microsoft GUI application basically works the same way.
A simple sample code (even not GUI) here!
class T extends Thread {
boolean runflag = true;
public T(String name){
super(name);
}
public void run() {
int i = 0;
while (runflag) {
System.out.println(getName() + ": " + i++);
try
{
sleep((int)(700*Math.random()));
}
catch (InterruptedException e) {
}
}
System.out.println(getName() + " is stopping.");
}

void setRunFlagFalse() {
runflag = false;
}

public static void main(String args[]) {
T t1=new T("t1");
T t2=new T("t2");
T t3=new T("t3");

t1.setDaemon(true);
t1.start();

t2.start();
t3.start();
try
{
// let three threads run
Thread.sleep(600);
}
catch (InterruptedException e) {
}

// t2 will stop
t2.setRunFlagFalse();

System.out.println("t3 will not stop after main stop");
System.out.println("t1 will stop after all user threads stopped");
System.out.println("Use ^C to stop everything, when you had enough");
System.out.println("main thread is stopping.");
}
}
3. What is the basic concept of synchronized keyword, is it responsible to our data integrity?
A: The key concept of synchronized keyword is locking the code to prevent other thread to access the critical code when one thread is processing it. You need acquire the monitor/lock from an object to lock it, and one object only has one lock/monitor. That is why when one thread acquired the lock/monitor, other threads have to wait. Why you need to lock the code? Mostly you need to keep the integrity of your data, and which is very application specific. The locking mechanism actually knows nothing about it. It is NOT responsible for your data integrity at all. It is you, the application programmer, who is responsible for it. For example, if you want to keep the integrity of your client's bank account balance, you must synchronize all methods, which have access to and can change the balance. If you leave a loophole there, you probably will be fired by your boss, not Dr. Gosling or someone else who designed the locking mechanism. I just want to scare you... However, when you are synchronizing the code, which has access to the client's account balance, you probably still can change his/her email address or list of hobbies for advertisement purposes. Of course, if you are really serious on that stuff too, you might want to synchronize the code, which has access those data independently.Programmers need to practice some examples to really understand it. Some times, I still get confused. Concurrent programming is not an easy subject. It is not Java specific either. Race condition, dead lock, critical section, semaphore, monitor, thread scheduling, thread pooling, etc. etc...I'm still in the learning process... How about we learn together.
4. Why we should call Thread.start() to start a Thread? I called the run() method, no error or exception at all, why?
A: When you call Thread start() method, JVM will create a new Thread, then call run() method of the new Thread. The new Thread will run concurrently with the original calling Thread.If you directly call the run() method, the Thread will act as a normal Java object. No new Thread will be created. The code will run sequentially. Try the following code to see the difference, and get a feeling of concurrency.
// MyRun.java
public class MyRun implements Runnable {
public static void main(String argv[]) {
MyRun r = new MyRun();
Thread t = new Thread(r);

// t is still running after Main finished
t.start();

// No new thread created, Main finishes after run() returns
// t.run();

try {
// See concurrency if you call t.start()
// See sequential if you call t.run()
for (int i = 0; i < 5; i++) {
Thread.sleep(10);
System.out.println("in Main: " + i);
}
}
catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Main thread finished...");
}
public void run(){
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(20);
System.out.println("in Run: " + i);
}
}
catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Run method finished...");
}
}
5.Thread t = null; t.yield(), is this legal? If it is, what is the effect of the statement?
A: Yes, but it is bad coding style. It is equivalent to Thread.yield(), which will cause the current thread to yield, and becomes ready state. The purpose of yield() is let other Thread has a chance to execute.Since yield() is a static method of Thread class, the only concern to compile is the type, that is why t.yield(); and Thread.yield(); are exact the same. However, it is confusing human beings. It is bad, but legal practice. It is good for you to really understand what is static method.
6. In some mocking exam, after the definition of Thread t = new Thread(); then both yield(); and t.yield(); are marked as alternative answers for causing the current running thread to pause. Is it generally correct?
A: No! It is generally incorrect. In some special situation, it will compile and work, however, it should still be considered as bad coding practice. The special case is: when yield(); is called inside a Thread class ( in a main, or other method ).You should use Thread.yield() instead to accomplish the task. For more discussion, read the question above.The following example shows you the general case, if you call yield(); it will not compile.
// ThreadTest.java
import java.io.*;
class MyThread extends Thread {
public void run(){
for (int i=0; i<5; i++){
System.out.println(getName() + ": i = " + i);
}
}
}

public class ThreadTest {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
t.yield();
// Not compible this line
// since ThreadTest is not a Thread
//yield();
}
}
7. What are the differences between notify() and notifyAll()? Do they release the object lock?
A: notify() does NOT relinquish the lock - it just lets the JVM know that it will be possible to wake up a Thread that called wait() when the current Thread exits the synchronized code. If you have more than one Thread wait() on an object, notify only wakes up one of them - you can't predict which one. notifyAll() tells the JVM that all Threads waiting will be eligible to run. The JVM will pick one - probably by looking at the priorities.
8. When Thread.sleep() is called inside a synchronized method or block, does the Thread release the object lock?
A: No, Thread definitely does not release the lock before it goes to sleep, if it is in a synchronized method or block. That is why we should use wait(), notify(), notifyAll() defined in Object in synchronized method or block. Do not sleep() there unless you want the program totally stop, please! Write some code, you will see it easyly. Or read JDK Doc here: http://java.sun.com/j2se/1.3/docs/api/java/lang/Thread.html#sleep(long) Here is a example, sleepInsteadOfWaitNotify() method causes t2 and t3 totally starved to death.
public class SleepTest implements Runnable{

public void run() {
while (true){
sleepInsteadOfWaitNotify();
}
}

synchronized void sleepInsteadOfWaitNotify() {
while (true) {
System.out.println(Thread.currentThread().getName() + "Go to sleep");
try{
Thread.sleep(400);
}
catch (Exception e){
System.out.println(e);
}
System.out.println(Thread.currentThread().getName() + "wake up");
}

}

public static void main (String[] args){
SleepTest t = new SleepTest();

Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);

t1.setName("t1");
t2.setName("t2");
t3.setName("t3");

t1.setDaemon(true);
t2.setDaemon(true);
t3.setDaemon(true);

t1.start();
t2.start();
t3.start();

try {
// let daemon threads run
Thread.sleep(10000);
}
catch (InterruptedException e) {
}
System.out.println("If user thread is dead, all daemon threads die. ");
}
}
9. In what situation, an IllegalThreadStateException will be thrown?
A:1) If the thread was already started, you call start() again.
2) If this thread is active, you call setDaemon().
3) A deprecated method countStackFrames() also throws IllegalThreadStateException.
10. What will be affected by assign a name to a thread using setName("YourThreadName")?
A:
Quote from JDK documentation:
Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
Nothing changes by assigning your Thread a name. It only gives you the convenience of debug, since it has a name you know.
11. What is Thread.interrupt()supposed to do?
A:
interrupt is supposed to end the sleep or wait state of a Thread prematurely by causing an InterruptedException.
12.What is Daemon Threads?
A: A daemon thread opposites to a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads. You threads are default to user thread unless you explicitly use method setDaemon(boolean on) to set it as daemon thread. Note: You cannot call setDaemon() after Thread has started, otherwise, an IllegalThreadStateException (RuntimeException) will be thrown. Make sure you read the JDK documentation of Thread and ThreadGroup . Javadoc is your best teacher to tell you almost anything and everything about Java Threads.See sample code at ThreadTest.java
13. Why Thread methods stop(), resume(), suspend() deprecated? How can we stop a thread without call stop()?
A: Why? Read here Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?
How? See the following example:
public class T extends Thread {
boolean runflag = true;
public T(String name){
super(name);
}
public void run() {
int i = 0;
while (runflag) {
System.out.println(getName() + ": " + i++);
try
{
sleep((int)(400*Math.random()));
}
catch (InterruptedException e) {
}
}
System.out.println(getName() + " is stopping.");
}

public void setRunFlagFalse() {
runflag = false;
}

public static void main(String args[]) {
T t1=new T("t1");
T t2=new T("t2");
T t3=new T("t3");
t1.start();
t2.start();
t3.start();
try
{
// let three threads run
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
// stop them
t1.setRunFlagFalse();
t2.setRunFlagFalse();
t3.setRunFlagFalse();
}
}
15. Can I use Thread.interrupt() to kill a thread? Is it a good idea?
A: Yes, you can. As long as your handle the InterruptedException tricky enough in your Thread.run() method, you can use interrupt() to kill a thread.However, it is absolutely a bad idea to do this. Thread.interrupt() is a general purposed method to interrupt or stop whatever a thread is doing now, such as sleep, wait, or living. If you used a general purpose method to mean killing a thread, you create a side effect, and invite unaware programmers to make mistake since they only read Sun's Thread javadoc.Stop is general; stop life is special. General includes special, but general does not imply special. If it does, it is a side effect. If stop sign on the street does also imply stop life, that would be really bad!!!Never do this kind of stunt, please! Please follow KISS rule in your code, Keep It Simple and Stupid, or Keep It Simple and Straight forward. Do your boss and current/future coworkers a favor please!
There is one exception, if you're the boss, you can do and ask your employees do whatever you want. If they do not follow your order, fire them!
If you want read more discussion about and opposite side of my opinion, read here !
16. What does the Thread.join() method do? Can you give an example?
A: The current running thread currT call another thread jobthread.join(), then wait until the jobthread to die.
For example, the current running thread, which spawns the jobthread to do something (do a long calculation, load several images, call somebody through satilite, etc. etc.). The jobthread has been coded to do its job and then terminate or die, in other words, the jobthread.run() method ends. The current thread will rely on jobthread's completion to continue its own work. The effect of calling jobthread.join() statement is that currT waits for jobthread to complete
public class JoinDemo {
public static void main(String[] args) {
Job job = new Job();
Thread jobthread = new Thread(job);

jobthread.start();
try {
// the current thread will wait until the job done
jobthread.join();
}
catch(Exception e){
}
System.out.println("Job done");
// do something else
}
}
class Job implements Runnable {
public void run(){
int i;
for (i=1; i<=200; i++ ){
if (i % 10 != 0) {
System.out.print(i + ", ");
}
else {
System.out.println(i);
}
}
}
}
17. Is class wide lock and instance lock independent of each other?
A: Yes. Why?
Every Java Object has one lock, and only one lock. If you want enter synchronized code, you have to acquire the lock first. When you enter the static synchronized code, you need to acquire the lock on the Class object.
When you enter the synchronized instance code, you need to acquire the lock on the instance object.
However, they are different objects with different locks, and independent of each other.When you call a synchronized static method you get a lock on NONE OF the instances of the class, except the Class object itself. Please pay attention to the difference between class and Class. Run the following code, it will tell you the whole story.
class MyObj {
String sName;

public MyObj(String name) {
sName = name;
}

// The Class Object of MyObj will be locked
// However, staticMethod() and instanceMethod() are independent of each other
public static synchronized void staticMethod(String sThreadName) {
try {
System.out.println(sThreadName + ": staticMethod start lock");
Thread.sleep((long)(Math.random() * 2000 + 1));
System.out.println(sThreadName + ": staticMethod finish lock");
}
catch (InterruptedException e) {
}
}

// The instance Object MyObj of will be locked
// However, staticMethod() and instanceMethod() are independent of each other
public synchronized void instanceMethod(String sThreadName){
try {
System.out.println(sThreadName + ": " + sName + ": instanceMethod start lock");
wait((long)(Math.random() * 2000 + 1));
System.out.println(sThreadName + ": " + sName + ": instanceMethod finish lock");
notifyAll();
}
catch (InterruptedException e) {
}
}
}

public class Test extends Thread{
String sTrdName;

// 2 objs for testing lock
static MyObj o1 = new MyObj("myobj1");
static MyObj o2 = new MyObj("myobj2");

public Test(String name){
super();
sTrdName = name;
}

public void run() {
while (true){
// Lock the Class object of MyObj
MyObj.staticMethod(sTrdName);

// Lock the instances object of MyObj
o1.instanceMethod(sTrdName);
o2.instanceMethod(sTrdName);
}
}

public static void main (String[] args){
Test t1 = new Test("t1");
Test t2 = new Test("t2");

t1.setDaemon(true);
t2.setDaemon(true);

t1.start();
t2.start();

try {
//let Daemon thread run
Thread.sleep(7000);
}
catch (InterruptedException e) {
}
System.out.println("If user thread is dead, all daemon threads die. ");
}
}

// Output of the program clearly tell you the story
/*
t1: staticMethod start lock
t1: staticMethod finish lock
t2: staticMethod start lock
t1: myobj1: instanceMethod start lock
t1: myobj1: instanceMethod finish lock
t1: myobj2: instanceMethod start lock
t2: staticMethod finish lock
t2: myobj1: instanceMethod start lock
t2: myobj1: instanceMethod finish lock
t2: myobj2: instanceMethod start lock
t1: myobj2: instanceMethod finish lock
t2: myobj2: instanceMethod finish lock
t2: staticMethod start lock
t2: staticMethod finish lock
t2: myobj1: instanceMethod start lock
t1: staticMethod start lock
t1: staticMethod finish lock
t1: myobj1: instanceMethod start lock
t2: myobj1: instanceMethod finish lock
t2: myobj2: instanceMethod start lock
t1: myobj1: instanceMethod finish lock
t1: myobj2: instanceMethod start lock
t2: myobj2: instanceMethod finish lock
t2: staticMethod start lock
t1: myobj2: instanceMethod finish lock
If user thread is dead, all daemon threads die.
*/
18. How to call wait(), notify(), notifyAll() in synchronized static methods?
A: Direct calling those methods will not compile since those are instance methods inherited from Object. When you call wait(), you are actually calling this.wait(), this does not exist in static methods.

How can we solve the problem? There are two ways to do it.
Call wait(), notify(), notifyAll() methods of your Class object, by using MyClass.class.wait(). synchronized static methods locks the Class, you release lock of the same object.
Instantiate a static Object dummy in your class, you can use synchronized block, which locks dummy, in your static method. Then you can call dummy.wait(), dummy.notify(), ... in those blocks.
This is better when you have more than one set of static methods, which needs locked independently, you can use more than one dummy objects for that purposes.

If your problem is something like that a Queue problem where add and remove are static methods working on static array. Lock the array object!!! See sample code snippet below.
static Object[] ary = new Object[50];
static void method1() {
System.out.println("do something not need to lock the ary...");
synchronized(ary){
System.out.println("do something on ary Object..");
try{
ary.wait();
}
catch(InterruptedException e) {
}
System.out.println("do something else on ary Object..");
}
System.out.println("do something else not need to lock the ary...");
}
19. What is race condition?
A:
Quote from The Java Tutorial:
Race conditions arise from multiple, asynchronously executing threads try to access a single object at the same time and getting the wrong result.
An excellent explanation of race condition here! Not Java specific!!!

20. What is Thread Deadlock? How to avoid it?
A: A deadlock occurs when one object is waiting for another to release a lock, and that object is also waiting. A circular dependency occurs, and then the waiting thread will wait forever, or deadlocked.The key to prevent deadlock: Do not hold a lock while waiting another resource that also requires locking.Read from Sun's tutorial:

Play with the famous Dining Philosopher Problem (not invented by Java!) Applet and learn the important concepts when you have fun.
21. What is Thread Starvation? How to avoid it?
A: For any reason, one or more threads never get a chance to run, or be blocked for a long time if not forever.Many reasons can cause Thread starvation:
Threads are deadlocked.
Thread is blocked by I/O, the I/O never become available again.
Other threads with higher priority run selfishly, never give other thread a chance to run.
Synchronized methods/blocks forget to release the lock/monitor. In Java, wrongfully using sleep/yield instead of wait/notify/notifyAll has a very good chance to cause deadlock/starvation.
Your Thread scheduling system does not working correctly.
...
How to avoid/correct them? Find out what causes your thread starvation, and correct them.
22. When a Thread die? Can a dead Thread be restarted?
A: No. a dead Thread cannot be restarted.
If you call its start() method after its death, IllegalThreadStateException will be thrown.
Even the Thread is dead, but you still can call its other method. Why? Simple, the Thread is just another Java Object. For example, if you call its run() method again, it will be just a sequential procedure call, no concurrent execution at all.
The exit() method of class Runtime has been called and the security manager has permitted the exit operation to take place.
Non daemon threads die, either by returning from call of the run() method or by throwing an exception that propagates beyond the run() method.
Daemon Threads die when all user Threads died.
23. When will a Thread I/O blocked?
A: When a thread executes a read() call on an InputStream, if no byte is available. The calling Thread blocks, in other words, stops executing until a byte is available or the Thread is interrupted.
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:


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?
new InputStreamReader(new FileInputStream("data"));
new InputStreamReader(new FileReader("data"));
new InputStreamReader(new BufferedReader("data"));
new InputStreamReader("data");
new InputStreamReader(System.in);
A:
The leagal constructors for InputStreamReader are
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String enc)
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?
try {
new InputStreamReader(new FileInputStream("data"));
}
catch (java.io.FileNotFoundException fnfe) {
}
Answer: If they let you choose one, choose e. If they let you choose two, choose a and e.
Error #1: FileReader is not an InputStream.
Error #2: The same problems as a), Exception java.io.FileNotFoundException must be caught
Error #1: BufferedReader is not an InputStream. Error #2: There is no contructor of BufferedReader to take string as argument.
String "data" is not an InputStream.
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
System.exit(1);
Uncaught Exception being thrown at the top level.
You may add more...
JVM is killed externally, by
User use ctrl C or other system commands to kill it on windows, unix, or ...
System power off.
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
1. What is Java?
A:
Java is a beautiful island in Indonesia. See here: Java, Indonesia
Java is another name for coffee, since coffee produced in Java, Indonesia is good!
Java is also a programming language was invented by Sun's programmers when they drank too much coffee. The language was called Oak, but it had a trademark conflict, then they renamed it as Java. See here: Sun's official history
2. Is Java a pure OO language?
A: No, it is not.
neither are C++/C#/etc. SmallTalk is general considered as a pure OO language. In SmallTalk, everything is an object, including int or even + sign. Java is one step more close to SmallTalk than C++, but it is still not pure OO language. Why bother to discuss this? Language is just a tool to get the job done. Choose one is better for your job/business. If speed is absolutely critical to your application, use FORTRAN, c or assembly. Burn your algorithm into the semiconductor chips would be a good choice too, of course, if it is necessary! In some cases, OO is an obstacle. SmallTalk never becomes a main stream programming language since it is too slow.
3. In what order should we get certified, Programmer, Developer, and Architect?
A:
Passing programmer's test will get you an interview, since others will consider you know Java at least as a walking Java compiler, maybe more, like Tony.

Passing developer's test will prove that you can code in Java, if you are not programming Java on your job yet. That is second to the real world job experience (psuedo-real-world, I like the word!). If you don't have any real coding experience in Java, or do not have any programming experience even in other languages, skip the developer's exam, and go ahead to do the Architect test? I'll consider that is crazy!!!

If you are already coding in Java, go ahead to prepare for the architect exam. That may be a reasonable choice. However, SCEA is not trivial either (3 parts test). SCJP is not a prerequisite of SCEA.

Why a lot of people skipped the developer exam to go SCJA (the old one), since the old one was just like SCJP, multi-choices only. If you did enough mocking exams, it was relatively easy to pass. There was another factor that almost everyone got the same test. Enough leaking made it even easier.

That might be one of the reasons why Sun changed the test to SCEA.

We have SCJD Study Group . If you pass the SCJP, you are welcome to join us!
4.. What software or books I should buy to prepare the test?
A:
My suggestion, don't buy any exam software. They don't help much IMHO.

But at least by one book, Bill Brogden's Exam Prep or Exam Cram will be my first choice. (Bill did not pay me anything, BTW. Get Bruise Eckle's free book, "Thinking In Java". If you can afford it, buy it. He did not pay me either. Learn how to use Sun's "The Java Tutorial" on Line, please! I saw so many questions asked here, which could be answered more precisely by a simple search of the free book from Sun .

Do free mocking exams or not free ones, when you get something wrong, read, code, test back and forth until you thoroughly understand. You are not only preparing yourself for the test, but also for your future interview and job. Read, Code, code, code, and test until the Java concepts become yours.

Post a question somewhere to get answer from others when you really get stuck!

Free Java Books
5. What to do when we see something ambiguous on the real test? A:
If you think something on the test is ambiguous, mark the question; make the best guess you can, finish the rest of the test. If you have time, go back to that question. It may not be ambiguous anymore, and then choose the correct answer. Otherwise, keep your figure crossed!

Do remember MARK any question in doubt. I lost some points since I did not mark, then could not find that question to which I gave wrong answer any more.

But, who cares now?
6. What do I need watch out for filling blank questions?
A:
Read questions very carefully; don't jump into conclusions. ONLY write exactly what is asked for - no extra punctuation such as quotes. Some questions will give a list of words you can pick from.

Don't add legs when you drawing a snake!
7. Where can I get all the Sun's test information?
A:
General:
SCJP:
SCJD:
SCJEA: