When this kind of question has been asked, find the problems you think is necessary to ask before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x
145
What is the difference between Swing and AWT components?
AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.
146
Why does Java not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C# shine.
147
Parsers? DOM vs SAX parser
Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.
148
What is a platform?
A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris, and MacOS.
149
What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components:
149.1 The Java Virtual Machine (Java VM)
149.2 The Java Application Programming Interface (Java API)
150
What is the Java Virtual Machine?
The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.
It is used to explain the java class codes and run in the OS.
151
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
152
What is the package?
The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.
153
What is native code?
The native code is code that after you compile it, the compiled code runs on a specific hardware platform.
154
Is Java code slower than native code?
Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.
155
What is the serialization?
The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.
156
How to make a class or a bean serializable?
By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.
157
How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.
158
How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().
159
What is the difference between Serializable and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.
160
What is a transient variable?
A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.
161
Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default layout.
162
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.
163
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 causes dirty data and leads to significant errors.
164
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.
165
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
166
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.
167
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.
168
What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
169
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.
170
Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
171
What is thread?
171A thread is an independent path of execution in a system.
172
What is multithreading?
Multithreading means various threads that run in a system.
173
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.
174
How to create multithread in a program?
You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread.
175
Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.
176
Can each Java object keep track of all the threads that want to exclusively access to it?
Yes, the methods in Object wait and notify are used to access the synchronized objects.
177
What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
178
What invokes a thread's run() method?
After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
179
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 communicate each other.
180
What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
181
What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
182
What is the List interface?
The List interface provides support for ordered collections of objects.
183
What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
184
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.
185
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.
186
What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
187
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.
188
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.
189
Is sizeof a keyword?
The sizeof operator is not a keyword. It is a just operator.
190
What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
191
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.
192
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.
193
Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
194
What is a native method?
A native method is a method that is implemented in a language other than Java.
195
How can you write a loop indefinitely?
for(;;)--for loop; while(true)--always true, etc.
196
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.
197
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.
198
Which class is the superclass for every class?
Object.
199
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.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.
200
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
201
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
202
Which Container method is used to cause a container to be laid out and redisplayed?
invalidate();
203
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.
204
What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
205
What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
206
Which package has light weight components?
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
207
What are peerless components?
The peerless components are called light weight components.
208
What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.
209
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.
210
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.
211
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
212
What is the difference between throw and throws keywords?
The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the mehtod, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.
213
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 or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
214
What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
215
Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
216
Name primitive Java types.
The primitive types are byte, char, short, int, long, float, double, and boolean.
217
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.
218
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 The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region
219
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.
220
What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation (an interface of a method).
221
What is a static method?
A static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
222
What is a protected method?
A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.
223
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.
224
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.
225
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.
226
What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
227
What do heavy weight components mean?
Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.
228
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.
229
How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
230
How are the elements of a GridBagLayout organized?
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.
231
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 accommodate platform-specific differences among windowing systems.
232
What are the problems faced by Java programmers who don't 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.
233
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.
234
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.
235
What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.
236
What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
237
What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.
The overridden methods can decrease the visibility of the methods. The overridden methods can increase the thrown exceptions.
238
What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
239
Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
240
What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
241
How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
242
How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.
243
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.
244
What is the List interface?
The List interface provides support for ordered collections of objects.
245
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.
The method enableEvents() is in the Component class in AWT.
246
What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
247
What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
248
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.
249
What is the difference between a Scrollbar and a ScrollPane?
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.
250
What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
251
What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.
252
What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
253
Does the code in finally block get executed if there is an exception and a return statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.
254
How you restrict a user to cut and paste from the html page?
Using javaScript to lock keyboard keys. It is one of solutions.
255
Is Java a super set of JavaScript?
No. They are completely different. Some syntax may be similar.
256
What is a Container in a GUI?
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.
257
How the object oriented approach helps us keep complexity of software development under control?
We can discuss such issue from the following aspects (Encapsulation, Inheritance and Porlymorphysm),
257.1 Objects allow procedures to be encapsulated with their data to reduce potential interference.
257.2 Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.
257.3 The well-defined separations of interface and implementation allows constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.
258
What is polymorphism?
Polymorphism allows methods to be written that needn't be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of yet unconceived classes.
259
What is design by contract?
The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions.
In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.
260
What are use cases?
A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust.
261
What is the difference between interface and abstract class?
261.1 interface contains methods that must be abstract; abstract class may contain concrete methods.
261.2 interface contains variables that must be static and final; abstract class may contain non-final and final variables.
261.3 members in an interface are public by default, abstract class may contain non-public members.
261.4 interface is used to "implements"; whereas abstract class is used to "extends".
261.5 interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.
261.6 interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.
261.7 interface is absolutely abstract; abstract class can be invoked if a main() exists.
261.8 interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
261.9 If given a choice, use interface instead of abstract class.
262
What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.
263
Why do u use Session Tracking in HttpServlet?
In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application.
264
What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.
Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not.
In url rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.
265
What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
265.1 Persisting the session into database
265.2 Storing the session in-memory on multiple servers.
266
How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true);
267
How you can destroy the session in Servlet?
You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();
268
It is said that the code in a finally clause will never fail to execute, Is there any example where it fails to execute?
Here is the example code where the finally clause code will not execute.
public class testFinally{ public static void main(String[] args){ System.out.println("Executing the program"); try { System.out.println("In the try block"); System.exit(1); } finally { System.out.println("In the finally."); } } } |
269
Why there are no global variables in Java?
Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
269.1 The global variables breaks the referential transparency
269.2 Global variables creates collisions in namespace.
270
What platforms is the Java-technology software available on?
Sun provides ports of the Java 2 Platform for Windows 95, Windows 98, Windows NT, Windows 2000, Solaris-SPARC, Solaris-Intel, and Linux.
271
Where can I download latest version of Java?
Latest version of JDK can be downloaded from Sun web site http://www.java.sun.com.
272
Do I need to know C++ to learn Java?
No, you don't need to know C or C++ to learn Java. Java is much simpler that C++.
273
What is the difference between Java and Java Script?
In Java and Java Script only the "Java" word is common. Java is programming language from Sun. JavaScript is a programming language from Netscape, which runs in their browsers.
274
Differentiate between applet and application.
Java applications runs as stand-alone application whereas applet runs in web browser. Application is a Java class that has a main() method. Applet class extends java.applet.Applet class.
275
How to convert String to Number in java program?
The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String strId = "10";
int id=Integer.valueOf(strId);
276
What is interface?
In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}
277
How you can force the garbage collection?
Garbage collection automatic process and can't be forced.
278
What is the use of Object and Class Classes?
The Object class is the superclass of all other classes and it is highest-level class in the Java class hierarchy. Instances of the class Class represent classes and interfaces in a running Java application. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
279
What do you understand by a variable?
The variables plays very important role in computer programming. Variables enable programmers to write flexible programs. It is a memory location that has been named so that it can be easily be referred in the program. The variable is used to hold the data and it can be changed changed during the course of the execution of the program.
280
What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
281
What do you understand by casting in java language?
The process of converting one datatype to another in Java language is called Casting.
282
What are the types of casting?
There are two types of casting in Java, these are Implicit casting and explicit casting.
283
What is Implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not workout for all application scenarios.
Example:
int i = 4000;
long h = i; //Implicit casting
284
What is explicit casting?
Explicit casting in the process in which the complier are specifically informed to about transforming the object.
long ln = 700.20;
t = (int) ln; //Explicit casting
285
What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy
286
What do you understand by final value?
FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived
287
What is a Servlet?
Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun's write once run anywhere technology java servlets provide excellent framework for server side processing.
288
What are the types of Servlet?
There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality linke doGet and doPost methods.
289
What are the differences between HttpServlet and Generic Servlets?
HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
init and destroy, to manage resources that are held for the life of the servlet
getServletInfo, which the servlet uses to provide information about itself
There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there's almost no reason to override the doOptions and doTrace methods.
290
Differentiate between Servlet and Applet.
Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser. Applets have GUI interface but there is not GUI interface in case of Servlets.
291
Differentiate between doGet and doPost method?
doGet is used when there are requirement of sending data appended to a query string in the URL. The doGet models the GET method of Http and it is used to retrieve the info on the client from some server as a request to it. The doGet cannot be used to send too much info appended as a query stream. GET puts the form values into the URL string. GET is limited to about 256 characters (usually a browser limitation) and creates really ugly URLs.
POST allows you to have extremely dense forms and pass that to the server without clutter or limitation in size. e.g. you obviously can't send a file from the client to the server via GET. POST has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure. For real security you have to look into encryption which is an entirely different topic
292
What are methods of HttpServlet?
The methods of HttpServlet class are :
292.1 doGet() is used to handle the GET, conditional GET, and HEAD requests
292.2 doPost() is used to handle POST requests
292.3 doPut() is used to handle PUT requests
292.4 doDelete() is used to handle DELETE requests
292.5 doOptions() is used to handle the OPTIONS requests and
292.6 doTrace() is used to handle the TRACE requests
293
What are the advantages of Servlets over CGI programs?
Java Servlets have a number of advantages over CGI and other API's. They are:
293.1
Platform Independence
Java Servlets are 100% pure Java, so it is platform independence. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets.
293.2
Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place very first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. This intuitive method of servlets could be use to develop high speed data driven web sites.
293.3
Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.
293.4
Safety
Java provides a very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.
293.5
Secure
Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.
294
What are the lifecycle methods of Servlet?
The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps.
294.1
If an instance of the servlet does not exist, the web container
294.1.1
Loads the servlet class.
294.1.2
Creates an instance of the servlet class.
294.1.3
Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.
294.2
The container invokes the service method, passing request and response objects.
294.3
To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.
295
What are the type of protocols supported by HttpServlet?
It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
296
What are the directory Structure of Web Application?
Web component follows the standard directory structure defined in the J2EE specification.
Java Source
Web Content
----jsp, html, css, images
----WEB-INF
------------web.xml
------------lib
------------classes
297
What is ServletContext?
ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)
298
What is meant by Pre-initialization of Servlet?
When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives the request it loads the servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In case of Pre-initialization, the servlet is loaded when context is loaded. You can specify 1
in between the tag.
299
What mechanisms are used by a Servlet Container to maintain session information?
Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.
300
What do you understand by servlet mapping?
Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.
301
What must be implemented by all Servlets?
The Servlet Interface must be implemented by all servlets.
302
What are the uses of Servlets?
302.1 Servlets are used to process the client request.
302.2 A Servlet can handle multiple requests concurrently and be used to develop high performance system
302.3 A Servlet can be used to load balance among several servers, as Servlet can easily forward request.
303
What are the objects that are received when a servlets accepts call from client?
The objects are ServletRequest and ServletResponse . The ServeltRequest encapsulates the communication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client.
304
What are design patterns?
A pattern is a proven (and recurring) solution to a problem in a context. Each pattern describes a problem which occurs over and over again in our environment, and describes its solution to this problem in such a way that we can use this solution a lots of times. In simple words, there are a lot of common problems which a lot of developers have faced over time. These common problems ideally should have a common solution too. It is this solution when documented and used over and over becomes a design pattern.
305
Can we always apply the same solution to different problems at hand?
No. Design patterns would study the different problems at hand. To these problems then it would suggest different design patterns to be used. However, the type of code to be written in that design pattern is solely the discretion of the Project Manager who is handling that project.
306
What should be the level of detail/abstraction which should be provided by a design pattern?
Design patterns should present a higher abstraction level though it might include details of the solution. However, these details are lower abstractions and are called strategies. There may be more than one way to apply these strategies in implementing the patterns.
307
What are the most common problems which one faces during the application design phase that are solved by design patterns?
307.1 Identifying components, internal structures of the components, and relationships between components.
307.2 Determining component granularity and appropriate interactions
307.3 Defining component interfaces.
308
How does one decide which Design pattern to use in our application?
We need to follow these steps:
308.1 We need to understand the problem at hand. Break it down to finer grained problems. Each design pattern is meant to solve certain kinds of problems. This would narrow down our search for design patterns.
308.2 Read the problem statement again along with the solution which the design pattern will provide. This may instigate to change a few patterns that we are to use.
308.3 Now figure out the interrelations between different patterns. Also decide what all patterns will remain stable in the application and what all need to change (with respect to Change Requests received from the clients).
309
What is Refactoring?
Learning different design patterns is not sufficient to becoming a good designer. We have to understand these patterns and use them where they have more benefits. Using too many patterns (more than required) would be over-engineering and using less design patterns than required would be under-engineering. In both these scenarios we use refactoring. Refactoring is a change made to the internal structure of the software to make it easier to understand and cheaper to modify, without changing its observable behaviour.
310
What are Antipatterns?
Though the use of patterns fulfils our objectives in the applications; there are also several instances where several applications did not fulfill their goals. The architects of these applications too need to document these wrong decisions. This helps us in repeating these mistakes in our future applications. Such documented mistakes are called antipatterns.
Thus antipatterns are negative solutions which cause more problems than what they address. For ex. We might use entity beans which have fine-grained interfaces which can directly be accessed from the client side. This would result in considerable RMI and transaction management overhead. It results in poor performance and un-scalable applications.
311
As we do development in tiers, how do we divide patterns in tiers?
The Sun Java Center has classified the patterns in three tiers. These are:
Presentation tier patterns for web-component tier,
Business tier patterns for business logic (EJB) tier, and
Integration tier patterns for connection to the databases.
The presentation tier patterns are:
Intercepting filter, Front Controller, View Helper, Composite View, Service-to-Worker, and Dispatcher View.
The business tier patterns are:
Business delegate, Value Object, Session Façade, Composite Entity, Value Object Assembler, Value List Handler, and Service Locator.
Integration tier patterns are:
Data Access Object (DAO) and Service Activator.
312
What is Intercepting Filter pattern?
Provides a solution for pre-processing and post-processing a request. It allows us to declaratively apply filters for intercepting requests and responses. For ex. Servlet filters.
313
What is Front Controller pattern?
It manages and handles requests through a centralized code. This could either be through a servlet or a JSP (through a Java Bean). This Controller takes over the common processing which happens on the presentation tier. The front controller manages content retrieval, security, view management and retrieval.
314
What is View Helper pattern?
There generally are two parts to any application – the presentation and the business logics. The “View” is responsible for the output-view formatting whereas “Helper” component is responsible for the business logic. Helper components do content retrieval, validation and adaptation. Helper components generally use Business delegate pattern to access business classes.
315
What is Composite View pattern?
This pattern is used for creating aggregate presentations (views) from atomic sub-components. This architecture enables says piecing together of elementary view components which makes the presentation flexible by allowing personalization and customization.
316
What is Service to Worker pattern?
This is used in larger applications wherein one class is used to process the requests while the other is used to process the view part. This differentiation is done for maintainability.
317
What is Dispatcher View pattern?
This is similar to Service to Worker pattern except that it is used for smaller applications. In this one class is used for both request and view processing.
318
What is Business Delegate pattern?
This pattern is used to reduce the coupling between the presentation and business-logic tier. It provides a proxy to the façade from where one could call the business classes or DAO class. This pattern can be used with Service Locator pattern for improving performance.
319
What is Value Object (VO) pattern?
Value Object is a serializable object which would contain lot of atomic values. These are normal java classes which may have different constructors (to fill in the value of different data) and getter methods to get access to these data. VOs are used as a course grained call which gets lots of data in one go (this reduces remote overhead). The VO is made serializable for it to be transferred between different tiers within a single remote method invocation.
320
What is Session Façade pattern?
This pattern hides the complexity of business components and centralizes the workflow. It provides course-grained interfaces to the clients which reduces the remote method overhead. This pattern fits well with declarative transactions and security management.
321
What is Value Object Assembler pattern?
This pattern allows for composing a Value Object from different sources which could be EJBs, DAOs or Java objects.
322
What is Value List Handler pattern?
This pattern provides a sound solution for query execution and results processing.
323
What is Service Locator pattern?
It provides a solution for looking-up, creating and locating services and encapsulating their complexity. It provides a single point of control and it also improves performance.
324
What is Data Access Object pattern?
It provides a flexible and transparent access to the data, abstracts the data sources and hides the complexity of Data persistence layer. This pattern provides for loose coupling between business and data persistence layer.
325
What is EJB Command pattern?
Session Façade and EJB Command patterns are competitor patterns. It wraps business logic in command beans, decouples the client and business logic tier, and reduces the number of remote method invocations.
326
What is Version Number pattern?
This pattern is used for transaction and persistence and provides a solution for maintaining consistency and protects against concurrency. Every time a data is fetched from the database, it comes out with a version number which is saved in the database. Once any update is requested on the same row of the database, this version is checked. If the version is same, the update is allowed else not.
327
What all patterns are used to improve performance and scalability of the application?
VO, Session Façade, Business Delegate and Service Locator.
328
What design patterns could be used to manage security?
Single Access Point, Check point and Role patterns.
329
How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This is how the standard output could be re-directed:
Stream st = new FileOutputStream("output.txt"));
System.setErr(st);
//System.setOut(st);
330
Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
331
Explain the usage of the keyword transient?
This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
332
How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
333
What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.The sleep does not release the object lock while wait releases object lock.
334
Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
335
What's the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
336
Can you call one constructor from another if a class has multiple constructors?
Yes. Use this() syntax.
337
Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes
338
If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:/dev/com/xyz/hr/Employee.java. In this case, you'd need to add c:/dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:/>java com.xyz.hr.Employee
339
What order does JVM search the path for the classes?
339.1 CLASSPATH
339.2 –classpath in java command
339.3 . the current directory
When you use CLASSPATH and –classpath, you must set the . (current directory) manually. Or the . (current director) is not searched.
340
What's the difference between J2SDK 1.5 and J2SDK 5.0?
There's no difference, Sun Microsystems just re-branded this version.
341
What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.
342
Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
343
Can an inner class declared inside of a method access local variables of this method?
It's possible if these variables are final.
Because the instance of the inner class have longer life cycle than the method. In addition, the final variant is special one, which will be stored beyond the method. So final variant inside the method can be access in method inner class.
344
What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A single ampersand here would lead to a NullPointerException.
345
What's the main difference between a Vector and an ArrayList?
Java Vector class is internally synchronized and ArrayList is not.
346
When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
347
How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
348
What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
349
You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
350
What comes to mind when you hear about a young generation in Java?
Garbage collection.
351
What comes to mind when someone mentions a shallow copy in Java?
Object cloning.
352
If you're overriding the method equals() of an object, which other method you might also consider?
hashCode()
353
You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?
ArrayList
354
How would you make a copy of an entire Java object with its state?
Have this class implement Cloneable interface and call its method clone().
355
How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
356
How to use the weak object reference?
If there is no strong reference to one object, the object may be reclaim or may not be relaim. Then softReference.get() can be used to get the object again if the object is not claimed.
import java.awt.Graphics;
import java.awt.Image;
import java.applet.Applet;
import java.lang.ref.SoftReference;
public class DisplayImage extends Applet {
SoftReference sr = null;
public void init() {
System.out.println("Initializing");
}
public void paint(Graphics g) {
Image im = (
sr == null) ? null : (Image)(
sr.get());
if (im == null) {
System.out.println(
"Fetching image");
im = getImage(getCodeBase(),
"truck1.gif");
sr = new SoftReference(im);
}
System.out.println("Painting");
g.drawImage(im, 25, 25, this);
im = null;
/* Clear the strong reference to the image */
}
public void start() {
System.out.println("Starting");
}
public void stop() {
System.out.println("Stopping");
}
}
357
There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads, I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
358
What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level.