basic java interview questions

114
Basic Java interview questions 1. What is a Marker Interface? - An interface with no methods. Example: Serializable, Remote, Cloneable 2. What interface do you implement to do the sorting? - Comparable 3. What is the eligibility for a object to get cloned? - It must implement the Cloneable interface 4. What is the purpose of abstract class? - It is not an instantiable class. It provides the concrete implementation for some/all the methods. So that they can reuse the concrete functionality by inheriting the abstract class. 5. What is the difference between interface and abstract class? - Abstract class defined with methods. Interface will declare only the methods. Abstract classes are very much useful when there is a some functionality across various classes. Interfaces are well suited for the classes which varies in functionality but with the same method signatures. 6. What do you mean by RMI and how it is useful? - RMI is a remote method invocation. Using RMI, you can work with remote object. The function calls are as though you are invoking a local variable. So it gives you a impression that you are working really with a object that resides within your own JVM though it is somewhere. 7. What is the protocol used by RMI? - RMI-IIOP 8. What is a hashCode? - hash code value for this object which is unique for every object. 9. What is a thread? - Thread is a block of code which can execute concurrently with other threads in the JVM. 10. What is the algorithm used in Thread scheduling? - Fixed priority scheduling. 11. What is hash-collision in Hashtable and how it is handled in Java? - Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision. 12. What are the different driver types available in JDBC? - 1. A JDBC-ODBC bridge 2. A native-API partly Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-protocol fully Java technology-enabled driver For more information: Driver Description 13. Is JDBC-ODBC bridge multi-threaded? - No 14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? - No

Upload: arvind-singh

Post on 22-Apr-2015

108 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Basic Java Interview Questions

Basic Java interview questions

1. What is a Marker Interface? - An interface with no methods. Example: Serializable, Remote, Cloneable

2. What interface do you implement to do the sorting? - Comparable3. What is the eligibility for a object to get cloned? - It must implement the Cloneable interface4. What is the purpose of abstract class? - It is not an instantiable class. It provides the concrete

implementation for some/all the methods. So that they can reuse the concrete functionality by inheriting the abstract class.

5. What is the difference between interface and abstract class? - Abstract class defined with methods. Interface will declare only the methods. Abstract classes are very much useful when there is a some functionality across various classes. Interfaces are well suited for the classes which varies in functionality but with the same method signatures.

6. What do you mean by RMI and how it is useful? - RMI is a remote method invocation. Using RMI, you can work with remote object. The function calls are as though you are invoking a local variable. So it gives you a impression that you are working really with a object that resides within your own JVM though it is somewhere.

7. What is the protocol used by RMI? - RMI-IIOP8. What is a hashCode? - hash code value for this object which is unique for every object.9. What is a thread? - Thread is a block of code which can execute concurrently with other threads

in the JVM.10. What is the algorithm used in Thread scheduling? - Fixed priority scheduling.11. What is hash-collision in Hashtable and how it is handled in Java? - Two different keys with

the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.

12. What are the different driver types available in JDBC? - 1. A JDBC-ODBC bridge 2. A native-API partly Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-protocol fully Java technology-enabled driver For more information: Driver Description

13. Is JDBC-ODBC bridge multi-threaded? - No14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per

connection? - No15. What is the use of serializable? - To persist the state of an object into any perminant storage

device.16. What is the use of transient? - It is an indicator to the JVM that those variables should not be

persisted. It is the users responsibility to initialize the value when read back from the storage.17. What are the different level lockings using the synchronization keyword? - Class level lock

Object level lock Method level lock Block level lock18. What is the use of preparedstatement? - Preparedstatements are precompiled statements. It is

mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk processing.

19. What is callable statement? Tell me the way to get the callable statement? - Callablestatements are used to invoke the stored procedures. You can obtain the callablestatement from Connection using the following methods prepareCall(String sql) prepareCall(String sql, int resultSetType, int resultSetConcurrency)

20. In a statement, I am executing a batch. What is the result of the execution? - It returns the int array. The array contains the affected row count in the corresponding index of the SQL.

Page 2: Basic Java Interview Questions

21. Can a abstract method have the static qualifier? - No22. What are the different types of qualifier and what is the default qualifier? - public, protected,

private, package (default)23. What is the super class of Hashtable? - Dictionary24. What is a lightweight component? - Lightweight components are the one which doesn’t go with

the native call to obtain the graphical units. They share their parent component graphical units to render them. Example, Swing components

25. What is a heavyweight component? - For every paint call, there will be a native call to get the graphical units. Example, AWT.

26. What is an applet? - Applet is a program which can get downloaded into a client environment and start executing there.

27. What do you mean by a Classloader? - Classloader is the one which loads the classes into the JVM.

28. What are the implicit packages that need not get imported into a class file? - java.lang29. What is the difference between lightweight and heavyweight component? - Lightweight

components reuses its parents graphical units. Heavyweight components goes with the native graphical unit for every component. Lightweight components are faster than the heavyweight components.

30. What are the ways in which you can instantiate a thread? - Using Thread class By implementing the Runnable interface and giving that handle to the Thread class.

31. What are the states of a thread? - 1. New 2. Runnable 3. Not Runnable 4. Dead32. What is a socket? - A socket is an endpoint for communication between two machines.33. How will you establish the connection between the servlet and an applet? - Using the URL, I

will create the connection URL. Then by openConnection method of the URL, I will establish the connection, through which I can be able to exchange data.

34. What are the threads will start, when you start the java program? - Finalizer, Main, Reference Handler, Signal Dispatcher

Core Java interview questions

1. Can there be an abstract class with no abstract methods in it? - Yes2. Can an Interface be final? - No3. Can an Interface have an inner class? - Yes.4. public interface abc

5. {

6. static int i=0; void dd();

7. class a1

8. {

9. a1()

10. {

Page 3: Basic Java Interview Questions

11. int j;

12. System.out.println("inside");

13. };

14. public static void main(String a1[])

15. {

16. System.out.println("in interfia");

17. }

18. }

19. }

20. Can we define private and protected modifiers for variables in interfaces? - No21. What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And

sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

22. What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces.

23. What is a local, member and a class variable? - Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables

24. What are the different identifier states of a Thread? - The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock

25. What are some alternatives to inheritance? - Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

26. Why isn’t there operator overloading? - Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

27. What does it mean that a method or field is “static”? - Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather

Page 4: Basic Java Interview Questions

than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.

28. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?29. String hostname = InetAddress.getByName("192.18.97.39").getHostName();

30. Difference between JRE/JVM/JDK?31. 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.32. 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.

33. Is null a keyword? - The null value is not a keyword.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 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.

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

37. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects.

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

39. What is the difference between preemptive scheduling and time slicing? - Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

40. What is a native method? - A native method is a method that is implemented in a language other than Java.

41. What are order of precedence and associativity, and how are they used? - Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

42. What is the catch or declare rule for method declarations? - If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

43. Can an anonymous class be declared as implementing an interface and extending a class? - An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

44. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.

Page 5: Basic Java Interview Questions

Java Interview Questions and Answers

What  is Java?Java is an object-oriented programming language developed initially by James Gosling and colleagues at Sun Microsystems. The language, initially called Oak (named after the oak trees outside Gosling's office), was intended to replace C++, although the feature set better resembles that of Objective C. Java should not be confused with JavaScript, which shares only the name and a similar C-like syntax. Sun Microsystems currently maintains and updates Java regularly.

What does a well-written OO program look like? A well-written OO program exhibits recurring structures that promote abstraction, flexibility, modularity and elegance.

Can you have virtual functions in Java? Yes, all functions in Java are virtual by default. This is actually a pseudo trick question because the word "virtual" is not part of the naming convention in Java (as it is in C++, C-sharp and VB.NET), so this would be a foreign concept for someone who has only coded in Java. Virtual functions or virtual methods are functions or methods that will be redefined in derived classes.

Jack developed a program by using a Map container to hold key/value pairs. He wanted to make a change to the map. He decided to make a clone of the map in order to save the original data on side. What do you think of it? ? If Jack made a clone of the map, any changes to the clone or the original map would be seen on both maps, because the clone of Map is a shallow copy. So Jack made a wrong decision.

What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class? Strategically speaking, threads created by implementing Runnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Runnable interface, you save a space for your class to extend another class now or in future.

What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown: --Calling the instance method of a null object.--Accessing or modifying the field of a null object.--Taking the length of a null as if it were an array.--Accessing or modifying the slots of null as if it were an array.--Throwing null as if it were a Throwable value.The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.

An application needs to load a library before it starts to run, how to code?One option is to use a static block to load a library before anything is called. For example, class Test { static {System.loadLibrary("path-to-library-file");}

Page 6: Basic Java Interview Questions

....} When you call new Test(), the static block will be called first before any initialization happens. Note that the static block position may matter.

How could Java classes direct program messages to the system console, but error messages, say to a file? The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed: Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

What's the difference between an interface and an abstract class? 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.

Name the containers which uses Border Layout as their default layout? Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

What do you understand by Synchronization? Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.Synchronization prevents such type of data corruption.E.g. Synchronizing a function:public synchronized void Method1 () {// Appropriate method-related code. }E.g. Synchronizing a block of code inside a function:public myFunction (){synchronized (this) { // Synchronized code here.}}

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. 

Page 7: Basic Java Interview Questions

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.Example of interfaces: Collection, Set, List and Map.

Is Iterator a Class or Interface? What is its use? Answer: Iterator is an interface which is used to step through the elements of a Collection.

What is similarities/difference between an Abstract class and Interface? Differences are as follows: 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. Similarities: 

Neither Abstract classes or Interface can be instantiated.

Java Interview Questions - How to define an Abstract class? A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.Example of Abstract class:abstract class testAbstractClass {protected String myString; public String getMyString() { return myString; } public abstract string anyAbstractFunction();}

How to define an Interface in Java ? In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.Emaple of Interface:

public interface sampleInterface {public void functionOne();

public long CONSTANT_ONE = 1000; }

If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:c:\>java com.xyz.hr.Employee

Page 8: Basic Java Interview Questions

How many methods in the Serializable interface? There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.

How many methods in the Externalizable interface? There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().

What is the difference between Serializalble and Externalizable interface? When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

What is a transient variable in Java? A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.

Which containers use a border layout as their default layout? The Window, Frame and Dialog classes use a border layout as their default layout.

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.

What is synchronization and why is it important?With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to a method or an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

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

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.

Page 9: Basic Java Interview Questions

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.

What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally.

What's the difference between J2SDK 1.5 and J2SDK 5.0? There's no difference, Sun Microsystems just re-branded this version.

What would you use to compare two String variables - the operator == or the method equals()? I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

What is thread? A thread is an independent path of execution in a system.

What is multi-threading? Multi-threading means various threads that run in a system.

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

How to create a thread in a program? You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread.

Can Java object be locked down for exclusive use by a given thread? Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

Can each Java object keep track of all the threads that want to exclusively access to it? Yes. Use Thread.currentThread() method to track the accessing thread.

Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written? Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

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

What is the purpose of the wait(), notify(), and notifyAll() methods?The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

Page 10: Basic Java Interview Questions

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

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.

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

What is the difference between Process and Thread? A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space; a thread doesn't. Threads typically share the heap belonging to their parent process. For instance, a JVM runs in a single process in the host O/S. Threads in the JVM share the heap belonging to that process; that's why several threads may access the same object. Typically, even though they share a common heap, threads have their own stack space. This is how one thread's invocation of a method is kept separate from another's. This is all a gross oversimplification, but it's accurate enough at a high level. Lots of details differ between operating systems. Process vs. Thread A program vs. similar to a sequential program an run on its own vs. Cannot run on its own Unit of allocation vs. Unit of execution Have its own memory space vs. Share with others Each process has one or more threads vs. Each thread belongs to one process Expensive, need to context switch vs. Cheap, can use process memory and may not need to context switch More secure. One process cannot corrupt another process vs. Less secure. A thread can write the memory used by another thread

Can an inner class declared inside of a method access local variables of this method? It's possible if these variables are final.

What can go wrong if you replace &emp;&emp; with &emp; in the following code: String a=null; if (a!=null && a.length()>10) {...} A single ampersand here would lead to a NullPointerException.

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

What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

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

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits 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.

Page 11: Basic Java Interview Questions

What's the main difference between a Vector and an ArrayList? Java Vector class is internally synchronized and ArrayList is not.

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

Does garbage collection guarantee that a program will not run out of memory? No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Name Component subclasses that support painting ?The Canvas, Frame, Panel, and Applet classes support painting.

What is a native method? A native method is a method that is implemented in a language other than Java.

How can you write a loop indefinitely? for(;;)--for loop; while(true)--always true, etc.

Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

When should the method invokeLater()be used? This method is used to ensure that Swing components are updated through the event-dispatching thread.

How many methods in Object class? This question is not asked to test your memory. It tests you how well you know Java. Ten in total.clone() equals() & hashcode() getClass() finalize() wait() & notify() toString()

How does Java handle integer overflows and underflows? It uses low order bytes of the result that can fit into the size of the type allowed by the operation.

Page 12: Basic Java Interview Questions

What is the numeric promotion? Numeric promotion is used with both unary and binary bitwise operators. This means that byte, char, and short values are converted to int values before a bitwise operator is applied.If a binary bitwise operator has one long operand, the other operand is converted to a long value.The type of the result of a bitwise operation is the type to which the operands have been promoted. For example:short a = 5;byte b = 10;long c = 15;The type of the result of (a+b) is int, not short or byte. The type of the result of (a+c) or (b+c) is long.

Is the numeric promotion available in other platform? Yes. Because Java is implemented using a platform-independent virtual machine, bitwise operations always yield the same result, even when run on machines that use radically different CPUs.

What is the difference between the Boolean & operator and the && operator? If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.

When is the ArithmeticException throwQuestion: What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars.

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

How can a subclass call a method or a constructor defined in a superclass? Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.

What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system.

What is the purpose of the System class?The purpose of the System class is to provide access to system resources.

What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

Page 13: Basic Java Interview Questions

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

What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation.

What is the difference between interface and abstract class? interface contains methods that must be abstract; abstract class may contain concrete methods. interface contains variables that must be static and final; abstract class may contain non-final and final variables. members in an interface are public by default, abstract class may contain non-public members. interface is used to "implements"; whereas abstract class is used to "extends". interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance. interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces. interface is absolutely abstract; abstract class can be invoked if a main() exists. interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces. If given a choice, use interface instead of abstract class.

What is a static method? A static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.

What is a protected method? A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.

What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

What is an object's lock and which object's have locks? An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

When can an object reference be cast to an interface reference? An object reference can be cast to an interface reference when the object implements the referenced interface.

What is the difference between a Window and a Frame? The Frame class extends Window to define a main application window that can have a menu bar.

What is the difference between a Window and a Frame? Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every

Page 14: Basic Java Interview Questions

component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.

Which package has light weight components? javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

What are peerless components? The peerless components are called light weight components.

What is the difference between the Font and FontMetrics classes? The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.

What is the difference between throw and throws keywords? The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.

If a class is declared without any access modifiers, where may the class be accessed? A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

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

Does a class inherit the constructors of its super class? A class does not inherit constructors from any of its superclasses.

Name primitive Java types. The primitive types are byte, char, short, int, long, float, double, and Boolean.

Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object's design.

Page 15: Basic Java Interview Questions

How can a GUI component handle its own events? A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

How are the elements of a GridBagLayout organized? The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

What advantage do Java's layout managers provide over traditional windowing systems? Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

What are the problems faced by Java programmers who don't use layout managers? Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

What is the purpose of the File class? The File class is used to create objects that provide access to the files and directories of a local file system.

Why would you use a synchronized block vs. synchronized method? Synchronized blocks place locks for shorter periods than synchronized methods. 

What restrictions are placed on method overriding?Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

What is casting? There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Explain the usage of the keyword transient? This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

Page 16: Basic Java Interview Questions

What class allows you to read objects directly from a stream? The ObjectInputStream class supports the reading of objects from input streams.

How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

How is it possible for two String objects with identical values not to be equal under the == operator? How are this() and super() used with constructors? The == operator compares two objects to determine if they are the same objects in memory. It is possible for two String objects to have the same value, but located in different areas of memory.

What is an IO filter? An IO filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

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

How can you force garbage collection? You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

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

What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

What interface must an object implement before it can be written to a stream as an object? An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

How do you know if an explicit object casting is needed? If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example: Object a; Customer b; b = (Customer) a; When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

What is a Java package and how is it used? A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. 

Page 17: Basic Java Interview Questions

How do you restrict a user to cut and paste from the html page? Using Servlet or client side scripts to lock keyboard keys. It is one of solutions.

What are the Object and Class classes used for?The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

What is Serialization and deserialization ? Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

Explain the usage of Java packages. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.

Is Java a super set of JavaScript? No. They are completely different. Some syntax may be similar.

What is a Container in a GUI? A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

How the object oriented approach helps us keep complexity of software development under control? We can discuss such issue from the following aspects: Objects allow procedures to be encapsulated with their data to reduce potential interference. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places. The well-defined separations of interface and implementation allow constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.

What is polymorphism? Polymorphism means "having many forms". It allows methods (may be variables) to be written that needn't be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of un-conceived classes.

What is design by contract? The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying

Page 18: Basic Java Interview Questions

the post conditions. In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

What are use cases? A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust.

What is scalability and performance? Performance is a measure of "how fast can you perform this task." and scalability describes how an application behaves as its workload and available computing resources increase.

What is the benefit of subclass? Generally: The sub class inherits all the public methods and the implementation. The sub class inherits all the protected methods and their implementation. The sub class inherits all the default(non-access modifier) methods and their implementation. The sub class also inherits all the public, protected and default member variables from the super class. The constructors are not part of this inheritance model.

How to add menushortcut to menu item? If you have a button instance called aboutButton, you may add menu short cut by calling aboutButton.setMnemonic('A'), so the user may be able to use Alt+A to click the button. 

In System.out.println(),what is System,out and println,pls explain?System is a predefined final class,out is a PrintStream object acting as a field member and println is a built-in overloaded method in the out object.

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.

Can you make an instance of an abstract class? For example - java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class. No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method.

What is the output of x > y? a:b = p*q when x=1,y=2,p=3,q=4? When this kind of question has been asked, find the problems you think is necessary to ask back before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x

What is the difference between Swing and AWT components? AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

Page 19: Basic Java Interview Questions

Why Java does not support pointers? Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C-sharp shine.

Parsers? DOM vs SAX parser Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.DOM1. Tree of nodes2. Memory: Occupies more memory, preffered for small XML documents3. Slower at runtime 4. Stored as objects 5. Programmatically easy 6. Ease of navigation SAX 1. Sequence of events 2. Doesn't use any memory preferred for large documents3. Faster at runtime4. Objects are to be created5. Need to write code for creating objects6. Backward navigation is not possible as it sequentially processes the document

Can you declare a class as private? Yes, we can declare a private class as an inner class. For example,

class MyPrivate {private static class MyKey {String key = "12345";}public static void main(String[] args) {System.out.println(new MyKey().key);//prints 12345}}

What is the difference between shallow copy and deep copy?Shallow copy shares the same reference with the original object like cloning, whereas the deep copy get a duplicate instance of the original object. If the shallow copy has been changed, the original object will be reflected and vice versa.

Can one create a method which gets a String and modifies it? No. In Java, Strings are constant or immutable; their values cannot be changed after they are created, but they can be shared. Once you change a string, you actually create a new object. For example: String s = "abc"; //create a new String object representing "abc" s = s.toUpperCase(); //create another object representing "ABC"

Why is multiple inheritance not possible in Java? It depends on how you understand "inheritance". Java can only "extends" one super class, but can "implements" many interfaces; that doesn't mean the multiple inheritance is not possible. You may use interfaces to make inheritance work for you. Or you may need to work around. For example, if you

Page 20: Basic Java Interview Questions

cannot get a feature from a class because your class has a super class already, you may get that class's feature by declaring it as a member field or getting an instance of that class. So the answer is that multiple inheritance in Java is possible.

What's the difference between constructors and other methods? Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

1. What is garbage collection? What is the process that is responsible for doing that in java? -

Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this

process

2. What kind of thread is the Garbage collector thread? - It is a daemon thread.

3. What is a daemon thread? - These are the threads which can run without user intervention. The

JVM can exit when there are daemon thread by killing them abruptly.

4. How will you invoke any external process in Java? - Runtime.getRuntime().exec(….)

5. What is the finalize method do? - Before the invalid objects get garbage collected, the JVM

give the user a chance to clean up some resources before it got garbage collected.

6. What is mutable object and immutable object? - If a object value is changeable then we can

call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an

object, it is immutable object. (Ex., String, Integer, Float, …)

7. What is the basic difference between string and stringbuffer object? - String is an immutable

object. StringBuffer is a mutable object.

8. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to

hold a reference to the Class object representing the primitive Java type void.

9. What is reflection? - Reflection allows programmatic access to information about the fields,

methods and constructors of loaded classes, and the use reflected fields, methods, and

constructors to operate on their underlying counterparts on objects, within security restrictions.

10. What is the base class for Error and Exception? - Throwable

11. What is the byte range? -128 to 127

12. What is the implementation of destroy method in java.. is it native or java code? - This

method is not implemented.

13. What is a package? - To group set of classes into a single unit is known as packaging. Packages

provides wide namespace ability.

Page 21: Basic Java Interview Questions

14. What are the approaches that you will follow for making a program very efficient? - By

avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized

methods Selection of related classes based on the application (meaning synchronized classes for

multiuser and non-synchronized classes for single user) Usage of appropriate design patterns

Using cache methodologies for remote invocations Avoiding creation of variables within a loop

and lot more.

15. What is a DatabaseMetaData? - Comprehensive information about the database as a whole.

16. What is Locale? - A Locale object represents a specific geographical, political, or cultural region

17. How will you load a specific locale? - Using ResourceBundle.getBundle(…);

18. What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a

one-pass compiler — no offline computations. So you can’t look at the whole method, rank the

expressions according to which ones are re-used the most, and then generate code. In theory

terms, it’s an on-line problem.

19. Is JVM a compiler or an interpreter? - Interpreter

20. When you think about optimization, what is the best way to findout the time/memory

consuming process? - Using profiler

21. What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain

expressions. It effectively replaces the if block and automatically throws the AssertionError on

failure. This keyword should be used for the critical arguments. Meaning, without that the method

does nothing.

22. How will you get the platform dependent values like line separator, path separator, etc., ? -

Using Sytem.getProperty(…) (line.separator, path.separator, …)

23. What is skeleton and stub? what is the purpose of those? - Stub is a client side representation

of the server, which takes care of communicating with the remote server. Skeleton is the server

side representation. But that is no more in use… it is deprecated long before in JDK.

24. What is the final keyword denotes? - final keyword denotes that it is the final implementation

for that method or variable or class. You can’t override that method/variable/class any more.

25. What is the significance of ListIterator? - You can iterate back and forth.

26. What is the major difference between LinkedList and ArrayList? - LinkedList are meant for

sequential accessing. ArrayList are meant for random accessing.

Page 22: Basic Java Interview Questions

27. What is nested class? - If all the methods of a inner class is static then it is a nested class.

28. What is inner class? - If the methods of the inner class can only be accessed via the instance of

the inner class, then it is called inner class.

29. What is composition? - Holding the reference of the other class within some other class is

known as composition.

30. What is aggregation? - It is a special type of composition. If you expose all the methods of a

composite class and route the method call to the composite method through its reference, then it

is called aggregation.

31. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify,

notifyAll, toString

32. Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in

this class are static. And the constructor is not public.

33. What is singleton? - It is one of the design pattern. This falls in the creational pattern of the

design pattern. There will be only one instance for that entire JVM. You can achieve this by

having the private constructor in the class. For eg., public class Singleton { private static final

Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance()

{ return s; } // all non static methods … }

34. What is DriverManager? - The basic service to manage set of JDBC drivers.

35. What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It

returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).

36. Inq adds a question: Expain the reason for each keyword of

public static void main(String args[])

Javascript Interview Questions and Answers

What is JavaScript?A1: JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be--and is--used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser

Page 23: Basic Java Interview Questions

with the rest of the HTML tags and content. 

A2:JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

How is JavaScript different from Java? JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements. JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the "Java" name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the "Java" name on JavaScript has confused the world's understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.

What’s relationship between JavaScript and ECMAScript? ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. 

How do you submit a form using Javascript? Use document.forms[0].submit();(0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).

How do we get JavaScript onto a web page? You can use several different methods of placing javascript in you pages. You can directly add a script element inside the body of page. 1. For example, to add the "last updated line" to your pages, In your page text, add the following: <p>blah, blah, blah, blah, blah.</p><script type="text/javascript" ><!-- Hiding from old browsersdocument.write("Last Updated:" + document.lastModified);document.close();// --></script><p>yada, yada, yada.</p>

(Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "// -->" finishes the comment. The "//" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. ) The above code will look like this on Javascript enabled browsers, 

Page 24: Basic Java Interview Questions

2. Javascript can be placed inside the <head> element Functions and global variables typically reside inside the <head> element. <head><title>Default Test Page</title><script language="JavaScript" type="text/javascript">var myVar = "";function timer(){setTimeout('restart()',10);}document.onload=timer();</script></head>

Javascript can be referenced from a separate file Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending "<script ... />). These are typically placed in the <head> element. <script type="text/javascript" SRC="myStuff.js"></script>

How to read and write a file using javascript? I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.

How to detect the operating system on the client machine? In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.

How can JavaScript make a Web site easier to use? That is, are there certain JavaScript techniques that make it easier for people to use a Web site? JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client. For example, consider a top-level navigation panel that has, say, six primary image map links into subsections of the Web site. With only a little bit of scripting, each map area can be instructed to pop up a more detailed list of links to the contents within a subsection whenever the user rolls the cursor atop a map area. With the help of that popup list of links, the user with a scriptable browser can bypass one intermediate menu page. The user without a scriptable browser (or who has disabled JavaScript) will have to drill down through a more traditional and time-consuming path to the desired content.

How can JavaScript be used to improve the "look and feel" of a Web site? By the same token, how can JavaScript be used to improve the user interface?On their own, Web pages tend to be lifeless and flat unless you add animated images or more bandwidth-intensive content such as Java applets or other content requiring plug-ins to operate (ShockWave and Flash, for example). Embedding JavaScript into an HTML page can bring the page to life in any number of ways. Perhaps the most visible features built into pages recently with the help of JavaScript are the so-called image rollovers: roll the cursor atop a graphic image and its appearance changes to a highlighted version as a feedback mechanism to let you know precisely what you're about to click on. But there are less visible yet more powerful enhancements to pages that JavaScript offers. Interactive forms validation is an extremely useful application of JavaScript. While a user is entering data into form fields, scripts can examine the validity of the data--did the user type any letters into a phone

Page 25: Basic Java Interview Questions

number field?, for instance. Without scripting, the user has to submit the form and let a server program (CGI) check the field entry and then report back to the user. This is usually done in a batch mode (the entire form at once), and the extra transactions take a lot of time and server processing power. Interactive validation scripts can check each form field immediately after the user has entered the data, while the information is fresh in the mind. Another helpful example is embedding small data collections into a document that scripts can look up without having to do all the server programming for database access. For instance, a small company could put its entire employee directory on a page that has its own search facility built into the script. You can cram a lot of text data into scripts no larger than an average image file, so it's not like the user has to wait forever for the data to be downloaded. Other examples abound, such as interactive tree-structure tables of contents. More modern scriptable browsers can be scripted to pre-cache images during the page's initial download to make them appear lickety-split when needed for image swapping. I've even written some multi-screen interactive applications that run entirely on the client, and never talk to the server once everything is downloaded.

What are JavaScript types? Number, String, Boolean, Function, Object, Null, Undefined.

How do you convert numbers between different bases in JavaScript? Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

How to create arrays in JavaScript? We can declare an array like this var scripts = new Array(); We can add elements to this array like this

scripts[0] = "PHP";scripts[1] = "ASP";scripts[2] = "JavaScript";scripts[3] = "HTML";

Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array. document.write(scripts[2]); We also can create an array like this var no_array = new Array(21, 22, 23, 24, 25);

How do you target a specific frame from a hyperlink? Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>

What is a fixed-width table and its advantages?

Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table. If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.

Page 26: Basic Java Interview Questions

Example of using Regular Expressions for syntax checking in JavaScript 

...var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");var text = myWidget.value;var OK = re.test(text);if( ! OK ) {alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");}

Where are cookies actually stored on the hard disk? This depends on the user's browser and OS.In the case of Netscape with Windows OS,all the cookies are stored in a single file called

cookies.txt c:\Program Files\Netscape\Users\username\cookies.txt In the case of IE,each cookie is stored in a separate file namely [email protected]. c:\Windows\Cookies\[email protected] 

How to add Buttons in JavaScript?The most basic and ancient use of buttons are the "submit" and "clear", which appear slightly before the Pleistocene period. Notice when the "GO!" button is pressed it submits itself to itself and appends the name in the URL. <form action="" name="buttonsGalore" method="get">Your Name: <input type="text" name="mytext" /><br /><input type="submit" value="GO!" /><input type="reset" value="Clear All" /></form>

Another useful approach is to set the "type" to "button" and use the "onclick" event. <script type="text/javascript">function displayHero(button) {alert("Your hero is \""+button.value+"\".");}</script>

<form action="" name="buttonsGalore" method="get"><fieldset style="margin: 1em; text-align: center;"><legend>Select a Hero</legend><input type="button" value="Agamemnon" onclick="displayHero(this)" /><input type="button" value="Achilles" onclick="displayHero(this)" /><input type="button" value="Hector" onclick="displayHero(this)" /><div style="height: 1em;" /></fieldset></form>

What can javascript programs do? Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control

Page 27: Basic Java Interview Questions

over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling

How to set a HTML document's background color? document.bgcolor property can be set to any appropriate color.

How can JavaScript be used to personalize or tailor a Web site to fit individual users? JavaScript allows a Web page to perform "if-then" kinds of decisions based on browser version, operating system, user input, and, in more recent browsers, details about the screen size in which the browser is running. While a server CGI program can make some of those same kinds of decisions, not everyone has access to or the expertise to create CGI programs. For example, an experienced CGI programmer can examine information about the browser whenever a request for a page is made; thus a server so equipped might serve up one page for Navigator users and a different page for Internet Explorer users. Beyond browser and operating system version, a CGI program can't know more about the environment. But a JavaScript-enhanced page can instruct the browser to render only certain content based on the browser, operating system, and even the screen size. Scripting can even go further if the page author desires. For example, the author may include a preference screen that lets the user determine the desired background and text color combination. A script can save this information on the client in a well-regulated local file called a cookie. The next time the user comes to the site, scripts in its pages look to the cookie info and render the page in the color combination selected previously. The server is none the wiser, nor does it have to store any visitor-specific information.

Are you concerned that older browsers don't support JavaScript and thus exclude a set of Web users? individual users? Fragmentation of the installed base of browsers will only get worse. By definition, it can never improve unless absolutely everyone on the planet threw away their old browsers and upgraded to the latest gee-whiz versions. But even then, there are plenty of discrepancies between the scriptability of the latest Netscape Navigator and Microsoft Internet Explorer. The situation makes scripting a challenge, especially for newcomers who may not be aware of the limitations of earlier browsers. A lot of effort in my books and ancillary material goes toward helping scripters know what features work in which browsers and how to either workaround limitations in earlier browsers or raise the compatibility common denominator. Designing scripts for a Web site requires making some hard decisions about if, when, and how to implement the advantages scripting offers a page to your audience. For public Web sites, I recommend using scripting in an additive way: let sufficient content stand on its own, but let scriptable browser users receive an enhanced experience, preferably with the same HTML document.

What does isNaN function do? Return true if the argument is not a number.

What is negative infinity? It’s a number in JavaScript, derived by dividing negative number by zero.

In a pop-up browser window, how do you refer to the main browser window that opened it? Use window.opener to refer to the main window from pop-ups.

What is the data type of variables of in JavaScript? All variables are of object type in JavaScript. 

Page 28: Basic Java Interview Questions

Methods GET and POST in HTML forms - what's the difference?GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb.POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.

How to write a script for "Select" lists using javascript 1. To remove an item from a list set it to null mySelectObject.options[3] = null; 2. To truncate a list set its length to the maximum size you desire mySelectObject.length = 2; 3. To delete all options in a select object set the length to 0. mySelectObject.leng

Text From Your Clipboard? It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server.

What does the "Access is Denied" IE error mean? The "Access Denied" error in any browser is due to the following reason.A javascript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script.

Is a javascript script faster than an ASP script? Yes.Since javascript is a client-side script it does require the web server's help for its computation,so it is always faster than any server-side script like ASP,PHP,etc..

Are Java and JavaScript the Same? No.java and javascript are two different languages.Java is a powerful object - oriented programming language like C++,C whereas Javascript is a client-side scripting language with some limitations.

How to embed javascript in a web page? javascript code can be embedded in a web page between <script langugage="javascript"></script> tags

What and where are the best JavaScript resources on the Web? The Web has several FAQ areas on JavaScript. The best place to start is something called the meta-FAQ [14-Jan-2001 Editor's Note: I can't point to it anymore, it is broken!], which provides a high-level overview of the JavaScript help available on the Net. As for fact-filled FAQs, I recommend one maintained by Martin Webb and a mini-FAQ that I maintain. For interactive help with specific problems, nothing beats the primary JavaScript Usenet newsgroup, comp.lang.javascript. Depending on my work backlog, I answer questions posted there from time to time. Netscape and Microsoft also have vendor-specific developer discussion groups as well as detailed documentation for the scripting and object model implementations.

What are the problems associated with using JavaScript, and are there JavaScript techniques that you discourage? Browser version incompatibility is the biggest problem. It requires knowing how each scriptable browser

Page 29: Basic Java Interview Questions

version implements its object model. You see, the incompatibility rarely has to do with the core JavaScript language (although there have been improvements to the language over time); the bulk of incompatibility issues have to do with the object models that each browser version implements. For example, scripters who started out with Navigator 3 implemented the image rollover because it looked cool. But they were dismayed to find out that the image object wasn't scriptable in Internet Explorer 3 or Navigator 2. While there are easy workarounds to make this feature work on newer browsers without disturbing older ones, it was a painful learning experience for many. The second biggest can of worms is scripting connections between multiple windows. A lot of scripters like to have little windows pop up with navigation bars or some such gizmos. But the object models, especially in the older browser versions, don't make it easy to work with these windows the minute you put a user in front of them--users who can manually close windows or change their stacking order. More recently, a glitch in some uninstall routines for Windows 95 applications can disturb vital parts of the system Registry that Internet Explorer 4 requires for managing multiple windows. A scripter can't work around this problem, because it's not possible to detect the problem in a user's machine. I tend to avoid multiple windows that interact with each other. I think a lot of inexperienced Web surfers can also get confused by them.

What Boolean operators does JavaScript support? &&, || and !

What does "1"+2+4 evaluate to? Since 1 is a string, everything is a string, so the result is 124. 

JavaScript interview questions and answers

1. What’s relationship between JavaScript and ECMAScript? - ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.

2. What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined.3. How do you convert numbers between different bases in JavaScript? - Use the parseInt()

function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);

4. What does isNaN function do? - Return true if the argument is not a number.5. What is negative infinity? - It’s a number in JavaScript, derived by dividing negative number by

zero.6. What boolean operators does JavaScript support? - &&, || and !7. What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124.8. How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string,

it’s concatenation, so 78 is the result.9. What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach.10. How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {};11. How do you assign object properties? - obj["age"] = 17 or obj.age = 17.12. What’s a way to append a value to an array? - arr[arr.length] = value;13. What is this keyword? - It refers to the current object.

JSP Interview Questions and Answers

Page 30: Basic Java Interview Questions

What is a JSP and what is it used for?Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components:1. the tag handler class that defines the tag\'s behavior2. the tag library descriptor file that maps the XML element names to the tag implementations 3. the JSP file that uses the tag library When the first two components are done, you can use the tag by using taglib directive: <%@ taglib uri="xxx.tld" prefix="..." %>Then you are ready to use the tags you defined. Let's say the tag prefix is test: MyJSPTag or JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class. 

<%=identifier.getclassField() %>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.

What are the two kinds of comments in JSP and what's the difference between them ?<%-- JSP Comment --%><!-- HTML Comment -->

What is JSP technology?

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

What is JSP page? A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

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 

Page 31: Basic Java Interview Questions

--session --application --out --config --page --exception

How many JSP scripting elements and what are they? There are three scripting language elements:--declarations --scriptlets --expressions

Why are JSP pages the preferred API for creating a web-based client program? Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

Is JSP technology extensible? YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Can we use the constructor, instead of init(), to initialize servlet? Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

How can a servlet refresh automatically if some new data has entered the database? You can use a client-side Refresh or Server Push.

The code in a finally clause will never fail to execute, right?Using System.exit(1); in try block will not allow finally code to execute.How many messaging models do JMS provide for and what are they? JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.What information is needed to create a TCP Socket? The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.What Class.forName will do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.How to Retrieve Warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

Page 32: Basic Java Interview Questions

SQLWarning warning = stmt.getWarnings();if (warning != null){while (warning != null){System.out.println(\"Message: \" + warning.getMessage());System.out.println(\"SQLState: \" + warning.getSQLState());System.out.print(\"Vendor error code: \");System.out.println(warning.getErrorCode());warning = warning.getNextWarning();}}How many JSP scripting elements are there and what are they? There are three scripting language elements: declarations, scriptlets, expressions.In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.What are stored procedures? How is it useful? A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements every time a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.How do I include static files within a JSP page? Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.Why does JComponent have add() and remove() methods but Component does not? because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.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.How do you restrict page errors display in the JSP page? You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage="error.jsp")in your jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it will automatically call the error page.

Page 33: Basic Java Interview Questions

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. hello1.jsp hello2.jsp hello2.jsp <%Integer i= (Integer )session.getValue("num");out.println("Num value in session is "+i.intValue());What JSP lifecycle methods can I override? You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy(). The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:How do I perform browser redirection from a JSP page? You can use the response implicit object to redirect the browser to a different resource, as:response.sendRedirect("http://www.exforsys.com/path/error.html");You can also physically alter the Location HTTP header attribute, as shown below:You can also use the: Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using >How does JSP handle run-time exceptions? You can use the errorPage attribute of the page directive to have uncaught runtime exceptions automatically forwarded to an error processing page.For example:redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request

Page 34: Basic Java Interview Questions

processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: the 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.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: --%> You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example: Of course, you can also use comments supported by your JSP scripting language within your scriptlets.Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as "passed-by-value", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The "pass-byreference" can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it.How can I implement a thread-safe JSP page? You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page. 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: Another Example: file1.jsp: file2.jsp <%test(out);% >Can I stop JSP execution while in the midst of processing a request? Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (assuming Java is your scripting language) is to use the return statement when you want to terminate further processing.Can a JSP page process HTML FORM data? Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like

Page 35: Basic Java Interview Questions

doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as.Is there a way to reference the "this" variable within a JSP page? Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the Servlet generated by the JSP page.How do you pass control from one JSP page to another? Use the following ways to pass control of a request from one servlet to another or one jsp to another. The RequestDispatcher object ‘s forward method to pass the control. The response.sendRedirect methodIs 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 JSPengine 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.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. 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);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:getPropertyname="fBean" property="name" / jsp:getProperty name="fBean" property="addr"

Page 36: Basic Java Interview Questions

/ jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean"property="personalizationInfo" /Can you make use of a ServletOutputStream object from within a JSP page? No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as: How do I include static files within a JSP page?Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax: < % @ include file="copyright.html" % > Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request. 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 JSPengine. In any case, your new super class 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 super class also needs to do the following: The service() method has to invoke the _jspService() methodThe init() method has to invoke the jspInit() methodThe 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 super class has been developed, you can have your JSP extend it as follows:Can a JSP page instantiate a serialized bean?No problem! The use Bean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example: A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INFjspbeans directory for it to be located by the JSP engine.What is JSP? Let's consider the answer to that from two different perspectives: that of an HTML designer and that of a Java programmer. If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the ability to seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamic content, which is embedded within the other HTML/XML content you author. Even better, JSP technology provides the means by which programmers can create new HTML/XML tags and JavaBeans components, which provide new features for HTML designers without those designers needing to learn how to program. Note: A common misconception is that Java code embedded in a JSP page is transmitted with the HTML and executed by the user agent (such as a browser). This is not the case. A JSP page is translated into a Java servlet and executed on the server. JSP statements embedded in the JSP page become part of the

Page 37: Basic Java Interview Questions

servlet generated from the JSP page. The resulting servlet is executed on the server. It is never visible to the user agent. If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writing servlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTML pages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it. Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSP code is executed, and the results are returned to the user.How do I mix JSP and SSI #include? Answer 1If you're just including raw HTML, use the #include directive as usual inside your .jsp file. But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use The is used for including non-JSP files. Answer 2 If you're just including raw HTML, use the #include directive as usual inside your .jsp file.<!--#include file="data.inc"-->But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. Ronel Sumibcay ([email protected]) says: If your data.inc file contains jsp code you will have to use<%@ vinclude="data.inc" %>The <!--#include file="data.inc"--> is used for including non-JSP files.How do I mix JSP and SSI #include? What is the difference between include directive & jsp:include action? Difference between include directive and1. provides the benefits of automatic recompliation,smaller class size ,since the code corresponding to the included page is not present in the servlet for every included jsp page and option of specifying the additional request parameter.2.The also supports the use of request time attributes values for dynamically specifying included page which directive does not.3.the include directive can only incorporate contents from a static document.4. can be used to include dynamically generated output e.g.. from servlets.5.include directive offers the option of sharing local variables, better run time efficiency.6.Because the include directive is processed during translation and compilation, it does not impose any restrictions on output buffering.How do you prevent the Creation of a Session in a JSP Page and why? What is the difference between include directive & jsp:include action? By default, a JSP page will automatically create a session for the request if one does not exist. However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions. 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

Page 38: Basic Java Interview Questions

it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. value=""/ >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:How do you connect to the database from JSP? A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets. Further then you can use the resultset object "res" to read data in the following way. What is the page directive is used to prevent a JSP page from automatically creating a session? <%@ page session="false">How do you delete a Cookie within a JSP? Cookie mycook = new Cookie("name","value");response.addCookie(mycook);Cookie killmycook = new Cookie("mycook","value");killmycook.setMaxAge(0);killmycook.setPath("/");killmycook.addCookie(killmycook);Can we implement an interface in a JSP? NoWhat is the difference between ServletContext and PageContext? ServletContext: Gives the information about the containerPageContext: Gives the information about the RequestWhat is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()? request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.How to pass information from JSP to included JSP? Using <%jsp:param> tag.How is JSP include directive different from JSP include action. ?When a JSP include directive is used, the included file's code is added into the added JSP page at page translation time, this happens before the JSP page is translated into a servlet. While if any page is included using action tag, the page's output is returned back to the added page. This happens at runtime.Can we override the jspInit(), _jspService() and jspDestroy() methods? We can override jspinit() and jspDestroy() methods but not _jspService().Why is _jspService() method starting with an '_' while other life cycle methods do not? _jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.What happens when a page is statically included in another JSP page? An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc.) in the current page. This process of including a file is also called as static include.A JSP page, include.jsp, has a instance variable "int a", now this page is statically included in another JSP page, index.jsp, which has a instance variable "int a" declared. What happens when the index.jsp page is requested by the client? Compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error.

Page 39: Basic Java Interview Questions

Can you override jspInit() method? If yes, In which cases?ye, we can. We do it usually when we need to initialize any members which are to be available for a servlet/JSP throughout its lifetime.What is the difference between directive include and jsp include? <%@ include> : Used to include static resources during translation time. : Used to include dynamic content or static content during runtime.What is the difference between RequestDispatcher and sendRedirect? RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.How does JSP handle runtime exceptions? Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.How can my application get to know when a HttpSession is removed? Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.Create an instance of that class and put that instance in HttpSession. What Class.forName will do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.How to Retrieve Warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

SQLWarning warning = stmt.getWarnings();if (warning != null){while (warning != null){System.out.println(\"Message: \" + warning.getMessage());System.out.println(\"SQLState: \" + warning.getSQLState());System.out.print(\"Vendor error code: \");System.out.println(warning.getErrorCode());warning = warning.getNextWarning();}}How many JSP scripting elements are there and what are they? There are three scripting language elements: declarations, scriptlets, expressions.In the Servlet 2.4 specification SingleThreadModel has been deprecated, why? Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.Is JSP technology extensible? YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Page 40: Basic Java Interview Questions

Can we use the constructor, instead of init(), to initialize servlet? Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.How can a servlet refresh automatically if some new data has entered the database? You can use a client-side Refresh or Server Push.The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute.How many messaging models do JMS provide for and what are they? JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

JDBC Interview Questions and Answers

What is JDBC?JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a layer of abstraction that allows users to choose between databases. It allows you to change to a different database engine and to write to a single API. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.

What's the JDBC 3.0 API? The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including scrollable result sets and the SQL:1999 data types. JDBC (Java Database Connectivity) is the standard for communication between a Java application and a relational database. The JDBC API is released in two versions; JDBC version 1.22 (released with JDK 1.1.X in package java.sql) and version 2.0 (released with Java platform 2 in packages java.sql and javax.sql). It is a simple and powerful largely database-independent way of extracting and inserting data to or from any database.

Does the JDBC-ODBC Bridge support the new features in the JDBC 3.0 API? The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.

Can the JDBC-ODBC Bridge be used with applets? Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration. Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.

Page 41: Basic Java Interview Questions

How do I start debugging problems related to the JDBC API? A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations. If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)

What is new in JDBC 2.0? With the JDBC 2.0 API, you will be able to do the following: Scroll forward and backward in a result set or move to a specific row (TYPE_SCROLL_SENSITIVE,previous(), last(), absolute(), relative(), etc.) Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.) Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch()) Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.

How to move the cursor in scrollable resultset ?

a. create a scrollable ResultSet object. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSet srs = stmt.executeQuery("SELECT COLUMN_1, COLUMN_2 FROM TABLE_NAME");

b. use a built in methods like afterLast(), previous(), beforeFirst(), etc. to scroll the resultset. srs.afterLast();while (srs.previous()) {String name = srs.getString("COLUMN_1");float salary = srs.getFloat("COLUMN_2");//...

c. to find a specific row, use absolute(), relative() methods. srs.absolute(4); // cursor is on the fourth rowint rowNum = srs.getRow(); // rowNum should be 4srs.relative(-3); int rowNum = srs.getRow(); // rowNum should be 1srs.relative(2); int rowNum = srs.getRow(); // rowNum should be 3

d. use isFirst(), isLast(), isBeforeFirst(), isAfterLast() methods to check boundary status.

How to update a resultset programmatically? a. create a scrollable and updatable ResultSet object. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);ResultSet uprs = stmt.executeQuery("SELECT COLUMN_1, COLUMN_2 FROM TABLE_NAME");

Page 42: Basic Java Interview Questions

b. move the cursor to the specific position and use related method to update data and then, call updateRow() method. uprs.last();uprs.updateFloat("COLUMN_2", 25.55);//update last row's datauprs.updateRow();//don't miss this method, otherwise, // the data will be lost.

How can I use the JDBC API to access a desktop database like Microsoft Access over the network? Most desktop databases currently require a JDBC solution that uses ODBC underneath. This is because the vendors of these database products haven't implemented all-Java JDBC drivers. The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of available JDBC drivers. The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge, however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is free.

Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge? Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in functionality between ODBC drivers, the functionality of the bridge may be affected. The bridge works with popular PC databases, such as Microsoft Access and FoxPro.

What causes the "No suitable driver" error? "No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are specifying is not being recognized by your JDBC driver. In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your configuration to be sure that the shared libraries are accessible to the Bridge.

Why isn't the java.sql.DriverManager class being found? This problem can be caused by running a JDBC applet in a browser that supports the JDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBC API, so the DriverManager class typically isn't found by the Java virtual machine running in the browser. Here's a solution that doesn't require any additional configuration of your web clients. Remember that classes in the java.* packages cannot be downloaded by most browsers for security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of the java.sql.* classes that have been renamed to jdbc.sql.*, along with a version of their driver that uses these modified classes. If you import jdbc.sql.* in your applet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your applet's codebase, then all of the JDBC classes needed by the applet can be downloaded by the browser at run time, including the DriverManager class. This solution will allow your applet to work in any client browser that supports the JDK 1.0.2. Your applet will also work in browsers that support the JDK 1.1, although you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution outlined here is just an example and that other solutions are possible.

Page 43: Basic Java Interview Questions

How to insert and delete a row programmatically? (new feature in JDBC 2.0)Make sure the resultset is updatable.

1. move the cursor to the specific position.

uprs.moveToCurrentRow(); 

2. set value for each column.

uprs.moveToInsertRow();//to set up for insertuprs.updateString("col1" "strvalue");uprs.updateInt("col2", 5);...

3. call inserRow() method to finish the row insert process.

uprs.insertRow();

To delete a row: move to the specific position and call deleteRow() method:

uprs.absolute(5);uprs.deleteRow();//delete row 5 

To see the changes call refreshRow();

uprs.refreshRow();

What are the two major components of JDBC? One implementation interface for database manufacturers, the other implementation interface for application and applet writers.

What is JDBC Driver interface? The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX method for each column? The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the cost of a function call in any scenario. We welcome input from developers on this issue.

What are the common tasks of JDBC?

Create an instance of a JDBC driver or load JDBC drivers through jdbc.driversRegister a driver Specify a database Open a database connectionSubmit a query

Page 44: Basic Java Interview Questions

Receive results Process results

Why does the ODBC driver manager return 'Data source name not found and no default driver specified Vendor: 0' This type of error occurs during an attempt to connect to a database with the bridge. First, note that the error is coming from the ODBC driver manager. This indicates that the bridge-which is a normal ODBC client-has successfully called ODBC, so the problem isn't due to native libraries not being present. In this case, it appears that the error is due to the fact that an ODBC DSN (data source name) needs to be configured on the client machine. Developers often forget to do this, thinking that the bridge will magically find the DSN they configured on their remote server machine

How to use JDBC to connect Microsoft Access? There is a specific tutorial at javacamp.org. Check it out.

What are four types of JDBC driver? Type 1 Drivers 

Bridge drivers such as the jdbc-odbc bridge. They rely on an intermediary such as ODBC to transfer the SQL calls to the database and also often rely on native code. It is not a serious solution for an application Type 2 Drivers 

Use the existing database API to communicate with the database on the client. Faster than Type 1, but need native code and require additional permissions to work in an applet. Client machine requires software to run. Type 3 Drivers 

JDBC-Net pure Java driver. It translates JDBC calls to a DBMS-independent network protocol, which is then translated to a DBMS protocol by a server. Flexible. Pure Java and no native code. Type 4 Drivers 

Native-protocol pure Java driver. It converts JDBC calls directly into the network protocol used by DBMSs. This allows a direct call from the client machine to the DBMS server. It doesn't need any special native code on the client machine. Recommended by Sun's tutorial, driver type 1 and 2 are interim solutions where direct pure Java drivers are not yet available. Driver type 3 and 4 are the preferred way to access databases using the JDBC API, because they offer all the advantages of Java technology, including automatic installation. For more info, visit Sun JDBC page

Which type of JDBC driver is the fastest one? JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the jdbc calls into vendor specific protocol calls and it directly interacts with the database.

Are all the required JDBC drivers to establish connectivity to my database part of the JDK? No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are considering bundling JDBC technology- enabled drivers in the future.

Is the JDBC-ODBC Bridge multi-threaded? No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-

Page 45: Basic Java Interview Questions

ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.

Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

What is the query used to display all tables names in SQL Server (Query analyzer)? select * from information_schema.tables

Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next works? You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.

How can I retrieve a String or other object type without creating a new object each time? Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object. We are studying this issue to see if it is an area in which the JDBC API should be improved. Stay tuned, and please send us any comments you have on this question.

How many types of JDBC Drivers are present and what are they? There are 4 types of JDBC DriversType 1: JDBC-ODBC Bridge DriverType 2: Native API Partly Java DriverType 3: Network protocol DriverType 4: JDBC Net pure Java Driver

What is the fastest type of JDBC driver? JDBC driver performance will depend on a number of issues:(a) the quality of the driver code,(b) the size of the driver code,(c) the database server and its load,(d) network topology,(e) the number of times your request is translated to a different API.In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).

There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of rows in a result set? No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.

Page 46: Basic Java Interview Questions

I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, Standard Edition (formerly JDK 1.2). I'm a beginner with the JDBC API, and I would like to start with the Bridge. How do I do it? The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.

If I use the JDBC API, do I have to use ODBC underneath? No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.

Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a database? You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.

What is the best way to generate a universally unique object ID? Do I need to use an external resource like a file or database, or can I do it all in memory? 1: Unique down to the millisecond. Digits 1-8 are the hex encoded lower 32 bits of the System.currentTimeMillis() call. 2: Unique across a cluster. Digits 9-16 are the encoded representation of the 32 bit integer of the underlying IP address. 3: Unique down to the object in a JVM. Digits 17-24 are the hex representation of the call to System.identityHashCode(), which is guaranteed to return distinct integers for distinct objects within a JVM. 4: Unique within an object within a millisecond. Finally digits 25-32 represent a random 32 bit integer generated on every method call using the cryptographically strong java.security.SecureRandom class. 

Answer1There are two reasons to use the random number instead of incrementing your last. 1. The number would be predictable and, depending on what this is used for, you could be opening up a potential security issue. This is why ProcessIDs are randomized on some OSes (AIX for one). 2. You must synchronize on that counter to guarantee that your number isn't reused. Your random number generator need not be synchronized, (though its implementation may be). 

Answer21) If your using Oracle You can create a sequence ,by which you can generate unique primary key or universal primary key. 2) you can generate by using random numbers but you may have to check the range and check for unique id. ie random number generate 0.0 to 1.0 u may have to make some logic which suits your unique id 3) Set the maximum value into an XML file and read that file at the time of loading your application from xml .

What happens when I close a Connection application obtained from a connection Pool? How does a connection pool maintain the Connections that I had closed through the application? Answer1It is the magic of polymorphism, and of Java interface vs. implementation types. Two objects can both be

Page 47: Basic Java Interview Questions

"instanceof" the same interface type, even though they are not of the same implementation type. When you call "getConnection()" on a pooled connection cache manager object, you get a "logical" connection, something which implements the java.sql.Connection interface. But it is not the same implementation type as you would get for your Connection, if you directly called getConnection() from a (non-pooled/non-cached) datasource. So the "close()" that you invoke on the "logical" Connection is not the same "close()" method as the one on the actual underlying "physical" connection hidden by the pool cache manager. The close() method of the "logical" connection object, while it satisfies the method signature of close() in the java.sql.Connection interface, does not actually close the underlying physical connection. 

Answer2Typically a connection pool keeps the active/in-use connections in a hashtable or other Collection mechanism. I've seen some that use one stack for ready-for-use, one stack for in-use. When close() is called, whatever the mechanism for indicating inuse/ready-for-use, that connection is either returned to the pool for ready-for-use or else physically closed. Connections pools should have a minimum number of connections open. Any that are closing where the minimum are already available should be physically closed. Some connection pools periodically test their connections to see if queries work on the ready-for-use connections or they may test that on the close() method before returning to the ready-for-use pool.

How do I insert a .jpg into a mySQL data base? I have tried inserting the file as byte[], but I recieve an error message stating that the syntax is incorrect.Binary data is stored and retrieved from the database usingstreams in connection with prepared statements and resultsets.This minimal application stores an image file in the database, then it retrieves the binary data from the database and converts it back to an image.

import java.sql.*;import java.io.*;import java.awt.*;import java.awt.Image;

/*** Storing and retrieving images from a MySQL database*/public class StoreBinary {private static String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";private Statement stmt = null;private Connection conn = null;

public StoreBinary() {}/*** Strips path prefix from filenames* @param fileName* @return the base filename*/public static String getBaseName(String fileName) {int ix=fileName.lastIndexOf("\\");if (ix < 0) return fileName;return fileName.substring(ix+1);

Page 48: Basic Java Interview Questions

}/*** Store a binary (image) file in the database using a* prepared statement.* @param fileName* @return true if the operation succeeds* @throws Exception*/public boolean storeImageFile(String fileName) throws Exception {if (!connect("test", "root", "")) {return false;}

FileInputStream in = new FileInputStream(fileName);int len=in.available();String baseName=StoreBinary.getBaseName(fileName);PreparedStatement pStmt = conn.prepareStatement("insert into image_tab values (?,?,?)");pStmt.setString(1, baseName);pStmt.setInt(2,len);pStmt.setBinaryStream(3, in, len);pStmt.executeUpdate();in.close();System.out.println("Stored: "+baseName+", length: "+len);return true;}/*** Retrieve the biary file data from the DB and convert it to an image* @param fileName* @return* @throws Exception*/public Image getImageFile(String fileName) throws Exception {String baseName=StoreBinary.getBaseName(fileName);

ResultSet rs=stmt.executeQuery("select * from image_tab where image_name='"+baseName+"'");

if (!rs.next()) {System.out.println("Image:"+baseName+" not found");return null;}int len=rs.getInt(2);

byte [] b=new byte[len];InputStream in = rs.getBinaryStream(3);int n=in.read(b);System.out.println("n: "+n);in.close();Image img=Toolkit.getDefaultToolkit().createImage(b);System.out.println("Image: "+baseName+" retrieved ok, size: "+len);

Page 49: Basic Java Interview Questions

return img;}/*** Establish database connection* @param dbName* @param dbUser* @param dbPassword* @return true if the operation succeeds*/public boolean connect(String dbName, String dbUser, String dbPassword) {try {Class.forName(driverName);}catch (ClassNotFoundException ex) {ex.printStackTrace();return false;}try {conn = DriverManager.getConnection("jdbc:odbc:" + dbName,dbUser,dbPassword);stmt = conn.createStatement();}catch (SQLException ex1) {ex1.printStackTrace();return false;}return true;}

/******************************************* MAIN stub driver for testing the class.*/public static void main(String[] args) {String fileName="c:\\tmp\\f128.jpg";StoreBinary sb = new StoreBinary();try {if (sb.storeImageFile(fileName)) {// stored ok, now get it back againImage img=sb.getImageFile(fileName);}}catch (Exception ex) {ex.printStackTrace();}}}

How can I know when I reach the last record in a table, since JDBC doesn't provide an EOF method? Answer1

Page 50: Basic Java Interview Questions

You can use last() method of java.sql.ResultSet, if you make it scrollable. You can also use isLast() as you are reading the ResultSet. One thing to keep in mind, though, is that both methods tell you that you have reached the end of the current ResultSet, not necessarily the end of the table. SQL and RDBMSes make no guarantees about the order of rows, even from sequential SELECTs, unless you specifically use ORDER BY. Even then, that doesn't necessarily tell you the order of data in the table. 

Answer2Assuming you mean ResultSet instead of Table, the usual idiom for iterating over a forward only resultset is: ResultSet rs=statement.executeQuery(...);while (rs.next()) {// Manipulate row here}

Where can I find info, frameworks and example source for writing a JDBC driver? There a several drivers with source available, like MM.MySQL, SimpleText Database, FreeTDS, and RmiJdbc. There is at least one free framework, the jxDBCon-Open Source JDBC driver framework. Any driver writer should also review For Driver Writers.

How can I create a custom RowSetMetaData object from scratch? One unfortunate aspect of RowSetMetaData for custom versions is that it is an interface. This means that implementations almost have to be proprietary. The JDBC RowSet package is the most commonly available and offers the sun.jdbc.rowset.RowSetMetaDataImpl class. After instantiation, any of the RowSetMetaData setter methods may be used. The bare minimum needed for a RowSet to function is to set the Column Count for a row and the Column Types for each column in the row. For a working code example that includes a custom RowSetMetaData,

How does a custom RowSetReader get called from a CachedRowSet?The Reader must be registered with the CachedRowSet using CachedRowSet.setReader(javax.sql.RowSetReader reader). Once that is done, a call to CachedRowSet.execute() will, among other things, invoke the readData method.

How do I implement a RowSetReader? I want to populate a CachedRowSet myself and the documents specify that a RowSetReader should be used. The single method accepts a RowSetInternal caller and returns void. What can I do in the readData method? "It can be implemented in a wide variety of ways..." and is pretty vague about what can actually be done. In general, readData() would obtain or create the data to be loaded, then use CachedRowSet methods to do the actual loading. This would usually mean inserting rows, so the code would move to the insert row, set the column data and insert rows. Then the cursor must be set to to the appropriate position.

How can I instantiate and load a new CachedRowSet object from a non-JDBC source? The basics are:* Create an object that implements javax.sql.RowSetReader, which loads the data.* Instantiate a CachedRowset object.* Set the CachedRowset's reader to the reader object previously created.* Invoke CachedRowset.execute().

Note that a RowSetMetaData object must be created, set up with a description of the data, and attached to the CachedRowset before loading the actual data. 

Page 51: Basic Java Interview Questions

The following code works with the Early Access JDBC RowSet download available from the Java Developer Connection and is an expansion of one of the examples: // Independent data source CachedRowSet Exampleimport java.sql.*;import javax.sql.*;import sun.jdbc.rowset.*;

public class RowSetEx1 implements RowSetReader{CachedRowSet crs;int iCol2;RowSetMetaDataImpl rsmdi;String sCol1, sCol3;

public RowSetEx1(){try {crs = new CachedRowSet();crs.setReader(this);crs.execute(); // load from reader

System.out.println("Fetching from RowSet...");while(crs.next()) {showTheData();} // end while next

if(crs.isAfterLast() == true) {System.out.println("We have reached the end");System.out.println("crs row: " + crs.getRow());}

System.out.println("And now backwards...");

while(crs.previous()) {showTheData();} // end while previous

if(crs.isBeforeFirst() == true) { System.out.println("We have reached the start"); 

Page 52: Basic Java Interview Questions

}

crs.first();if(crs.isFirst() == true){ System.out.println("We have moved to first"); }

System.out.println("crs row: " + crs.getRow());

if(crs.isBeforeFirst() == false){ System.out.println("We aren't before the first row."); }

crs.last();if(crs.isLast() == true){ System.out.println("...and now we have moved to the last"); }

System.out.println("crs row: " + crs.getRow());

if(crs.isAfterLast() == false){System.out.println("we aren't after the last.");}

} // end trycatch (SQLException ex) {System.err.println("SQLException: " + ex.getMessage());}

} // end constructor

public void showTheData() throws SQLException{sCol1 = crs.getString(1);if(crs.wasNull() == false) { System.out.println("sCol1: " + sCol1); } else { System.out.println("sCol1 is null"); }

iCol2 = crs.getInt(2);if (crs.wasNull() == false) { System.out.println("iCol2: " + iCol2); } 

Page 53: Basic Java Interview Questions

else { System.out.println("iCol2 is null"); } 

sCol3 = crs.getString(3);if (crs.wasNull() == false) { System.out.println("sCol3: " + sCol3 + "\n" ); } else { System.out.println("sCol3 is null\n"); }

} // end showTheData

// RowSetReader implementationpublic void readData(RowSetInternal caller) throws SQLException{rsmdi = new RowSetMetaDataImpl();rsmdi.setColumnCount(3);rsmdi.setColumnType(1, Types.VARCHAR);rsmdi.setColumnType(2, Types.INTEGER);rsmdi.setColumnType(3, Types.VARCHAR);crs.setMetaData( rsmdi );

crs.moveToInsertRow();

crs.updateString( 1, "StringCol11" );crs.updateInt( 2, 1 );crs.updateString( 3, "StringCol31" );crs.insertRow();

crs.updateString( 1, "StringCol12" );crs.updateInt( 2, 2 );crs.updateString( 3, "StringCol32" );crs.insertRow();

crs.moveToCurrentRow();crs.beforeFirst();

} // end readData

public static void main(String args[]){new RowSetEx1();}

} // end class RowSetEx1

Page 54: Basic Java Interview Questions

Can I set up a connection pool with multiple user IDs? The single ID we are forced to use causes problems when debugging the DBMS.Since the Connection interface ( and the underlying DBMS ) requires a specific user and password, there's not much of a way around this in a pool. While you could create a different Connection for each user, most of the rationale for a pool would then be gone. Debugging is only one of several issues that arise when using pools. However, for debugging, at least a couple of other methods come to mind. One is to log executed statements and times, which should allow you to backtrack to the user. Another method that also maintains a trail of modifications is to include user and timestamp as standard columns in your tables. In this last case, you would collect a separate user value in your program.

How can I protect my database password ? I'm writing a client-side java application that will access a database over the internet. I have concerns about the security of the database passwords. The client will have access in one way or another to the class files, where the connection string to the database, including user and password, is stored in as plain text. What can I do to protect my passwords? This is a very common question. Conclusion: JAD decompiles things easily and obfuscation would not help you. But you'd have the same problem with C/C++ because the connect string would still be visible in the executable. SSL JDBC network drivers fix the password sniffing problem (in MySQL 4.0), but not the decompile problem. If you have a servlet container on the web server, I would go that route (see other discussion above) then you could at least keep people from reading/destroying your mysql database. Make sure you use database security to limit that app user to the minimum tables that they need, then at least hackers will not be able to reconfigure your DBMS engine. Aside from encryption issues over the internet, it seems to me that it is bad practice to embed user ID and password into program code. One could generally see the text even without decompilation in almost any language. This would be appropriate only to a read-only database meant to be open to the world. Normally one would either force the user to enter the information or keep it in a properties file.

Detecting Duplicate Keys I have a program that inserts rows in a table. My table has a column 'Name' that has a unique constraint. If the user attempts to insert a duplicate name into the table, I want to display an error message by processing the error code from the database. How can I capture this error code in a Java program? A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad. You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000.

What driver should I use for scalable Oracle JDBC applications? Sun recommends using the thin ( type 4 ) driver.* On single processor machines to avoid JNI overhead.* On multiple processor machines, especially running Solaris, to avoid synchronization bottlenecks.

Page 55: Basic Java Interview Questions

Can you scroll a result set returned from a stored procedure? I am returning a result set from a stored procedure with type SQLRPGLE but once I reach the end of the result set it does not allow repositioning. Is it possible to scroll this result set? A CallableStatement is no different than other Statements in regard to whether related ResultSets are scrollable. You should create the CallableStatement using Connection.prepareCall(String sql, int resultSetType, int resultSetConcurrency).

How do I write Greek ( or other non-ASCII/8859-1 ) characters to a database? From the standard JDBC perspective, there is no difference between ASCII/8859-1 characters and those above 255 ( hex FF ). The reason for that is that all Java characters are in Unicode ( unless you perform/request special encoding ). Implicit in that statement is the presumption that the data store can handle characters outside the hex FF range or interprets different character sets appropriately. That means either:

* The OS, application and database use the same code page and character set. For example, a Greek version of NT with the DBMS set to the default OS encoding.* The DBMS has I18N support for Greek ( or other language ), regardless of OS encoding. This has been the most common for production quality databases, although support varies. Particular DBMSes may allow setting the encoding/code page/CCSID at the database, table or even column level. There is no particular standard for provided support or methods of setting the encoding. You have to check the DBMS documentation and set up the table properly.* The DBMS has I18N support in the form of Unicode capability. This would handle any Unicode characters and therefore any language defined in the Unicode standard. Again, set up is proprietary.

How can I insert images into a Mysql database? This code snippet shows the basics:

File file = new File(fPICTURE);FileInputStream fis = new FileInputStream(file);PreparedStatement ps = ConrsIn.prepareStatement("insert into dbPICTURE values (?,?)");

// ***use as many ??? as you need to insert in the exact order*** ps.setString(1,file.getName());ps.setBinaryStream(2,fis,(int)file.length());ps.close();fis.close();

Is possible to open a connection to a database with exclusive mode with JDBC? I think you mean "lock a table in exclusive mode". You cannot open a connection with exclusive mode. Depending on your database engine, you can lock tables or rows in exclusive mode. In Oracle you would create a statement st and run st.execute("lock table mytable in exclusive mode"); Then when you are finished with the table, execute the commit to unlock the table. Mysql, Informix and SQLServer all have a slightly different syntax for this function, so you'll have to change it depending on your database. But they can all be done with execute().

What are the standard isolation levels defined by JDBC? The values are defined in the class java.sql.Connection and are:* TRANSACTION_NONE

Page 56: Basic Java Interview Questions

* TRANSACTION_READ_COMMITTED* TRANSACTION_READ_UNCOMMITTED* TRANSACTION_REPEATABLE_READ* TRANSACTION_SERIALIZABLE

Update fails without blank padding. Although a particular row is present in the database for a given key, executeUpdate() shows 0 rows updated and, in fact, the table is not updated. If I pad the Key with spaces for the column length (e.g. if the key column is 20 characters long, and key is msgID, length 6, I pad it with 14 spaces), the update then works!!! Is there any solution to this problem without padding? In the SQL standard, CHAR is a fixed length data type. In many DBMSes ( but not all), that means that for a WHERE clause to match, every character must match, including size and trailing blanks. As Alessandro indicates, defining CHAR columns to be VARCHAR is the most general answer.

J2EE interview questions and answers

1. What makes J2EE suitable for distributed multitiered Applications?- The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are: Client-tier components run on the client machine. Web-tier components run on the J2EE server. Business-tier components run on the J2EE server. Enterprise information system (EIS)-tier software runs on the EIS server.

2. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.

3. What are the components of J2EE application?- A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:

A. Application clients and applets are client components.B. Java Servlet and JavaServer Pages technology components are web components.C. Enterprise JavaBeans components (enterprise beans) are business components.D. Resource adapter components provided by EIS and tool vendors.

What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logicthat solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a

Page 57: Basic Java Interview Questions

graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications.Enterprise beans and their container run on the J2EE server.What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings.What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.What are types of J2EE clients? - Following are the types of J2EE clients: Applets Application clients Java Web Start-enabled rich clients, powered by Java Web Start technology.

Page 58: Basic Java Interview Questions

Wireless clients, based on Mobile Information Device Profile (MIDP) technology.What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizationsfor an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming anddirectory services such as LDAP, NDS, DNS, and NIS.What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.

Page 59: Basic Java Interview Questions

How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.

J2ME Interview Questions and Answers

What is J2ME ?Java 2, Micro Edition is a group of specifications and technologies that pertain to Java on small devices. The J2ME moniker covers a wide range of devices, from pagers and mobile telephones through set-top boxes and car navigation systems. The J2ME world is divided into configurations and profiles, specifications that describe a Java environment for a specific class of device.

What is J2ME WTK ?The J2ME Wireless Toolkit is a set of tools that provides developers with an emulation environment, documentation and examples for developing Java applications for small devices. The J2ME WTK is based on the Connected Limited Device Configuration (CLDC) and Mobile Information Device Profile (MIDP) reference implementations, and can be tightly integrated with Forte for Java

What is 802.11 ?802.11 is a group of specifications for wireless networks developed by the Institute of Electrical and Electronics Engineers (IEEE). 802.11 uses the Ethernet protocol and CSMA/CA (carrier sense multiple access with collision avoidance) for path sharing.

What is API ?An Application Programming Interface (API) is a set of classes that you can use in your own application. Sometimes called libraries or modules, APIs enable you to write an application without reinventing common pieces of code. For example, a networking API is something your application can use to make network connections, without your ever having to understand the underlying code. 5. What is AMPS 

Advanced Mobile Phone Service (AMPS) is a first-generation analog, circuit-switched cellular phone network. Originally operating in the 800 MHz band, service was later expanded to include transmissions in the 1900 MHz band, the VHF range in which most wireless carriers operate. Because AMPS uses analog signals, it cannot transmit digital signals and cannot transport data packets without assistance from newer technologies such as TDMA and CDMA.

What is CDC ?

The Connected Device Configuration (CDC) is a specification for a J2ME configuration. Conceptually, CDC deals with devices with more memory and processing power than CLDC; it is for devices with an always-on network connection and a minimum of 2 MB of memory available for the Java system.

Page 60: Basic Java Interview Questions

What is CDMA ?Code-Division Multiple Access (CDMA) is a cellular technology widely used in North America. There are currently three CDMA standards: CDMA One, CDMA2000 and W-CDMA. CDMA technology uses UHF 800Mhz-1.9Ghz frequencies and bandwidth ranges from 115Kbs to 2Mbps.

What is CDMA One ?Also know as IS-95, CDMA One is a 2nd generation wireless technology. Supports speeds from 14.4Kbps to 115K bps.

What is CDMA2000 ?Also known as IS-136, CDMA2000 is a 3rd generation wireless technology. Supports speeds ranging from 144Kbps to 2Mbps.

What is CDPD ?Developed by Nortel Networks, Cellular Digital Packet Data (CDPD) is an open standard for supporting wireless Internet access from cellular devices. CDPD also supports Multicast, which allows content providers to efficiently broadcast information to many devices at the same time.

What is cHTML ?Compact HTML (cHTML) is a subset of HTML which is designed for small devices. The major features of HTML that are excluded from cHTML are: JPEG image, Table, Image map, Multiple character fonts and styles, Background color and image, Frame and Style sheet.

What is CLDC ?The Connected, Limited Device Configuration (CLDC) is a specification for a J2ME configuration. The CLDC is for devices with less than 512 KB or RAM available for the Java system and an intermittent (limited) network connection. It specifies a stripped-down Java virtual machine1 called the KVM as well as several APIs for fundamental application services. Three packages are minimalist versions of the J2SE java.lang, java.io, and java.util packages. A fourth package, javax.microedition.io, implements the Generic Connection Framework, a generalized API for making network connections.

What is configuration ?In J2ME, a configuration defines the minimum Java runtime environment for a family of devices: the combination of a Java virtual machine (either the standard J2SE virtual machine or a much more limited version called the CLDC VM) and a core set of APIs. CDC and CLDC are configurations. See also profile, optional package.

What is CVM ?The Compact Virtual Machine (CVM) is an optimized Java virtual machine1 (JVM) that is used by the CDC.

What is Deck ?A deck is a collection of one or more WML cards that can be downloaded, to a mobile phone, as a single entity.

What is EDGE ?Enhanced Data GSM Environment (EDGE) is a new, faster version of GSM. EDGE is designed to support transfer rates up to 384Kbps and enable the delivery of video and other high-bandwidth applications. EDGE is the result of a joint effort between TDMA operators, vendors and carriers and the GSM Alliance.

Page 61: Basic Java Interview Questions

What is ETSI ?The European Telecommunications Standards Institute (ETSI) is a non-profit organization that establishes telecommunications standards for Europe.

What is FDMA ?Frequency-division multiple-access (FDMA) is a mechanism for sharing a radio frequency band among multiple users by dividing it into a number of smaller bands.

What is Foundation Profile ?The Foundation Profile is a J2ME profile specification that builds on CDC. It adds additional classes and interfaces to the CDC APIs but does not go so far as to specify user interface APIs, persistent storage, or application life cycle. Other J2ME profiles build on the CDC/Foundation combination: for example, the Personal Profile and the RMI Profile both build on the Foundation Profile.

What is Generic Connection Framework ?The Generic Connection Framework (GCF) makes it easy for wireless devices to make network connections. It is part of CLDC and CDC and resides in the javax.microedition.io package.

What is GPRS ?The General Packet Radio System (GPRS) is the next generation of GSM. It will be the basis of 3G networks in Europe and elsewhere.

What is GSM ?The Global System for Mobile Communications (GSM) is a wireless network system that is widely used in Europe, Asia, and Australia. GSM is used at three different frequencies: GSM900 and GSM1800 are used in Europe, Asia, and Australia, while GSM1900 is deployed in North America and other parts of the world.

What is HLR ?The Home Location Register (HLR) is a database for permanent storage of subscriber data and service profiles.

What is HTTPS ?Hyper Text Transfer Protocol Secure sockets (HTTPS) is a protocol for transmission of encrypted hypertext over Secure Sockets Layer.

What is i-appli ?Sometimes called "Java for i-mode", i-appli is a Java environment based on CLDC. It is used on handsets in NTT DoCoMo's i-mode service. While i-appli is similar to MIDP, it was developed before the MIDP specification was finished and the two APIs are incompatible.

What is IDE ?An Integrated Development Environment (IDE) provides a programming environment as a single application. IDEs typically bundle a compiler, debugger, and GUI builder tog ether. Forte for Java is Sun's Java IDE.

What is iDEN ?The Integrated Dispatch Enhanced Network (iDEN) is a wireless network system developed by Motorola. Various carriers support iDEN networks around the world: Nextel is one of the largest carriers, with networks covering North and South America.

Page 62: Basic Java Interview Questions

What is i-mode ?A standard used by Japanese wireless devices to access cHTML (compact HTML) Web sites and display animated GIFs and other multimedia content.

What is 3G ?Third generation (3G) wireless networks will offer faster data transfer rates than current networks. The first generation of wireless (1G) was analog cellular. The second generation (2G) is digital cellular, featuring integrated voice and data communications. So-called 2.5G networks offer incremental speed increases. 3G networks will offer dramatically improved data transfer rates, enabling new wireless applications such as streaming media.

What is 3GPP ?The 3rd Generation Partnership Project (3GPP) is a global collaboration between 6 partners: ARIB, CWTS, ETSI, T1, TTA, and TTC. The group aims to develop a globally accepted 3rd-generation mobile system based on GSM.

What is Java Card ?The Java Card specification allows Java technology to run on smart cards and other small devices. The Java Card API is compatible with formal international standards, such as, ISO7816, and industry-specific standards, such as, Europay/Master Card/Visa (EMV). 

What is JavaHQ ?JavaHQ is the Java platform control center on your Palm OS device.

What is JCP ?The Java Community Process (JCP) an open organization of international Java developers and licensees who develop and revise Java technology specifications, reference implementations, and technology compatibility kits through a formal process.

What is JDBC for CDC/FP ?The JDBC Optional Package for CDC/Foundation Profile (JDBCOP for CDC/FP) is an API that enables mobile Java applications to communicate with relational database servers using a subset of J2SE's Java Database Connectivity. This optional package is a strict subset of JDBC 3.0 that excludes some of JDBC's advanced and server-oriented features, such as pooled connections and array types. It's meant for use with the Foundation Profile or its supersets.

What is JSR Java Specification Request (JSR) is the actual description of proposed and final specifications for the Java platform. JSRs are reviewed by the JCP and the public before a final release of a specification is made.

What is KittyHawk KittyHawk is a set of APIs used by LG Telecom on its IBook and p520 devices. KittyHawk is based on CLDC. It is conceptually similar to MIDP but the two APIs are incompatible.

What is KJava KJava is an outdated term for J2ME. It comes from an early package of Java software for PalmOS, released at the 2000 JavaOne show. The classes for that release were packaged in the com.sun.kjava package.

Page 63: Basic Java Interview Questions

What is kSOAP kSOAP is a SOAP API suitable for the J2ME, based on kXML.

What is kXML The kXML project provides a small footprint XML parser that can be used with J2ME.

What is KVM The KVM is a compact Java virtual machine (JVM) that is designed for small devices. It supports a subset of the features of the JVM. For example, the KVM does not support floating-point operations and object finalization. The CLDC specifies use of the KVM. According to folklore, the 'K' in KVM stands for kilobyte, signifying that the KVM runs in kilobytes of memory as opposed to megabytes.

What is LAN A Local Area Network (LAN) is a group of devices connected with various communications technologies in a small geographic area. Ethernet is the most widely-used LAN technology. Communication on a LAN can either be with Peer-to-Peer devices or Client-Server devices.

What is LCDUI LCDUI is a shorthand way of referring to the MIDP user interface APIs, contained in the javax.microedition.lcdui package. Strictly speaking, LCDUI stands for Liquid Crystal Display User Interface. It's a user interface toolkit for small device screens which are commonly LCD screens.

 What is MExE The Mobile Execution Environment (MExE) is a specification created by the 3GPP which details an applicatio n environment for next generation mobile devices. MExE consists of a variety of technologies including WAP, J2ME, CLDC and MIDP.

What is MIDlet A MIDlet is an application written for MIDP. MIDlet applications are subclasses of the javax.microedition.midlet.MIDlet class that is defined by MIDP.

What is MIDlet suite MIDlets are packaged and distributed as MIDlet suites. A MIDlet suite can contain one or more MIDlets. The MIDlet suite consists of two files, an application descriptor file with a .jad extension and an archive file with a .jar file. The descriptor lists the archive file name, the names and class names for each MIDlet in the suite, and other information. The archive file contains the MIDlet classes and resource files. 

What is MIDP The Mobile Information Device Profile (MIDP) is a specification for a J2ME profile. It is layered on top of CLDC and adds APIs for application life cycle, user interface, networking, and persistent storage.

What is MIDP-NG The Next Generation MIDP specification is currently under development by the Java Community Process. Planned improvements include XML parsing and cryptographic support.

What is Mobitex Mobitex is a packet-switched, narrowband PCS network, designed for wide-area wireless data communications. It was developed in 1984 by Eritel, an Ericsson subsidiary, a nd there are now over 30 Mobitex networks in operation worldwide.

Page 64: Basic Java Interview Questions

What is Modulation ?Modulation is the method by which a high-frequency digital signal is grafted onto a lower-frequency analog wave, so that digital packets are able to ride piggyback on the analog airwave.

What is MSC ? A Mobile Switching Center (MSC) is a unit within a cellular phone network that automatically coordinates and switches calls in a given cell. It monitors each caller's signal strength, and when a signal begins to fade, it hands off the call to another MSC that's better positioned to manage the call.

What is Obfuscation Obfuscation is a technique used to complicate code. Obfuscation makes code harder to understand when it is de-compiled, but it typically has no affect on the functionality of the code. Obfuscation programs can be used to protect Java programs by making them harder to reverse-engineer.

What is optional package An optional package is a set of J2ME APIs providing services in a specific area, such as database access or multimedia. Unlike a profile, it does not define a complete application environment, but rather is used in conjunction with a configuration or a profile. It extends the runtime environment to support device capabilities that are not universal enough to be defined as part of a profile or that need to be shared by different profiles. J2ME RMI and the Mobile Media RMI are examples of optional packages.

What is OTA Over The Air (OTA) refers to any wireless networking technology.

What is PCS Personal Communications Service (PCS) is a suite of second-generation, digitally modulated mobile-communications interfaces that includes TDMA, CDMA, and GSM. PCS serves as an umbrella term for second-generation wireless technologies operating in the 1900MHz range

What is PDAP The Personal Digital Assistant Profile (PDAP) is a J2ME profile specification designed for small platforms such as PalmOS devices. You can think of PDAs as being larger than mobile phones but smaller than set-top boxes. PDAP is built on top of CLDC and will specify user interface and persistent storage APIs. PDAP is currently being developed using the Java Community Process (JCP).

What is PDC Personal Digital Cellular (PDC) is a Japanese standard for wireless communications.

What is PDCP Parallel and Distributed Computing Practices (PDCP) are often used to describe computer systems that are spread over many devices on a network (wired or wireless) where many nodes process data simultaneously.

What is Personal Profile The Personal Profile is a J2ME profile specification. Layered on the Foundation Profile and CDC, the Personal Profile will be the next generation of PersonalJava technology. The specification is currently in development under the Java Community Process (JCP).

What is PersonalJava PersonalJava is a Java environment based on the Java virtual machine1 (JVM) and a set of APIs similar to

Page 65: Basic Java Interview Questions

a JDK 1.1 environment. It includes the Touchable Look and Feel (also called Truffle), a graphic toolkit that is optimized for consumer devices with a touch sensitive screen. PersonalJava will be included in J2ME in the upcoming Personal Profile, which is built on CDC.

What is PNG Portable Network Graphics (PNG) is an image format offering lossless compression and storage flexibility. The MIDP specification requires implementations to recognize certain types of PNG images.

What is POSE Palm OS Emulator (POSE).

What is PRC Palm Resource Code (PRC) is the file format for Palm OS applications.

What is preverification Due to memory and processing power available on a device, the verification process of classes are split into two processes. The first process is the preverification which is off-device and done using the preverify tool. The second process is verification which is done on-device.

What is profile A profile is a set of APIs added to a configuration to support specific uses of a mobile device. Along with its underlying configuration, a profile defines a complete, and usually self-contained, general-purpose application environment. Profiles often, but not always, define APIs for user interface and persistence; the MIDP profile, based on the CLDC configuration, fits this pattern. Profiles may be supersets or subsets of other profiles; the Personal Basis Profile is a subset of the Personal Profile and a superset of the Foundation Profile. See also configuration, optional package.

What is Provisioning ?In telecommunications terms, provisioning means to provide telecommunications services to a user. This includes providing all necessary hardware, software, and wiring or transmission devices.

What is PSTN ?The public service telephone network (PSTN) is the traditional, land-line based system for exchanging phone calls.

What is RMI Remote method invocation (RMI) is a feature of J2SE that enables Java objects running in one virtual machine to invoke methods of Java objects running in another virtual machine, seamlessly.

What is RMI OP The RMI Optional Package (RMI OP) is a subset of J2SE 1.3's RMI functionality used in CDC-based profiles that incorporate the Foundation Profile, such as the Personal Basis Profile and the Personal Profile. The RMIOP cannot be used with CLDC-based profiles because they lack object serialization and other important features found only in CDC-based profiles. RMIOP supports most of the J2SE RMI functionality, including the Java Remote Method Protocol, marshalled objects, distributed garbage collection, registry-based object lookup, and network class loading, but not HTTP tunneling or the Java 1.1 stub protocol.

What is RMI Profile The RMI Profile is a J2ME profile specification designed to support Java's Remote Method Invocation

Page 66: Basic Java Interview Questions

(RMI) distributed object system. Devices implementing the RMI Profile will be able to interoperate via RMI with other Java devices, including Java 2, Standard Edition. The RMI Profile is based on the Foundation Profile, which in turn is based on CDC.

What is RMS The Record Management System (RMS) is a simple record-oriented database that allows a MIDlet to persistently store information and retrieve it later. Different MIDlets can also use the RMS to share data.

What is SDK A Software Development Kit (SDK) is a set of tools used to develop applications for a particular platform. An SDK typically contains a compiler, linker, and debugger. It may also contain libraries and documentation for APIs.

What is SIM A Subscriber Identity Module (SIM) is a stripped-down smart card containing information about the identity of a cell-phone subscriber, and subscriber authentication and service information. Because the SIM uniquely identifies the subscriber and is portable among handsets, the user can move it from one kind of phone to another, facilitating international roaming.

What is SMS Short Message Service (SMS) is a point-to-point service similar to paging for sending text messages of up to 160 characters to mobile phones.

What is SOAP The Simple Object Access Protocol (SOAP) is an XML- based protocol that allows objects of any type to communicated in a distributed environment. SOAP is used in developing Web Services.

What is SSL Secure Sockets Layer (SSL) is a socket protocol that encrypts data sent over the network and provides authentication for the socket endpoints.

What is T9 T9 is a text input method for mobile phones and other small devices. It replaces the "multi-tap" input method by guessing the word that you are trying to enter. T9 may be embedded in a device by the manufacturer. Note that even if the device supports T9, the Java implementation may or may not use it. Check your documentation for details.

What is TDMA Time Division Multiple Access (TDMA) is a second-generation modulation standard using bandwidth allocated in the 800 MHz, 900 MHz, and 1900MHz ranges.

What is Telematics Telematics is a location-based service that routes event notification and control data over wireless networks to and from mobile devices installed in automobiles. Telematics makes use of GPS technology to track vehicle latitude and longitude, and displays maps in LED consoles mounted in dashboards. It connects to remote processing centers that turn provide server-side Internet and voice services, as well as access to database resources.

Page 67: Basic Java Interview Questions

What is Tomcat ?Tomcat is a reference implementation of the Java servlet and JavaServer Pages (JSP) specifications. It is intended as a platform for developing and testing servlets.

What is UDDI ?Universal Description, Discovery, and Integration (UDDI) is an XML-based standard for describing, publishing, and finding Web services. UDDI is a specification for a distributed registry of Web services.

What is UMTS Developed by Nortel Networks, Universal Mobile Telecommunications Service (UMTS) is a standard that will provide cellular users a consistent set of technologies no matter where they are located worldwide. UMTS utilizes W-CDMA technology. 

What is VLR The Visitor Location Register (VLR) is a database that contains temporary information about subscribers.

What is WAE The Wireless Application Environment (WAE) provides a application framework for small devices. WAE leverages other technologies such as WAP, WTP, and WSP.

What is WAP Wireless Application Protocol (WAP) is a protocol for transmitting data between servers and clients (usually small wireless devices like mobile phones). WAP is analogous to HTTP in the World Wide Web. Many mobile phones include WAP browser software to allow users access to Internet WAP sites.

What is WAP Gateway A WAP Gateway acts as a bridge allowing WAP devices to communicate with other networks (namely the Internet).

What is W-CDMA Wideband Code-Division Multiple Access (W-CDMA), also known as IMT-2000, is a 3rd generation wireless technology. Supports speeds up to 384Kbps on a wide-area network, or 2Mbps locally.

What is WDP Wireless Datagram Protocol (WDP) works as the transport layer of WAP. WDP processes datagrams from upper layers to formats required by different physical datapaths, bearers, that may be for example GSM SMS or CDMA Packet Data. WDP is adapted to the bearers available in the device so upper layers don't need to care about the physical level.

What is WMA The Wireless Messaging API (WMA) is a set of classes for sending and receiving Short Message Service messages. See also SMS.

What is WML The Wireless Markup Language (WML) is a simple language used to create applications for small wireless devices like mobile phones. WML is analogous to HTML in the World Wide Web.

What is WMLScript WMLScript is a subset of the JavaScript scripting language designed as part of the WAP standard to provide a convenient mechanism to access mobile phone's peripheral functions.

Page 68: Basic Java Interview Questions

What is WSP Wireless Session Protocol (WSP) implements session services of WAP. Sessions can be connection-oriented and connectionless and they may be suspended and resumed at will.

What is WTLS Wireless Transport Layer Security protocal (WTLS) does all cryptography oriented features of WAP. WTLS handles encryption/decryption, user authentication and data integrity. WTLS is based on the fixed network Transport Layer Security protocal (TLS), formerly known as Secure Sockets Layer (SSL).

What is WTP Wireless Transaction Protocol (WTP) is WAP's transaction protocol that works between the session protocol WSP and security protocol WTLS. WTP chops data packets into lower level datagrams and concatenates received datagrams into useful data. WTP also keeps track of received and sent packets and does re-transmissions and acknowledgment sending when needed.

J2SE Interview Questions and Answers

What is abstract ?A Java keyword used in a class definition to specify that a class is not to be instantiated, but rather inherited by other classes. An abstract class can have abstract methods that are not implemented in the abstract class, but in subclasses. 

What is abstract class ?A class that contains one or more abstract methods, and therefore can never be instantiated. Abstract classes are defined so that other classes can extend them and make them concrete by implementing the abstract methods.

What is abstract method ?A method that has no implementation.

What is Abstract Window Toolkit (AWT) ?A collection of graphical user interface (GUI) components that were implemented using native-platform versions of the components. These components provide that subset of functionality which is common to all native platforms. Largely supplanted by the Project Swing component set. See also Swing.

What is access control ?The methods by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.

What is ACID ?The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation, and durability.

What is actual parameter list ?The arguments specified in a particular method call. See also formal parameter list.

What is API ?

Page 69: Basic Java Interview Questions

Application Programming Interface. The specification of how a programmer writing an application accesses the behavior and state of classes and objects. 

What is applet ?A component that typically executes in a Web browser, but can execute in a variety of other applications or devices that support the applet programming model. 

What is ASCII ?American Standard Code for Information Interchange. A standard assignment of 7-bit numeric codes to characters. See also Unicode.

What is atomic ?Refers to an operation that is never interrupted or left in an incomplete state under any circumstance.

What is authentication ?The process by which an entity proves to another entity that it is acting on behalf of a specific identity.

What is autoboxing ?Automatic conversion between reference and primitive types.

What is bean ?A reusable software component that conforms to certain design and naming conventions. The conventions enable beans to be easily combined to create an application using tools that understand the conventions.

What is binary operator ?An operator that has two arguments.

What is bitwise operator ?An operator that manipulates the bits of one or more of its operands individually and in parallel. Examples include the binary logical operators (&, |, ^), the binary shift operators (<< , >>, >>> ) and the unary one's complement operator (~).

What is block ?In the Java programming language, any code between matching braces. Example: { x = 1; }.

What is Boolean ?Refers to an expression or variable that can have only a true or false value. The Java programming language provides the boolean type and the literal values true and false.

What is break ?A Java keyword used to resume program execution at the statement immediately following the current statement. If followed by a label, the program resumes execution at the labeled statement.

What is bytecode ?Machine-independent code generated by the Java compiler and executed by the Java interpreter.

What is case ?A Java keyword that defines a group of statements to begin executing if a value specified matches the value defined by a preceding switch keyword.

Page 70: Basic Java Interview Questions

What is casting ?Explicit conversion from one data type to another.

What is catch ?A Java keyword used to declare a block of statements to be executed in the event that a Java exception, or run time error, occurs in a preceding try block.

What is "abstract schema" ?The part of an entity bean's deployment descriptor that defines the bean's persistent fields and relationships.

What is "abstract schema name" ?A logical name that is referenced in EJB QL queries.

What is "access control" ?The methods by which interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.

What is "ACID" ?The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation, and durability.

What is "activation" ?

The process of transferring an enterprise bean from secondary storage to memory. (See passivation.)

What is "anonymous access" ?Accessing a resource without authentication.

What is class ?In the Java programming language, a type that defines the implementation of a particular kind of object. A class definition defines instance and class variables and methods, as well as specifying the interfaces the class implements and the immediate superclass of the class. If the superclass is not explicitly specified, the superclass will implicitly be Object.

What is class method ?A method that is invoked without reference to a particular object. Class methods affect the class as a whole, not a particular instance of the class. Also called a static method. See also instance method.

What is class variable ?A data item associated with a particular class as a whole--not with particular instances of the class. Class variables are defined in class definitions. Also called a static field. See also instance variable.

What is classpath ?An environmental variable which tells the Java virtual machine1 and Java technology-based applications where to find the class libraries, including user-defined class libraries.

Page 71: Basic Java Interview Questions

What is client ?In the client/server model of communications, the client is a process that remotely accesses resources of a compute server, such as compute power and large memory capacity.

What is CODEBASE ?Works together with the code attribute in the <APPLET> tag to give a complete specification of where to find the main applet class file: code specifies the name of the file, and codebase specifies the URL of the directory containing the file.

What is comment ?In a program, explanatory text that is ignored by the compiler. In programs written in the Java programming language, comments are delimited using // or /*...*/.

What is commit ?The point in a transaction when all updates to any resources involved in the transaction are made permanent.

What is compilation unit ?The smallest unit of source code that can be compiled. In the current implementation of the Java platform, the compilation unit is a file.

What is compiler ?A program to translate source code into code to be executed by a computer. The Java compiler translates source code written in the Java programming language into bytecode for the Java virtual machine1. See also interpreter.

What is compositing ?The process of superimposing one image on another to create a single image.

What is constructor ?A pseudo-method that creates an object. In the Java programming language, constructors are instance methods with the same name as their class. Constructors are invoked using the new keyword.

What is const ?A reserved Java keyword not used by current versions of the Java programming language.

What is continue ?A Java keyword used to resume program execution at the end of the current loop. If followed by a label, continue resumes execution where the label occurs.

What is conversational state ?The field values of a session bean plus the transitive closure of the objects reachable from the bean's fields. The transitive closure of a bean is defined in terms of the serialization protocol for the Java programming language, that is, the fields that would be stored by serializing the bean instance.

What is CORBA ?Common Object Request Broker Architecture. A language independent, distributed object model specified by the Object Management Group (OMG).

Page 72: Basic Java Interview Questions

What is core class ?A public class (or interface) that is a standard member of the Java Platform. The intent is that the core classes for the Java platform, at minimum, are available on all operating systems where the Java platform runs. A program written entirely in the Java programming language relies only on core classes, meaning it can run anywhere. .

What is core packages ?The required set of APIs in a Java platform edition which must be supported in any and all compatible implementations.

What is credentials ?The information describing the security attributes of a principal. Credentials can be acquired only through authentication or delegation.

What is critical section ?A segment of code in which a thread uses resources (such as certain instance variables) that can be used by other threads, but that must not be used by them at the same time.

What is declaration ?A statement that establishes an identifier and associates attributes with it, without necessarily reserving its storage (for data) or providing the implementation (for methods). See also definition.

What is default ?A Java keyword optionally used after all case conditions in a switch statement. If all case conditions are not matched by the value of the switch variable, the default keyword will be executed.

What is definition ?A declaration that reserves storage (for data) or provides implementation (for methods). See also declaration.

What is delegation ?An act whereby one principal authorizes another principal to use its identity or privileges with some restrictions.

What is deprecation ?Refers to a class, interface, constructor, method or field that is no longer recommended, and may cease to exist in a future version.

What is derived from ?Class X is "derived from" class Y if class X extends class Y. See also subclass, superclass.

What is distributed ?Running in more than one address space.

What is distributed application ?An application made up of distinct components running in separate runtime environments, usually on different platforms connected through a network. Typical distributed applications are two-tier (client/server), three-tier (client/middleware/server), and n-tier (client/multiple middleware/multiple servers).

Page 73: Basic Java Interview Questions

What is do ?A Java keyword used to declare a loop that will iterate a block of statements. The loop's exit condition can be specified with the while keyword.

What is DOM ?Document Object Model. A tree of objects with interfaces for traversing the tree and writing an XML version of it, as defined by the W3C specification.

What is double ?A Java keyword used to define a variable of type double.

What is double precision ?In the Java programming language specification, describes a floating point number that holds 64 bits of data. See also single precision.

What is DTD ?Document Type Definition. A description of the structure and properties of a class of XML files.

What is else ?A Java keyword used to execute a block of statements in the case that the test condition with the if keyword evaluates to false.

What is Embedded Java Technology ?The availability of Java 2 Platform, Micro Edition technology under a restrictive license agreement that allows a licensee to leverage certain Java technologies to create and deploy a closed-box application that exposes no APIs.

What is encapsulation ?The localization of knowledge within a module. Because objects encapsulate data and implementation, the user of an object can view the object as a black box that provides services. Instance variables and methods can be added, deleted, or changed, but as long as the services provided by the object remain the same, code that uses the object can continue to use it without being rewritten. See also instance variable, instance method.

What is enum ?A Java keyword used to declare an enumerated type.

What is enumerated type ?A type whose legal values consist of a fixed set of constants.

What is exception ?An event during program execution that prevents the program from continuing normally; generally, an error. The Java programming language supports exceptions with the try, catch, and throw keywords. See also exception handler.

What is exception handler ?A block of code that reacts to a specific type of exception. If the exception is for an error that the program can recover from, the program can resume executing after the exception handler has executed.

Page 74: Basic Java Interview Questions

What is executable content ?An application that runs from within an HTML file. See also applet.

What is extends ?Class X extends class Y to add functionality, either by adding fields or methods to class Y, or by overriding methods of class Y. An interface extends another interface by adding methods. Class X is said to be a subclass of class Y. See also derived from. 

What is field ?A data member of a class. Unless specified otherwise, a field is not static.

What is final ?A Java keyword. You define an entity once and cannot change it or derive from it later. More specifically: a final class cannot be subclassed, a final method cannot be overridden and a final variable cannot change from its initialized value.

What is finally ?A Java keyword that executes a block of statements regardless of whether a Java Exception, or run time error, occurred in a block defined previously by the try keyword.

What is float ?A Java keyword used to define a floating point number variable.

What is for ?A Java keyword used to declare a loop that reiterates statements. The programmer can specify the statements to be executed, exit conditions, and initialization variables for the loop.

What is FTP ?File Transfer Protocol. FTP, which is based on TCP/IP, enables the fetching and storing of files between hosts on the Internet. See also TCP/IP.

What is formal parameter list ?The parameters specified in the definition of a particular method. See also actual parameter list.

What is garbage collection ?The automatic detection and freeing of memory that is no longer in use. The Java runtime system performs garbage collection so that programmers never explicitly free objects.

What is generic ?A class, interface, or method that declares one or more type variables. These type variables are known as type parameters. A generic declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. At runtime, all of these parameterized types share the same class, interface, or method.

What is goto ?This is a reserved Java keyword. However, it is not used by current versions of the Java programming language.

Page 75: Basic Java Interview Questions

What is GUI ?Graphical User Interface. Refers to the techniques involved in using graphics, along with a keyboard and a mouse, to provide an easy-to-use interface to some program.

What is hexadecimal ?The numbering system that uses 16 as its base. The marks 0-9 and a-f (or equivalently A-F) represent the digits 0 through 15. In programs written in the Java programming language, hexadecimal numbers must be preceded with 0x. See also octal. 

What is group ?A collection of principals within a given security policy domain.

What is hierarchy ?A classification of relationships in which each item except the top one (known as the root) is a specialized form of the item above it. Each item can have one or more items below it in the hierarchy. In the Java class hierarchy, the root is the Object class.

What is HTML ?Hypertext Markup Language. This is a file format, based on SGML, for hypertext documents on the Internet. It is very simple and allows for the embedding of images, sounds, video streams, form fields and simple text formatting. References to other objects are embedded using URLs.

What is HTTP ?Hypertext Transfer Protocol. The Internet protocol, based on TCP/IP, used to fetch hypertext objects from remote hosts. See also TCP/IP.

What is HTTPS ?Hypertext Transfer Protocol layered over the SSL protocol.

What is IDL ?Interface Definition Language. APIs written in the Java programming language that provide standards-based interoperability and connectivity with CORBA (Common Object Request Broker Architecture).

What is identifier ?The name of an item in a program written in the Java programming language.  

What is IIOP ?Internet Inter-ORB Protocol. A protocol used for communication between CORBA object request brokers.

What is if ?A Java keyword used to conduct a conditional test and execute a block of statements if the test evaluates to true.

What is impersonation ?An act whereby one entity assumes the identity and privileges of another entity without restrictions and without any indication visible to the recipients of the impersonator's calls that delegation has taken place. Impersonation is a case of simple delegation.

Page 76: Basic Java Interview Questions

What is implements ?A Java keyword included in the class declaration to specify any interfaces that are implemented by the current class.

What is import ?A Java keyword used at the beginning of a source file that can specify classes or entire packages to be referred to later without including their package names in the reference.

What is inheritance ?The concept of classes automatically containing the variables and methods defined in their super types. See also super class, subclass.

What is instance ?An object of a particular class. In programs written in the Java programming language, an instance of a class is created using the new operator followed by the class name.

What is instance method ?Any method that is invoked with respect to an instance of a class. Also called simply a method. See also class method.

What is instance variable ?Any item of data that is associated with a particular object. Each instance of a class has its own copy of the instance variables defined in the class. Also called a field. See also class variable.

What is instanceof ?A two-argument Java keyword that tests whether the runtime type of its first argument is assignment compatible with its second argument.

Servlet Interview Questions and Answers

What is Servlet?A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm.

Why is Servlet so popular? Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

What is servlet container? The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.

When a client request is sent to the servlet container, how does the container choose which servlet to invoke? The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

Page 77: Basic Java Interview Questions

If a servlet is not properly initialized, what exception may be thrown? During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

Given the request path below, which are context path, servlet path and path info? /bookstore/education/index.html 

context path: /bookstoreservlet path: /educationpath info: /index.html

What is filter? Can filter be used as request or response? A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?

I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

What is new in ServletRequest interface ? (Servlet 2.4) The following methods have been added to ServletRequest 2.4 version:public int getRemotePort()public java.lang.String getLocalName()public java.lang.String getLocalAddr()public int getLocalPort()

Request parameter How to find whether a parameter exists in the request object? 1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));2. boolean hasParameter = request.getParameterMap().contains(theParameter);(which works in Servlet 2.3+)

How can I send user authentication information while making URL Connection? You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

Can we use the constructor, instead of init(), to initialize servlet? Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

How can a servlet refresh automatically if some new data has entered the database? You can use a client-side Refresh or Server Push

Page 78: Basic Java Interview Questions

The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute.

What mechanisms are used by a Servlet Container to maintain session information?Cookies, URL rewriting, and HTTPS protocol information are used to maintain session informationDifference between GET and POST In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy. In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.What is session? The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.What is servlet mapping? The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.What is servlet context ? The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. 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. (answer supplied by Sun's tutorial).Which interface must be implemented by all servlets? Servlet interface.Explain the life cycle of Servlet.Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet? An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.Why don't we write a constructor in a servlet? Container writes a no argument constructor for our servlet.When we don't write any constructor for the servlet, how does container create an instance of servlet? Container creates instance of servlet by calling Class.forName(className).newInstance().Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time? Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext? We can give relative URL when we use ServletRequest and not while using ServletContext.

Page 79: Basic Java Interview Questions

Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()? Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

My SQL Interview Questions and Answers

What's MySQL ?MySQL (pronounced "my ess cue el") is an open source relational database management system (RDBMS) that uses Structured Query Language (SQL), the most popular language for adding, accessing, and processing data in a database. Because it is open source, anyone can download MySQL and tailor it to their needs in accordance with the general public license. MySQL is noted mainly for its speed, reliability, and flexibility. ...

What is DDL, DML and DCL ? If you look at the large variety of SQL commands, they can be divided into three large subgroups. Data Definition Language deals with database schemas and descriptions of how the data should reside in the database, therefore language statements like CREATE TABLE or ALTER TABLE belong to DDL. DML deals with Data Manipulation, and therefore includes most common SQL statements such SELECT, INSERT, etc. Data Control Language includes commands such as GRANT, and mostly concerns with rights, permissions and other controls of the database system.

How do you get the number of rows affected by query? SELECT COUNT (user_id) FROM users would only return the number of user_id’s.

If the value in the column is repeatable, how do you find out the unique values? Use DISTINCT in the query, such as SELECT DISTINCT user_firstname FROM users; You can also ask for a number of distinct values by saying SELECT COUNT (DISTINCT user_firstname) FROM users;

How do you return the a hundred books starting from 25th? SELECT book_title FROM books LIMIT 25, 100. The first number in LIMIT is the offset, the second is the number.

You wrote a search engine that should retrieve 10 results at a time, but at the same time you’d like to know how many rows there’re total. How do you display that to the user? SELECT SQL_CALC_FOUND_ROWS page_title FROM web_pages LIMIT 1,10; SELECT FOUND_ROWS(); The second query (not that COUNT() is never used) will tell you how many results there’re total, so you can display a phrase "Found 13,450,600 results, displaying 1-10". Note that FOUND_ROWS does not pay attention to the LIMITs you specified and always returns the total number of rows affected by query.

How would you write a query to select all teams that won either 2, 4, 6 or 8 games? SELECT team_name FROM teams WHERE team_won IN (2, 4, 6, 8)

How would you select all the users, whose phone number is null? SELECT user_name FROM users WHERE ISNULL(user_phonenumber);

What does this query mean: SELECT user_name, user_isp FROM users LEFT JOIN isps USING (user_id) ?

Page 80: Basic Java Interview Questions

It’s equivalent to saying SELECT user_name, user_isp FROM users LEFT JOIN isps WHERE users.user_id=isps.user_id

How do you find out which auto increment was assigned on the last insert?

SELECT LAST_INSERT_ID() will return the last value assigned by the auto_increment function. Note that you don’t have to specify the table name.

What does –i-am-a-dummy flag to do when starting MySQL? Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE clause is not present.

On executing the DELETE statement I keep getting the error about foreign key constraint failing. What do I do? What it means is that so of the data that you’re trying to delete is still alive in another table. Like if you have a table for universities and a table for students, which contains the ID of the university they go to, running a delete on a university table will fail if the students table still contains people enrolled at that university. Proper way to do it would be to delete the offending data first, and then delete the university in question. Quick way would involve running SET foreign_key_checks=0 before the DELETE command, and setting the parameter back to 1 after the DELETE is done. If your foreign key was formulated with ON DELETE CASCADE, the data in dependent tables will be removed automatically.

When would you use ORDER BY in DELETE statement? When you’re not deleting by row ID. Such as in DELETE FROM techpreparation_com_questions ORDER BY timestamp LIMIT 1. This will delete the most recently posted question in the table techpreparation_com_questions.

How can you see all indexes defined for a table? SHOW INDEX FROM techpreparation_questions;

How would you change a column from VARCHAR(10) to VARCHAR(50)? ALTER TABLE techpreparation_questions CHANGE techpreparation_content techpreparation_CONTENT VARCHAR(50).

How would you delete a column? ALTER TABLE techpreparation_answers DROP answer_user_id.