Você está na página 1de 66

30 Java Interview Questions

* Q1. How could Java classes direct program messages to the system console, but error messages, say to a file? A. The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed: Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st); * Q2. What's the difference between an interface and an abstract class? A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class. * Q3. Why would you use a synchronized block vs. synchronized method? A. Synchronized blocks place locks for shorter periods than synchronized methods. * Q4. Explain the usage of the keyword transient? A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers). * Q5. How can you force garbage collection? A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately. * Q6. How do you know if an explicit object casting is needed? A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example: Object a; Customer b; b = (Customer) a; When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

CIO, CTO & Developer Resources


* Q7. What's the difference between the methods sleep() and wait()

A. The code sleep(1000); puts thread aside for exactly one second. The codewait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread. * Q8. Can you write a Java class that could be used both as an applet as well as an application? A. Yes. Add a main() method to the applet. * Q9. What's the difference between constructors and other methods? A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times. * Q10. Can you call one constructor from another if a class has multiple constructors A. Yes. Use this() syntax. * Q11. Explain the usage of Java packages. A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes. * Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it? A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows: c:\>java com.xyz.hr.Employee * Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0? A.There's no difference, Sun Microsystems just re-branded this version. * Q14. What would you use to compare two String variables - the operator == or the method equals()? A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

* Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written? A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first. * Q16. Can an inner class declared inside of a method access local variables of this method? A. It's possible if these variables are final. * Q17. What can go wrong if you replace && with & in the following code: String a=null; if (a!=null && a.length()>10) {...} A. A single ampersand here would lead to a NullPointerException. * Q18. What's the main difference between a Vector and an ArrayList A. Java Vector class is internally synchronized and ArrayList is not. * Q19. When should the method invokeLater()be used? ( Not required) A. This method is used to ensure that Swing components are updated through the event-dispatching thread. * Q20. How can a subclass call a method or a constructor defined in a superclass? A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor

** Q21. What's the difference between a queue and a stack? A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule ** Q22. 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? A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option. ** Q23. What comes to mind when you hear about a young generation in Java? A. Garbage collection. ** Q24. What comes to mind when someone mentions a shallow copy in Java? A. Object cloning.

** Q25. If you're overriding the method equals() of an object, which other method you might also consider? A. hashCode()

CIO, CTO & Developer Resources


** Q26. 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? A. ArrayList ** Q27. How would you make a copy of an entire Java object with its state? A. Have this class implement Cloneable interface and call its method clone(). ** Q28. How can you minimize the need of garbage collection and make the memory use more effective? A. Use object pooling and weak object references. ** Q29. 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? A. If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface. ** Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it? A. You do not need to specify any access level, and Java will use a default package access level.

Q 34: Discuss the Java error handling mechanism? What is the difference between Runtime (unchecked) exceptions and checked exceptions? What is the implication of catching all the exceptions with the type Exception ? EH BP A 34: Errors: When a dynamic linking failure or some other hard failure in the virtual machine occurs, the virtual machine throws an Error. Typical Java programs should not catch Errors. In addition, it s unlikely that typical Java programs will ever throw Errors either.

Exceptions: Most programs throw and catch objects that derive from the Exception class. Exceptions indicate that a problem occurred but that the problem is not a serious JVM problem. An Exception class has many subclasses. These descendants indicate various types of exceptions that can occur. For example, NegativeArraySizeException indicates that a program attempted to create an array with a negative size. One exception subclass has special meaning in the Java language: RuntimeException. All the exceptions except RuntimeException are compiler checked exceptions. If a method is capable of throwing a checked exception it must declare it in its method header or handle it in a try/catch block. Failure to do so raises a compiler error. So checked exceptions can, at compile time, greatly reduce the occurence of unhandled exceptions surfacing at runtime in a given application at the expense of requiring large throws declarations and encouraging use of poorlyconstructed try/catch blocks. Checked exceptions are present in other languages like C++, C#, and Python. Throwable and its subclasses Object Exception Error Throwable IOException RuntimeException NullPointerException LinkageError Runtime Exceptions (unchecked exception)

A RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). An example of a runtime exception is NullPointerException. The cost of checking for the runtime exception often outweighs the benefit of catching it. Attempting to catch or specify all of them all the time would make your code unreadable and unmaintainable. The compiler allows runtime exceptions to go uncaught and unspecified. If you Java 35 like, you can catch these exceptions just like other exceptions. However, you do not have to declare it in your throws" clause or catch it in your catch clause. In addition, you can create your own RuntimeException subclasses and this approach is probably preferred at times because checked exceptions can complicate method signatures and can be difficult to follow. Exception handling best practices: BP Why is it not advisable to catch type Exception ? CO Exception handling in Java is polymorphic in nature. For example if you catch type Exception in your code then it can catch or throw its descendent types like IOException as well. So if you catch the type Exception before the type IOException then the type Exception block will catch the entire exceptions and type IOException block is never reached. In order to catch the type IOException and handle it differently to type Exception, IOException should be caught first (remember that you can t have a bigger basket above a smaller basket). The diagram below is an example for illustration only. In practice it is not recommended to catch type Exception . We should only catch specific subtypes of the Exception class. Having a bigger basket (ie Exception) will hide or cause problems. Since the RunTimeException is a subtype of Exception, catching the type

Exception will catch all the run time exceptions (like NullpointerException, ArrayIndexOut-OfBoundsException) as well. Catching Exceptions try{} catch(Exception ex){ //this block is reached { catch(IOException ioe) { //this block is never reached //There is a bigger basket //above me who will catch it //before I can. { try{} catch(IOException ioe){ { catch(Exception ex) { { Wrong approach Right approach basket basket basket basket Hint: as shown in the

figure, think of catching an exception in a basket. You should always have the smaller basket above the bigger one. Otherwise the bigger basket will catch all the exceptions and smaller baskets will not catch any. Why should you throw an exception early? CO The exception stack trace helps you pinpoint where an exeception occurred by showing us the exact sequence of method calls that lead to the exception. By throwing your exception early, the exception becomes more accurate and more specific. Avoid suppressing or ignoring exceptions. Also avoid using exceptions just to get a flow control. Instead of:

InputStream in = new FileInputStream(fileName); // assume this line throws an exception because filename == null.

Use the following code because you get a more accurate stack trace:

if(filename == null) { throw new IllegalArgumentException( file name is null ); { InputStream in = new FileInputStream(fileName);

Why should you catch a checked exception late in a catch {} block? You should not try to catch the exception before your program can handle it in an appropriate manner. The natural tendency when a compiler complains about a checked exception is to catch it so that the compiler stops reporting 36 Java errors. The best practice is to catch the exception at the appropriate layer (e.g an exception thrown at an integration layer can be caught at a presentation layer in a catch {} block), where your program can either meaningfully recover from the exception and continue to execute or log the exception only once in detail, so that user can identify the cause of the exception. Note: Due to heavy use of checked exceptions and minimal use of unchecked exceptions, there has been a hot debate in the Java community regarding true value of checked exceptions. Use checked exceptions when the client code can take some useful recovery action based on information in exception. Use unchecked exception when client code cannot do anything. For example, convert your SQLException into another checked exception if the client code can recover from it and convert your SQLexception into an unchecked (i.e. RuntimeException) exception, if the client code cannot do anything about it.

A note on key words for error handling: throw / throws used to pass an exception to the method that called it. try block of code will be tried but may cause an exception. catch declares the block of code, which handles the exception. finally block of code, which is always executed (except System.exit(0) call) no matter what program flow, occurs when dealing with an exception.

assert Evaluates a conditional expression to verify the programmer s assumption. Q 35: What is a user defined exception? EH A 35: User defined exceptions may be implemented by defining a new exception class by extending the Exception class. public class MyException extends Exception { /* class definition of constructors goes here */ public MyException() { super(); { public MyException (String errorMessage) { super (errorMessage); { { Throw and/or throws statement is used to signal the occurrence of an exception. Throw an exception: throw new MyException( I threw my own exception. ) To declare an exception: public myMethod() throws MyException { }

Let's say a Java class reads a file with the customer's data. What's going to happen if someone deletes this file? Will the program crash with that scary multi-line error message, or will it stay alive displaying a user friendly message like this one: "Dear friend, for some reason I could not read the file customer.txt. Please make sure that the file exists"? In many programming languages, error processing depends on the skills of a programmer. Java forces software developers to include error processing code, otherwise the programs will not even compile. Error processing in the Java is called exception handling. You have to place code that may produce errors in a so-called try/catch block:

try{ fileCustomer.read(); process(fileCustomer); } catch (IOException e){ System.out.println("Dear friend, I could not read the file customer.txt..."); } In case of an error, the method read() throws an exception. In this example the catch clause receives the instance of the class IOException that contains information about input/output errors that have occured. If the catch block exists for this type of error, the exception will be caught and the statements located in a catch block will be executed. The program will not terminate and this exception is considered to be taken care of. The print statement from the code above will be executed only in case of the file read error. Please note that method process() will not even be called if the read fails.

Reading the Stack Trace


If an unexpected exception occurs that's not handled in the code, the program may print multiple error messages on the screen. Theses messages will help you to trace all method calls that lead to this error. This printout is called a stack trace. If a program performs a number of nested method calls to reach the problematic line, a stack trace can help you trace the workflow of the program, and localize the error. Let's write a program that will intentionally divide by zero: class TestStackTrace{ TestStackTrace() { divideByZero(); } int divideByZero() { return 25/0; } static void main(String[]args) { new TestStackTrace(); } } Below is an output of the program - it traced what happened in the program stack before the error had occurred. Start reading it from the last line going up. It reads that the program was executing methods main(), init() (constructor), and divideByZero(). The line numbers 14, 4 and 9 (see below) indicate where in the program these methods were called. After that, the ArithmeticException had been thrown - the line number nine tried to divide by zero. c:\temp>java TestStackTrace Exception in thread "main"

java.lang.ArithmeticException: / by zero at TestStackTrace.divideByZero(TestStackTrace.java:9) at TestStackTrace.(TestStackTrace.java:4) at TestStackTrace.main(TestStackTrace.java:14)

Exception Hierarchy
All exceptions in Java are classes implicitely derived from the class Throwable which has immediate subclasses Error and Exception. Subclasses of the class Exception are called listed exceptions and have to be handled in your code. Subclasses of the class Error are fatal JVM errors and your program can't fix them. Programmers also can define their own exceptions. How you are supposed to know in advance if some Java method may throw a particular exception and the try/catch block should be used? Don't worry - if a method throws an exception and you did not put this method call in a try/catch block, the Java compiler will print an error message similar to this one: "Tax.java": unreported exception: java.io.IOException; must be caught or declared to be thrown at line 57

Try/Catch Block
There are five Java keywords that could be used for exceptions handling: try, catch, finally, throw, and throws.

CIO, CTO & Developer Resources


By placing a code in a try/catch block, a program says to a JVM: "Try to execute this line of code, and if something goes wrong, and this method throws exceptions, please catch them, so that I could report this situation to a user." One try block can have multiple catch blocks, if more than one problem occurs. For example, when a program tries to read a file, the file may not be there - FileNotFoundException, or it's there, but the code has reached the end of the file - EOFException, etc. public void getCustomers(){ try{ fileCustomers.read(); }catch(FileNotFoundException e){ System.out.println("Can not find file Customers"); }catch(EOFException e1){ System.out.println("Done with file read"); }catch(IOException e2){ System.out.println("Problem reading file " + e2.getMessage()); } } If multiple catch blocks are handling exceptions that have a subclass-superclass relationship (i.e. EOFException is a subclass of the IOException), you have to put the catch block for the subclass first as shown in the previous example. A lazy programmer would not bother with catching multiple exception, but will rather write the above code like this: public void getCustomers(){

try{ fileCustomers.read(); }catch(Exception e){ System.out.println("Problem reading file " + e.getMessage()); } } Catch blocks receive an instance of the Exception object that contains a short explanation of a problem, and its method getMessage() will return this info. If the description of an error returned by the getMessage() is not clear, try the method toString() instead. If you need more detailed information about the exception, use the method printStackTrace(). It will print all internal method calls that lead to this exception (see the section "Reading Stack Trace" above).

Clause throws
In some cases, it makes more sense to handle an exception not in the method where it happened, but in the calling method. Let's use the same example that reads a file. Since the method read() may throw an IOException, you should either handle it or declare it: class CustomerList{ void getAllCustomers() throws IOException{ file.read(); // Do not use try/catch if you are not handling exceptions here } public static void main(String[] args){ System.out.println("Customer List"); try{ // Since the getAllCustomers()declared exception, // we have to either handle it over here, or re// throw it (see the throw clause explanation below) getAllCustomers(); }catch(IOException e){ System.out.println("Sorry, the

Customer List is not available");

} } In this case, the IOException has been propagated from the getAllCustomers() to the main() method.

Clause finally
A try/catch block could be completed in different ways 1. the code inside the try block successfully ended and the program continues, 2. the code inside the try block ran into a return statement and the method is exited, 3. an exception has been thrown and code goes to the catch block, which handles it

4. an exception has been thrown and code goes to the catch block, which throws another exception to the calling method. If there is a piece of code that must be executed regardless of the success or failure of the code, put it under the clause finally: try{ file.read(); }catch(Exception e){ printStackTrace(); } finally{ file.close(); } The code above will definitely close the file regardless of the success of the read operation. The finally clause is usually used for the cleanup/release of the system resources such as files, database connections, etc.. If you are not planning to handle exceptions in the current method, they will be propagated to the calling method. In this case, you can use the finally clause without the catch clause: void myMethod () throws IOException{ try{ file.read(); } finally{ file.close(); } }

Clause throw
If an exception has occurred in a method, you may want to catch it and re-throw it to the calling method. Sometimes, you might want to catch one exception but re-throw another one that has a different description of the error (see the code snippet below). The throw statement is used to throw Java objects. The object that a program throws must be Throwable (you can throw a ball, but you can't throw a grand piano). This technically means that you can only throw subclasses of the Throwable class, and all Java exceptions are its subclasses: class CustomerList{ void getAllCustomers() throws Exception{ try{ file.read(); // this line may throw an exception } catch (IOException e) { // Perform some internal processing of this error, and _ throw new Exception ( "Dear Friend, the file has problems..."+ e.getMessage());

} } public static void main(String[] args){ System.out.println("Customer List"); try{ // Since the getAllCustomers() declares an // exception, wehave to either handle it, or re-throw it getAllCustomers(); }catch(Exception e){ System.out.println(e.getMessage()); } } }

User-Defined Exceptions
Programmers could also create user-defined exceptions, specific to their business. Let's say you are in business selling bikes and need to validate a customers order. Create a new class TooManyBikesException that is derived from the class Exception or Throwable, and if someone tries to order more bikes than you can ship - just throw this exception: class TooManyBikesException extends Exception{ TooManyBikesException (String msgText){ super(msgText); } } class BikeOrder{ static void validateOrder(String bikeModel,int quantity) throws TooManyBikesException{ // perform some data validation, and if you do not like // the quantity for the specified model, do the following: throw new TooManyBikesException("Can not ship" + quantity+" bikes of the model " + bikeModel +); } } class Order{ try{ bikeOrder.validateOrder("Model-123", 50); // the next line will be skipped in case of an exception System.out.println("The order is valid");

} catch(TooManyBikes e){ txtResult.setText(e.getMessage()); } } In general, to make your programs robust and easy to debug, you should always use the exception mechanism to report and handle exceptional situations in your program. Be specific when writing your catch clauses - catch as many exceptional situations as you can predict. Just having one catch (Exception e) statements is not a good idea.

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. As garbage collection is JVM dependent then It is possible for programs to use memory resources faster than they are garbage collected.Moreover garbage collection cannot be enforced,it is just suggested.Java guarantees that thefinalize method will be run before an object is Garbage collected,it is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

The garbage collection is uncontrolled, it means you cannot predict when it will happen, you thus cannot predict exactly when the finalize method will run. Once a variable is no longer referenced by anything it is available for garbage collection.You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen.

What is finally in Exception handling?


'finally' is a part of try-catch-throw and finally blocks for exception handling mechanism in Java.'finally' block contains snippet which is always executed irrespective of exception occurrence. The runtime system always executes the statements within the finally block regardless of what happens within the try block. The cleanup code is generally written in this part of snippet e.g. dangling references are collected here.

What can prevent the execution of the code in finally block?


-Use of System.exit() -The death of thread -Turning off the power to CPU -An exception arising in the finally block itself

Explain 'try','catch' and 'finally' blocks?

In Java exceptions are handled in try, catch, throw and finally blocks. It says try a block of Java code for a set of exception/s catch an exception if it appears in a catch block of code separate from normal execution of code. It clearly segregates errors from a block of code in an effective and efficient manner. The exceptions, which are caught, thrown using throw keyword. A finally block is called in order to execute clean up activities for any mess caused during abnormal execution of program.

Define Checked and Unchecked exception.


A checked exception is one, which a block of code is likely to throw, and represented by throws clause.It represents invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files). In Java it is expected that a method 'throws' an exception which is a checked exception.They are subclasses of Exception. While unchecked exceptions represent defects in the program (often invalid arguments passed to a non-private method). According to definition in The Java Programming Language, by Gosling, Arnold, and Holmes,"Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time." They are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).

Q: What is the Collections API? A: The Collections API is a set of classes and interfaces that support operations on collections of objects. [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the List interface? A: The List interface provides support for ordered collections of objects. [ Received from SPrasanna Inamanamelluri]
TOP

Q: What is the Vector class?

A: The Vector class provides the capability to implement a growable array of objects. [ Received from Prasanna Inamanamelluri]
TOP

Q: What is an Iterator interface? A: The Iterator interface is used to step through the elements of a Collection . [ Received from Prasanna Inamanamelluri]
TOP

Q: Which java.util classes and interfaces support event handling? A: The EventObject class and the EventListener interface support event processing. [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the GregorianCalendar class? A: The GregorianCalendar provides support for traditional Western calendars [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the Locale class? A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region . [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the SimpleTimeZone class? A: The SimpleTimeZone class provides support for a Gregorian calendar . [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the Map interface? A: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

[ Received from Prasanna Inamanamelluri]

TOP

Q: What is the highest-level event class of the event-delegation model? A: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy. [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the Collection interface? A: The Collection interface provides support for the implementation of a mathematical bag an unordered collection of objects that may contain duplicates. [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the Set interface? A: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. [ Received from Prasanna Inamanamelluri]
TOP

Q: What is the typical use of Hashtable? A: Whenever a program wants to store a key value pair, one can use Hashtable. [ Received from Sandesh Sadhale]
TOP

Q: I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere? A: The existing object will be overwritten and thus it will be lost. [ Received from Sandesh Sadhale]
TOP

Q: What is the difference between the size and capacity of a Vector? A: The size is the number of elements actually stored in the vector, while capacity is the

maximum number of elements it can store at a given instance of time. [ Received from Sandesh Sadhale]
TOP

Q: Can a vector contain heterogenous objects? A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object. [ Received from Sandesh Sadhale]
TOP

Q: Can a ArrayList contain heterogenous objects? A: Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object. [ Received from Sandesh Sadhale]
TOP

Q: What is an enumeration? A: An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection. [ Received from Sandesh Sadhale]
TOP

Q: Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList? A: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one. [ Received from Sandesh Sadhale]
TOP

Q: Can a vector contain heterogenous objects?

A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

http://fresherswisdom.com/

1) What is the difference between an Abstract class and Interface?


1. Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code. 2. An class can implement any number of interfaces, but subclass at most one abstract class. 3. An abstract class can have nonabstract methods. All methods of an interface are abstract. 4. An abstract class can have instance variables. An interface cannot. 5. An abstract class can define constructor. An interface cannot. 6. An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package). 7. An abstract class inherits from Object and includes methods such as clone() and equals().

2) What are checked and unchecked exceptions?


Java defines two kinds of exceptions : y Checked exceptions : Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples - SQLException, IOxception. Unchecked exceptions : RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions. Example Unchecked exceptions areNullPointerException, OutOfMemoryError, DivideByZeroException typically, programming errors.

3) What is a user defined exception?


User-defined exceptions may be implemented by y y defining a class to respond to the exception and embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled).

The developer can define a new exception by deriving it from the Exception class as follows:

public class MyException extends Exception { /* class definition of constructors (but NOT the exception handling code) goes here */ public MyException() { super(); } public MyException( String errorMessage ) { super( errorMessage ); } } The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax.

throw new MyException("I threw my own exception.") To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:

public myMethodName() throws MyException

4) What is the difference between C++ & Java?


Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are few I discovered: y y y y y y y y Java is multithreaded Java has no pointers Java has automatic memory management (garbage collection) Java is platform independent (Stroustrup may differ by saying "Java is a platform" Java has built-in support for comment documentation Java has no operator overloading Java doesnt provide multiple inheritance There are no destructors in Java

5) What are statements in JAVA ?


Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon y y y y Assignment expressions Any use of ++ or -Method calls Object creation expressions

These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements.

6) What is JAR file?


JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.

7)What is JNI?
JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages. Advantages: y y y y You want to use your existing library which was previously written in other language. You want to call Windows API function. For the sake of execution speed. You want to call API function of some server product which is in c or c++ from java client.

Disadvantages: y y y y You cant say write once run anywhere. Difficult to debug runtime error in native code. Potential security risk. You cant call it from Applet.

8) What is serialization?
Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream.

9) Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable

10) Is synchronised a modifier?indentifier??what is it??


It's a modifier. 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.

11) What is singleton class?where is it used?


Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections.

12) What is a compilation unit?


The smallest unit of source code that can be compiled, i.e. a .java file.

13) Is string a wrapper class?


String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and viceversa.

14) Why java does not have multiple inheritance?


The Java design team strove to make Java: y y y y y Simple, object oriented, and familiar Robust and secure Architecture neutral and portable High performance Interpreted, threaded, and dynamic

The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple). In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache.

15) Why java is not a 100% oops?


Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question..

16) What is a resource bundle?


In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key.

17) What is transient variable?


Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

18) What is Collection API?


The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map.

19) Is Iterator a Class or Interface? What is its use?


Iterator is an interface which is used to step through the elements of a Collection.

20) What is similarities/difference between an Abstract class and Interface?


Differences are as follows: y y Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

y y

Similarities:

Neither Abstract classes or Interface can be instantiated.

21) What is a transient variable?


A transient variable is a variable that may not be serialized.

22) Which containers use a border Layout as their default layout?


The window, Frame and Dialog classes use a border layout as their default layout.

23) 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.

24) 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.

25) 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.

26) 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..

27) 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.

28) Is null a keyword?


The null value is not a keyword.

29) 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.

30) What method is used to specify a container's layout?


The setLayout() method is used to specify a container's layout.

31) Which containers use a FlowLayout as their default layout?


The Panel and Applet classes use the FlowLayout as their default layout.

32) What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.

33) What is the Collections API?


The Collections API is a set of classes and interfaces that support operations on collections of objects.

34) 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.

35) What is the List interface?


The List interface provides support for ordered collections of objects.

36) 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.

37) What is the Vector class?


The Vector class provides the capability to implement a growable array of objects

38) 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.

39) What is an Iterator interface?


The Iterator interface is used to step through the elements of a Collection.

40) What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

41) Which method of the Component class is used to set the position and size of a component?
setBounds()

42) 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.

43) 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.

44) Which java.util classes and interfaces support event handling?


The EventObject class and the EventListener interface support event processing.

45) Is sizeof a keyword?


The sizeof operator is not a keyword.

46) What are wrapped classes?


Wrapped classes are classes that allow primitive types to be accessed as objects.

47) 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

48) 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).

49) Can an object's finalize() method be invoked while it is reachable?


An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

50) What is the immediate superclass of the Applet class? Panel


More ques on http://www.javabeat.net/articles/108-java-interview-questions-2.html

SERVLETS
Explain the life cycle methods of a Servlet. A: 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 with 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.

Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface? A: 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.
TOP

Q: Explain the directory structure of a web application. A: 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

Q: What are the common mechanisms used for session tracking? A: Cookies SSL sessions URL- rewriting

Q: Explain ServletContext. A: 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.

Q: What is preinitialization of a servlet? A: 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 <load-on-startup> 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. [ Received from Amit Bhoir ] Q: What is the difference between Difference between doGet() and doPost()? A: 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.allapplabs.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. [ Received from Amit Bhoir ] Q: What is the difference between HttpServlet and GenericServlet? A: 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. Q What is the difference between ServletContext and ServletConfig? : A:ServletContext: 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.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

Important Interview Questions of Servlets and JSP (JAVA)


What are Servlets? What are advantages of servlets over CGI? Can you explain Servlet life cycle? What are the two important API s in for Servlets? Can you explain in detail javax.servlet package? What s the use of Servlet Context? How do we define an application level scope for servlet? What's the difference between Generic Servlet and Http Servlet? Can you explain in detail javax.servlet.http package? What s the architecture of a Servlet package? Why is HTTP protocol called as a stateless protocol? What are the different ways we can maintain state between requests? What is URL rewriting? What are cookies? What are sessions in Servlets? What the difference is between get Session (true) and get Session (false)? What s the difference between do Post and do get methods? Which are the different ways you can communicate between servlets? What is functionality of Request Dispatcher object? How do we share data using get Servlet Context () ? Explain the concept of SSI? What are filters in JAVA? Can you explain in short how do you go about implementing filters using Apache Tomcat? Twist: - Explain step by step of how to implement filters? What s the difference between Authentication and authorization? Explain in brief the directory structure of a web application? Can you explain JSP page life cycle? What is EL? How does EL search for an attribute? What are the implicit EL objects in JSP? How can we disable EL? What is JSTL? Can you explain in short what the different types of JSTL tags are?

(I) How can we use beans in JSP? What is the use of <jsp: include>? What is <jsp: forward> tag for? What are JSP directives? What are Page directives? What are including directives? Can you explain taglib directives? How does JSP engines instantiate tag handler classes instances? What s the difference between JavaBeans and taglib directives? What are the different scopes an object can have in a JSP page? What are different implicit objects of JSP? What are different Authentication Options available in servlets? Can you explain how do we practically implement security on a resource? How do we practically implement form based authentication? How do we authenticate using JDBC? Can you explain JDBCRealm? Can you explain how do you configure JNDIRealm? How did you implement caching in JSP? What is the difference between Servletcontext and ServletConfig? How do we prevent browser from caching output of my JSP pages? Can we explicitly destroy a servlet object?

What's the difference between init() & init(ServletConfig) and Which is better ? A- Before start we have to understand the servlet flow.

For example you have servlet LoginServlet which extends HttpServlet public class LoginServlet extends HttpServlet{ } And your HttpServlet internally extends GenericServlet. public abstract class GenericServlet implements Servlet, ServletConfig, Serializable { public GenericServlet() { }

public void init() throws ServletException { } public ServletConfig getServletConfig() {

return config; } public void init(ServletConfig config) throws ServletException { this.config = config; init(); } public abstract void service(ServletRequest servletrequest, ServletResponse servletresponse) throws ServletException, IOException; private transient ServletConfig config; } Now servlet container flow Step 1. Loads the servlet class and create instance of the servlet class (LoginServlet). LoginServlet login = new LoginServlet(); Step 2. Then servlet container create ServletConfig object for that servlet and Call login.init(ServletConfig); Case 1 : If you have overridden init(ServletConfig) method in your servlet then call goes to your init(ServletConfig) method . public void init(ServletConfig config) throws ServletException { System.out.println("\n**** Initializing LoginServlet Init Servlet ********** \n"); super.init(config); } It will print "Initializing LoginServlet Init Servlet" and call goes to supper class GenericServlet init(ServletConfig) method. In the GenericServlet init(ServletConfig) method there is code This.config= config // initialize the Servlet config object and it is available to you. Case 2 : If you overridden init() method and not overridden init(ServletConfig) method. Servlet container call login.init(ServletConfig); There is no method like init(ServletConfig) in your servlet so call directly goes

to super class GenericServlet init(ServletConfig) method. This.config= config // initialize the Servlet config object and it is available to you. You can get the Servlet config object using getServletConfig() method. Conclusion: It is BETTER to use init(). If you use init() you have no such worries as calling super.init(). If you use init(servletconfig) and forgot to call super.init(config) then servletconfig object will not set and you will not get the servletconfig object. Ques. Can we override service method in HttpServlet ? You can override service method in HttpServlet also. If you override service method in HttpServlet then call will go to service() method instead of doGet() or doPost() method. If the jsp form you mentioned <form name="reg" method="post"> then also call will go to service method of the servlet. Call don't go to doPost() method. you can call doPost() method explicitly from servive() method. If the jsp form you mentioned <form name="reg" method="get"> then also call will go to service method of the servlet. Call don't go to doGet() method. you can call doGet () method explicitly from servive() method. Why IllegalStateException in jsp/servet?

by attempting to redirect from within the middle of a JSP page you will get IllegalStateException . For Example <div>News </div> <% if ("not logged in") response.sendRedirect("login.jsp"); %> <div>more news</div> You can avoid this bu using return ; Example : <div>News </div> <% if ("not logged in") response.sendRedirect("login.jsp"); return; %> <div>more news</div>

How the Web Container creates a servlet object


By Ramakrishna on Oct 5, 2008 in Servlet Interview Questions | 0 Comments

Rep) Web Container reads the name of the servlet class from web.xml and uses Class.forName() method to load the servlet class and it calls the newInstance() method to create the servlet Object.
1 QWhat is the difference between JSP and Servlets ? A JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc. QWhat is difference between custom JSP tags and beans? A 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. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags 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. 3 QWhat are the different ways for session tracking? A Cookies, URL rewriting, HttpSession, Hidden form fields QWhat mechanisms are used by a Servlet Container to maintain session information? A Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

QDifference between GET and POST A In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL. In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

QWhat is session? A The session is an object used by a servlet to track a user's interaction with a multiple HTTP Web application across requests. The session is stored on theserver. QWhat is servlet mapping? A The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets. QWhat is servlet context ? A The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. QWhat is a servlet ? A servlet is a java program that runs inside a web container. QCan we use the constructor, instead of init(), to initialize servlet? A Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldnt dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you wont have access to a ServletConfig or ServletContext. QHow many JSP scripting elements are there and what are they? A There are three scripting language elements: declarations, scriptlets, expressions. QHow do I include static files within a JSP page?

10

12

13

A Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. 14 QHow can I implement a thread-safe JSP page? A You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page. QWhat is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()? A In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource. QWhat are the lifecycle of JSP? A When presented with JSP page the JSP engine does the following 7 phases.

15

16

o o o o o o o

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.

17

QWhat are context initialization parameters? A Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application. QWhat is a Expression? A Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet. QWhat is a Declaration? A It declares one or more variables or methods for use later in the JSP source file.

18

19

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. This will be included in the declaration section of the generated servlet. 20 QWhat is a Scriptlet? A A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables 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 <jsp:useBean>. Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method.

Common JSP interview questions


By admin | September 23, 2004

1.

What are the implicit objects? - Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception. Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? - 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. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the <%! DECLARE %>tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

2. 3.

4.

5.

How do I prevent the output of my JSP or Servlet pages from being cached by the browser? - You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions. <% response.setHeader("Cache-Control","no-store"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>

6.

How do I use comments within a JSP page? - You can use JSP-style comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:
<%-- the scriptlet is now commented out <% out.println("Hello World"); %> --%>

7. 8. 9. 10. 11.

You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:
<!-- (c) 2004 -->

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:
<% //some comment /** yet another comment **/ %>

12. Response has already been commited error. What does it mean? - This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type=text/html or text/xml or plain-text or image/jpg, etc.)

When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasnt finished to set up the header. If not starter to set up the header, there are no problems, but if it s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over In this last case its like you have a file started with <HTML Tag><Some Headers><Body>some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1 13. How do I use a scriptlet to initialize a newly instantiated bean? - A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the today property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
14. <jsp:useBean id="foo" class="com.Bar.Foo" > 15. <jsp:setProperty name="foo" property="today" 16. value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ > 17. <%-- scriptlets calling bean setter methods go here --%> 18. </jsp:useBean >

19. How can I enable session tracking for JSP pages if the browser has disabled cookies? - We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
20. 21. hello1.jsp <%@ page session="true" %>

22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32.

<% Integer num = new Integer(100); session.putValue("num",num); String url =response.encodeURL("hello2.jsp"); %> <a href='<%=url%>'>hello2.jsp</a> hello2.jsp <%@ page session="true" %> <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is "+i.intValue());

33. How can I declare methods within my JSP page? - You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:
34. 35. 36. 37. 38. 39. 40. 41. 42. 43. <%! public String whereFrom(HttpServletRequest req) { HttpSession ses = req.getSession(); ... return req.getRemoteHost(); } %> <% out.print("Hi there, I see that you are coming in from "); %>

44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59.

<%= whereFrom(request) %> Another Example file1.jsp: <%@page contentType="text/html"%> <%! public void test(JspWriter writer) throws IOException{ writer.println("Hello!"); } %> file2.jsp <%@include file="file1.jsp"%> <html> <body> <%test(out);% > </body> </html>

60. Is there a way I can set the inactivity lease period on a per-session basis? - Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:
61. 62. 63. <% session.setMaxInactiveInterval(300); %>

would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds. 64. How can I set a cookie and delete a cookie from within a JSP page? - A cookie, mycookie, can be deleted using the following scriptlet:
65. <%

66. 67. 68. 69. 70. 71. 72. 73. 74.

//creating a cookie Cookie mycookie = new Cookie("aName","aValue"); response.addCookie(mycookie); //delete a cookie Cookie killMyCookie = new Cookie("mycookie", null); killMyCookie.setMaxAge(0); killMyCookie.setPath("/"); response.addCookie(killMyCookie); %>

75. How does a servlet communicate with a JSP page? - The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr")); f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f);

89. 90. 91. 92. 93. 94. } . . . }

getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) {

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request" / jsp:getProperty name="fBean" property="name" / jsp:getProperty name="fBean" property="addr" / jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean" property="personalizationInfo" /

95. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? - One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by: Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:  The service() method has to invoke the _jspService() method  The init() method has to invoke the jspInit() method  The destroy() method has to invoke jspDestroy() If any of the above conditions are not satisfied, the JSP engine may throw a translation error. Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends="packageName.ServletName" %>

96. How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values? - You could make a simple wrapper function, like
97. 98. <%! String blanknull(String s) {

99. 100. 101. 102. 103.

return (s == null) ? "" : s; } %> then use it inside your JSP form, like <input type="text" name="shoesize" value="<%=blanknull(shoesize)% >" >

104. How can I get to print the stacktrace for an exception occuring within my JSP page? - By printing out the exceptions stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:
105. 106. 107. 108. 109. 110. 111. <%@ page isErrorPage="true" %> <% out.println(" ");

PrintWriter pw = response.getWriter(); exception.printStackTrace(pw); out.println(" "); %>

112. How do you pass an InitParameter to a JSP? - The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
113. 114. 115. 116. 117. 118. 119. <%@ page import="java.util.*" %> <%! ServletConfig cfg =null; public void jspInit(){ ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) { String name=(String)e.nextElement();

120. 121. 122. 123. 124.

String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %>

125. How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
126. <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %> 127. 128. <%! //declare a "global" reference to an instance of the home interface of

the session bean 129. 130. 131. 132. 133. 134. AccountHome accHome=null; public void jspInit() { //obtain an instance of the home interface InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB"); accHome =

(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); 135. 136. 137. 138. 139. 140. 141. 142. } %> <% //instantiate the session bean Account acct = accHome.create(); //invoke the remote methods acct.doWhatever(...); // etc etc...

%>

Servlet Question 2. What is HTTP Session tracking and why is it important? Servlet Answer : HTTP Session tracking is the way Web server knows that the request is not a fresh or new request, and has a session already created in the web context. So when a request reaches web server, it looks for a variable called jsessionid, that should be associated with the request either in form of cookies, or URL rewriting. If your site visitor has blocked all cookies then redirect to another JSP or Servlet, will not be able to carry the same session, and all the data/object reference stored in HttpSession is/are lost. But is this redirect is done by using encodeURL method of HttpServletResponse object, then session id is attached as a part of URL and webserver attaches already created session to the new request. Servlet Question 3. What is session management, and how is it different from session tracking? Servlet Answer : HTTP session management is related to the mechanism, by which application data or client state can be passed from one request to another request (As HTTP is stateless). Session Management is obviously comes after session tracking, as without session tracking, client request cannot be hooked onto one and only one session. But if requirement is to just pass reasonably small data/variables, from one request to another, then it can be done, by Hidden form field, and can be transported from browser to server, either by POST or GET as method in HTML FORM tag. Servlet Question 4. Can I use Hidden form field to track session? Servlet Answer : No, as Hidden form field sends its value as a request parameter, which is not same as URL rewriting (passing jsessionid as part of URL).

Struts Validator Framework(www.javabeat.com)

This lesson introduces you the Struts Validator Framework. In this lesson you will learn how to use Struts ValidatorFramework to validate the user inputs on the client browser.

Introduction to Validator Framework

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of the form can be accomplished by sub classing your From Bean withDynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validatorframework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts

Framework and can be used without doing any extra settings.

Using Validator Framework

Validator uses the XML file to pickup the validation rules to be applied to an form. In XML validation requirements are defined applied to a form. In case we need special validation rules not provided by the validator framework, we can plug in our own custom validations into Validator. The Validator Framework uses two XML configuration files validatorrules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Structure of validator-rule.xml

The validation-rules.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines. It also contains the clientside javascript code for each validation routine. The validationroutines are java methods plugged into the system to perform specific validations. Following table contains the details of the elements in this file:

Element form-validation global validator

Attributes and Description This is the root node. It contains nested elements for all of the other configuration settings. The validator details specified within this, are global and are accessed by all forms. The validator element defines what validators objects can be used with the fields referenced by the formset elements. The attributes are:
y y y y

name: Contains a logical name for the validation routine classname: Name of the Form Bean class that extends the subclass of ActionForm class method: Name of the method of the Form Bean class methodParams: parameters passed to the method

y y

msg:Validator uses Struts' Resource Bundle mechanism for externalizing error messages. Instead of having hard-coded error messages in the framework, Validator allows you to specify a key to a message in the ApplicationResources.properties file that should be returned if a validation fails. Each validation routine in the validatorrules.xml file specifies an error message key as value for this attribute. depends: If validation is required, the value here is specified as 'required' for this attribute. jsFunctionName: Name of the javascript function is specified here.

javascript

Contains the code of the javascript function used for client-side validation. Starting in Struts 1.2.0 the default javascript definitions have been consolidated to commons-validator. The default can be overridden by supplying a <javascript> element with a CDATA section, just as in struts 1.1.

The Validator plug-in (validator-rules.xml) is supplied with a predefined set of commonly used validation rules such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. This basic set of rules can also be extended with custom validators if required.

Structure of validation.xml

This validation.xml configuration file defines which validation routines that is used to validate Form Beans. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

Element form-validation global constant constant-name constant-value formset form

Attributes and Description This is the root node. It contains nested elements for all of the other configuration settings The constant details are specified in <constant> element within this element. Constant properties are specified within this element for pattern matching. Name of the constant property is specified here Value of the constant property is specified here. This element contains multiple <form> elements This element contains the form details. The attributes are:

name:Contains the form name. Validator uses this logical name to map the validations to a Form Bean defined in the struts-config.xml file This element is inside the form element, and it defines the validations to apply to specified Form Bean fields. The attributes are: field
y y

property: Contains the name of a field in the specified Form Bean depends: Specifies the logical names of validationroutines from the validator-rules.xml file that should be applied to the field.

arg var var-name var-value

A key for the error message to be thrown incase the validation fails, is specified here Contains the variable names and their values as nested elements within this element. The name of the criteria against which a field is validated is specified here as a variable The value of the field is specified here

Example of form in the validation.xml file:

<!-- An example form --> <form name="logonForm"> <field property="username" depends="required"> <arg key="logonForm.username"/> </field> <field property="password" depends="required,mask"> <arg key="logonForm.password"/> <var> <var-name>mask</var-name> <var-value>^[0-9a-zA-Z]*$</var-value> </var> </field> </form>

The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code:<html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

In the next lesson we will create a new form for entering the address and enable the client side java script with theValidator Framework.

Client Side Address Validation in Struts

In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser. Validator Framework emits the JavaScript code which validates the user input on the browser. To accomplish this we have to follow the following steps:

1. Enabling the Validator plug-in: This makes the Validator available to the system. 2. Create Message Resources for the displaying the error message to the user. 3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation. 4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript. 5. Build and test: We are required to build the application once the above steps are done before testing.

Enabling the Validator plug- in

To enable the validator plug-in open the file struts-config.xml and make sure that following line is present in the file. <!-- Validator plugin --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in>

Creating Message Resources

Message resources are used by the Validator Framework to generate the validation error messages. In our applicationwe need to define the messages for name, Address and E-

mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines: AddressForm.name=Name AddressForm.address=Address AddressForm.emailAddress=E-mail address

Developing Validation rules

In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.

<!-- Address form Validation--> <form name="AddressForm"> <field property="name" depends="required"> <arg key="AddressForm.name"/> </field> <field property="address" depends="required"> <arg key="AddressForm.address"/> </field> <field property="emailAddress" depends="required"> <arg key="AddressForm.emailAddress"/> </field> </form>

The above definition defines the validation for the form fields name, address and emailAddress. The attributedepends="required" instructs the Validator Framework to generate the JavaScript that checks that the fields are not left blank. If the fields are left blank then JavaScript shows the error message. In the error message the message are taken from the key defined in the <arg key=".."/> tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties).

Applying Validation rules to JSP

Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:

<%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html locale="true"> <head> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body bgcolor="white"> <html:form action="/AddressJavascriptValidation" method="post" onsubmit="return validateAddressForm(this);"> <div align="left"> <p> This application shows the use of Struts Validator.<br> The following form contains fields that are processed by Struts Validator.<br> Fill in the form and see how JavaScript generated by Validator Framework validates the form. </p> <p> <html:errors/> </p> <table> <tr> <td align="center" colspan="2"> <font size="4"><b>Please Enter the Following Details</b></font> </tr> <tr> <td align="right"> <b>Name</b> </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <b>Address</b> </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right">

<b>E-mail address</b> </td> <td align="left"> <html:text property="emailAddress" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit> </td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table> </div> <!-- Begin Validator Javascript Function--> <html:javascript formName="AddressForm"/> <!-- End of Validator Javascript Function--> </html:form> </body> </html:html>

The code <html:javascript formName="AddressForm"/> is used to plug-in the Validator JavaScript. Create the following entry in the struts-config.xml for the mapping the /AddressJavascriptValidation url for handlingthe form submission through AddressJavascriptValidation.jsp.

<action path="/AddressJavascriptValidation" type="roseindia.net.AddressAction" name="AddressForm" scope="request" validate="true" input="/pages/AddressJavascriptValidation.jsp"> <forward name="success" path="/pages/success.jsp"/> </action> Add the following line in the index.jsp to call the form. <li> <html:link page="/pages/AddressJavascriptValidation.jsp">Client Side Validation

for Address Form</html:link> <br> The Address Form that validates the data on the client side using Stuts Validator generated JavaScript. </li>

Building Example and Testing

To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the AddressJavascriptValidation.jsp page. Your browser should show the following out put.

If the fields are left blank and Save button is clicked, browser shows the error message. In this lesson you learned how to use Struts Validator Framework to validate the form on client browser.

What if the main method is declared as private? The program compiles properly but at runtime it will give Main method not public. message. What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value. If youre overriding the method equals() of an object, which other method you might also consider? hashCode() What is Byte Code? Or What gives java its write once and run anywhere nature? All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent. Expain the reason for each keyword of public static void main(String args[])? public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public. static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static. void: main does not return anything so the return type must be void The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line. What are the differences between == and .equals() ? Or what is difference between == and equals Or Difference between == and equals method Or What would you use to compare two String variables - the operator == or the method equals()?

Or 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 i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory. == compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal. public class EqualsTest { public static void main(String[] args) { String s1 = abc; String s2 = s1; String s5 = abc; String s3 = new String(abc); String s4 = new String(abc); System.out.println(== comparison : + (s1 == s5)); System.out.println(== comparison : + (s1 == s2)); System.out.println(Using equals method : + s1.equals(s2)); System.out.println(== comparison : + s3 == s4); System.out.println(Using equals method : + s3.equals(s4)); } } Output == comparison : true == comparison : true Using equals method : true false Using equals method : true What if the static modifier is removed from the signature of the main method? Or What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error NoSuchMethodError. Why oracle Type 4 driver is named as oracle thin driver? Oracle provides a Type 4 JDBC driver, referred to as the Oracle thin driver. This driver includes its own implementation of a TCP/IP version of Oracles Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name. What is the difference between final, finally and finalize? What do you understand by the java final keyword? Or What is final, finalize() and finally? Or What is finalize() method? Or What is the difference between final, finally and finalize? Or What does it mean that a class or member is final? o final - declare constant o finally - handles exception o finalize - helps in garbage collection Variables defined in an interface are implicitly final. A final class cant be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method cant be overridden when its class is inherited. You cant change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method. 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. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. 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 programs appearance to the particular locale in which it is being run. Why there are no global variables in Java? Global variables are globally accessible. Java does not support globally accessible variables due to following reasons: y y The global variables breaks the referential transparency Global variables creates collisions in namespace.

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 numString = 1000 ; int id=Integer.valueOf(numString).intValue(); What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. What is the difference between a while statement and a do statement? A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) 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 loop body at least once. What is the Locale class? The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region. Describe the principles of OOPS. There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle. Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places 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 work for all scenarios. Example int i = 1000; long j = i; //Implicit casting Is sizeof a keyword in java? The sizeof operator is not a keyword. What is a native method? A native method is a method that is implemented in a language other than Java. In System.out.println(), what is System, out and println? System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object. What are Encapsulation, Inheritance and Polymorphism Or Explain the Polymorphism principle. Explain the different forms of Polymorphism. Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation. Polymorphism exists in three distinct forms in Java: Method overloading

Method overriding through inheritance Method overriding through the Java interface What is explicit casting? Explicit casting in the process in which the complier are specifically informed to about transforming the object. Example long i = 700.20; int j = (int) i; //Explicit casting What is the Java Virtual Machine (JVM)? The Java Virtual Machine is software that can be ported onto various hardware-based platforms 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 What are Java Access Specifiers? Or What is the difference between public, private, protected and default Access Specifiers? Or What are different types of access modifiers? Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing privileges to parts of a program such as functions and variables. These are: Public : accessible to all classes Protected : accessible to the classes within the same package and any subclasses. Private : accessible only to the class to which they belong Default : accessible to the class to which they belong and to subclasses within the same package Which class is the superclass of every class? Object.

Name primitive Java types. The 8 primitive types are byte, char, short, int, long, float, double, and boolean. What is the difference between static and non-static variables? Or What are class variables? Or What is static in java? Or What is a static method? A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesnt apply to an object or even require that any objects of the class have been instantiated. 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 cant override a static method with a non-static method. In other words, you cant change a static method into an instance method in a subclass. Non-static variables take on unique values with each object instance. What is the difference between the boolean & operator and the && operator? If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. 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. If the first operand evaluates to false, the evaluation of the second operand is skipped. 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 if I write static public void instead of public static void? Program compiles and runs properly. What is the difference between declaring a variable and defining a variable? In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String (bob); Or String s = bob; are both definitions. What type of parameter passing does Java support? In Java the arguments (primitives and objects) are always passed 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. Explain the Encapsulation principle. Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. What do you understand by a variable? Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program. 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 integral 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. What do you understand by casting in java language? What are the types of casting? The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting. 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. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null. How can one prove that the array is not null but empty? Print array.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 array.length. Can an application have multiple classes having main method? Yes. 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. When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java? Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields. Can I have multiple main methods in the same class? We can have multiple overloaded main methods but there can be only one main method with the following signature : public static void main(String[] args) {} No the program fails to compile. The compiler says that the main method is already defined in the class. Explain working of Java Virtual Machine (JVM)? JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes. How can I swap two variables without using a third variable?

Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example: int a=5,b=10;a=a+b; b=a-b; a=a-b; An other approach to the same question You use an XOR swap. for example: int a = 5; int b = 10; a = a ^ b; b = a ^ b; a = a ^ b; What is data encapsulation? Encapsulation may be used by creating get and set methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding. What is reflection API? How are they implemented? Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK. What is phantom memory? Phantom memory is false memory. Memory that does not exist in reality.

Can a method be static and synchronized? A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang. Class instance associated with the object. It is similar to saying: synchronized(XYZ.class) { } What is difference between String and StringTokenizer? A StringTokenizer is utility class used to break up string. Example: StringTokenizer st = new StringTokenizer(Hello World); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } Output: Hello World

Você também pode gostar