text:
Mehr über die Mitgliedschaft bei Scribd erfahren
Entdecken, was Scribd alles zu bieten hat, inklusive Bücher und Hörbücher von großen Verlagen.
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 15. 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 lock 18. 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.
21. Can a abstract method have the static qualifier? - No 22. 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? - Dictionary 24. What is a lightweight component? - Lightweight components are the one which doesnt 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.lang 29. 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. Dead 32. 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? - Yes 2. Can an Interface be final? - No 3. Can an Interface have an inner class? - Yes. 4. public interface abc 5. 6. 7. 8. 9. 10. { static int i=0; void dd(); class a1 { a1() {
int j; System.out.println("inside");
20. Can we define private and protected modifiers for variables in interfaces? - No 21. 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 doesnt 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 isnt there operator overloading? - Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasnt 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
than the name of a particular object of the class (though that works too). Thats 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 220.127.116.11 into a hostname like java.sun.com? 29. String hostname = InetAddress.getByName("126.96.36.199").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 objects 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.
.... } 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.
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
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.
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.
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.
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.
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.
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
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.
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. Nonstatic 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).
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.
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.
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. DOM 1. Tree of nodes 2. Memory: Occupies more memory, preffered for small XML documents 3. 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 documents 3. Faster at runtime 4. Objects are to be created 5. Need to write code for creating objects 6. 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
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.
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 cant look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, its 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 cant 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.
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 cant 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
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 bandwidthintensive 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
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 behavior 2. 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, platformindependent, 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
--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(). Theres nothing to stop you. But you shouldnt. The original reason for init() was that ancient versions of Java couldnt dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you wont have access to a ServletConfig or ServletContext. 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 Systems IPAddress and Port Number. What Class.forName will do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. How to Retrieve Warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println(\"Message: \" + warning.getMessage()); System.out.println(\"SQLState: \" + warning.getSQLState()); System.out.print(\"Vendor error code: \"); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } } How many JSP scripting elements are there and what are they? There are three scripting language elements: declarations, scriptlets, expressions. In the Servlet 2.4 specification SingleThreadModel has been deprecated, why? Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. What are stored procedures? How is it useful? A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements 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 dbs 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.
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
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
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 method Is there a way I can set the inactivity lease period on a per-session basis? Typically, a default inactivity lease period for all sessions is set within your 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 //additional //maybe // the bean perform . id properties a db . to like query, compute info etc. .
f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, } catch (Exception . . } } The fter scope JSP first page Bean1.jsp can extracting it from via the then
response); { .
jsp:useBean name="fBean"
/ 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() method The init() method has to invoke the jspInit() method The destroy() method has to invoke jspDestroy() If any of the above conditions are not satisfied, the JSP engine may throw a translation error. Once the 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
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 1 If you're just including raw HTML, use the #include directive as usual inside your .jsp file. But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use 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 (firstname.lastname@example.com) 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 and 1. 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
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? No What is the difference between ServletContext and PageContext? ServletContext: Gives the information about the container PageContext: Gives the information about the Request What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()? request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource. How to pass information from JSP to included JSP? Using <%jsp:param> tag. 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.
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.
Can we use the constructor, instead of init(), to initialize servlet? Yes , of course you can use the constructor instead of init(). Theres nothing to stop you. But you shouldnt. The original reason for init() was that ancient versions of Java couldnt dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you wont have access to a ServletConfig or ServletContext. 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.
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 row int rowNum = srs.getRow(); // rowNum should be 4 srs.relative(-3); int rowNum = srs.getRow(); // rowNum should be 1 srs.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");
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 data uprs.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 RMIJDBC 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.
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 insert uprs.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.drivers Register a driver Specify a database Open a database connection Submit a query
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-
ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multithreaded 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 Drivers Type 1: JDBC-ODBC Bridge Driver Type 2: Native API Partly Java Driver Type 3: Network protocol Driver Type 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.
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 technologyenabled 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 JDBCODBC 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. Answer1 There 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). Answer2 1) 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? Answer1 It is the magic of polymorphism, and of Java interface vs. implementation types. Two objects can both be
"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. Answer2 Typically 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 using streams 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);
} /** * 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);
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 again Image 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
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. Answer2 Assuming 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.
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 Example import 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");
} 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 try catch (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); }
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 implementation public 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
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.
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
* 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 logic that 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 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 components 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. 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 components 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 authorizations for 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 doesnt 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 doesnt 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 and directory 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. 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 applications 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. 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. 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. 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. 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. 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 mobilecommunications 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 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 (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. 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
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 ? 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. 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. 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). 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). 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. 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. 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 standardsbased 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. 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. 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: /bookstore servlet path: /education path 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 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 information Difference 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 servlets 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. 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_ids. 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 youd like to know how many rows therere 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 therere 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) ? Its 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 dont 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 youre 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 youre 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.