1.What is a transient variable?
A transient variable is a variable that may not be serialized.
2. Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout..
3. 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..
4. 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. Objects that observe Observable objects implement the Observer interface
5. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors
6. 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...
7. 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.
8. Is null a keyword?
The null value is not a keyword
9. 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
10. What method is used to specify a container's layout?
The set Layout () method is used to specify a container's layout..
11. Which containers use a Flow Layout as their default layout?
The Panel and Applet classes use the Flow Layout as their default layout
12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state..
13. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on
collections of objects
14. 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
15. What is the List interface?
The List interface provides support for ordered collections of objects
16. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation
17. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
18. 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..
19. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection..
20. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out..
21. Which method of the Component class is used to set the position and size of a component?
Set Bounds ().
22. 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..
23. 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..
24. Which java.util classes and interfaces support event handling?
The Event Object class and the Event Listener interface support event processing..
25. Is size of a keyword?
The size of operator is not a keyword..
26. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects..
27. Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.
28. 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).
29. Can an object's finalize () method be invoked while it is reachable?
An object's finalize () method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize () method may be invoked by other objects.
30. What is the immediate super class of the Applet class?
Panel.
31. 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..
32. Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting..
33. What value does readLine () return when it has reached the end of a file?
The readLine () method returns null when it has reached the end of a file..
34. What is the immediate super class of the Dialog class?
Window.
35. What is clipping?
Clipping is the process of confining paint operations to a limited area or shape..
36. What is a native method?
A native method is a method that is implemented in a language other than Java..
37. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following:
for (;;).
38. What is order of precedence and associatively, 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.
39. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
40. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
41. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
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. What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked..
44. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks..
45. What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy..
46. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started..
47. 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..
48. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1..
49What is the range of the char type?
The range of the char type is 0 to 2^16 - 1..
50. In which package are most of the AWT events that support the event-delegation model defined?
Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package..
51. What is the immediate superclass of Menu?
MenuItem.
1) Can a class be it’s own event handler? Explain how to implement this.
Ans: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the actionPerformed method, put the code to perform when the button is pressed.
2) Why does JComponent have add() and remove() methods but Component does not?
Ans: because JComponent is a subclass of Container, and can contain other components and jcomponents.
3) How would you create a button with rounded edges?
Ans: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how would I do that?
Ans: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate.
5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?
Ans: The Font Class is used to render ‘glyphs’ - the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent)
6) What class is at the top of the AWT event hierarchy?
Ans: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a while.
7) Explain how to render an HTML page using only Swing.
Ans: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane.
How would you detect a keypress in a JComboBox?
Ans: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ - but the right answer is ‘add a KeyListener to the JComboBox’s editor component.’
9) Why should the implementation of any Swing callback (like a listener) execute quickly?
Ans: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
10) In what context should the value of Swing components be updated directly?
Ans: Swing components should be updated directly only in the context of callback methods invoked from the event dispatch thread. Any other context is not thread safe.
11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?
Ans: I want to update a Swing component but I’m not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when the update occurs, I’d use invokeLater.
12) If your UI seems to freeze periodically, what might be a likely reason?
Ans: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is taking a long time to execute thereby blocking the event dispatch thread from processing other UI events.
13) Which Swing methods are thread-safe?
Ans: The only thread-safe methods are repaint(), revalidate(), and invalidate()
14) Why won’t the JVM terminate when I close all the application windows?
Ans: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM.
1. Q: What if the main method is declared as private?
A: The program compiles properly but at runtime it will give "Main method not public." message.
2. Q: What if the static modifier is removed from the signature of the main method?
A: Program compiles. But at runtime throws an error "NoSuchMethodError".
A transient variable is a variable that may not be serialized.
2. Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout..
3. 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..
4. 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. Objects that observe Observable objects implement the Observer interface
5. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors
6. 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...
7. 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.
8. Is null a keyword?
The null value is not a keyword
9. 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
10. What method is used to specify a container's layout?
The set Layout () method is used to specify a container's layout..
11. Which containers use a Flow Layout as their default layout?
The Panel and Applet classes use the Flow Layout as their default layout
12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state..
13. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on
collections of objects
14. 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
15. What is the List interface?
The List interface provides support for ordered collections of objects
16. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation
17. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
18. 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..
19. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection..
20. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out..
21. Which method of the Component class is used to set the position and size of a component?
Set Bounds ().
22. 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..
23. 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..
24. Which java.util classes and interfaces support event handling?
The Event Object class and the Event Listener interface support event processing..
25. Is size of a keyword?
The size of operator is not a keyword..
26. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects..
27. Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.
28. 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).
29. Can an object's finalize () method be invoked while it is reachable?
An object's finalize () method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize () method may be invoked by other objects.
30. What is the immediate super class of the Applet class?
Panel.
31. 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..
32. Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting..
33. What value does readLine () return when it has reached the end of a file?
The readLine () method returns null when it has reached the end of a file..
34. What is the immediate super class of the Dialog class?
Window.
35. What is clipping?
Clipping is the process of confining paint operations to a limited area or shape..
36. What is a native method?
A native method is a method that is implemented in a language other than Java..
37. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following:
for (;;).
38. What is order of precedence and associatively, 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.
39. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
40. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
41. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
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. What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked..
44. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks..
45. What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy..
46. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started..
47. 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..
48. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1..
49What is the range of the char type?
The range of the char type is 0 to 2^16 - 1..
50. In which package are most of the AWT events that support the event-delegation model defined?
Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package..
51. What is the immediate superclass of Menu?
MenuItem.
1) Can a class be it’s own event handler? Explain how to implement this.
Ans: Sure. an example could be a class that extends Jbutton and implements ActionListener. In the actionPerformed method, put the code to perform when the button is pressed.
2) Why does JComponent have add() and remove() methods but Component does not?
Ans: because JComponent is a subclass of Container, and can contain other components and jcomponents.
3) How would you create a button with rounded edges?
Ans: there’s 2 ways. The first thing is to know that a JButton’s edges are drawn by a Border. so you can override the Button’s paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the button’s border to it.
4) If I wanted to use a SolarisUI for just a JTabbedPane, and the Metal UI for everything else, how would I do that?
Ans: in the UIDefaults table, override the entry for tabbed pane and put in the SolarisUI delegate.
5) What is the difference between the ‘Font’ and ‘FontMetrics’ class?
Ans: The Font Class is used to render ‘glyphs’ - the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent)
6) What class is at the top of the AWT event hierarchy?
Ans: java.awt.AWTEvent. if they say java.awt.Event, they haven’t dealt with swing or AWT in a while.
7) Explain how to render an HTML page using only Swing.
Ans: Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane.
How would you detect a keypress in a JComboBox?
Ans: This is a trick. most people would say ‘add a KeyListener to the JComboBox’ - but the right answer is ‘add a KeyListener to the JComboBox’s editor component.’
9) Why should the implementation of any Swing callback (like a listener) execute quickly?
Ans: Because callbacks are invoked by the event dispatch thread which will be blocked processing other events for as long as your method takes to execute.
10) In what context should the value of Swing components be updated directly?
Ans: Swing components should be updated directly only in the context of callback methods invoked from the event dispatch thread. Any other context is not thread safe.
11) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater?
Ans: I want to update a Swing component but I’m not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then I’d use invokeAndWait. If I don’t care when the update occurs, I’d use invokeLater.
12) If your UI seems to freeze periodically, what might be a likely reason?
Ans: A callback implementation like ActionListener.actionPerformed or MouseListener.mouseClicked is taking a long time to execute thereby blocking the event dispatch thread from processing other UI events.
13) Which Swing methods are thread-safe?
Ans: The only thread-safe methods are repaint(), revalidate(), and invalidate()
14) Why won’t the JVM terminate when I close all the application windows?
Ans: The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM.
1. Q: What if the main method is declared as private?
A: The program compiles properly but at runtime it will give "Main method not public." message.
2. Q: What if the static modifier is removed from the signature of the main method?
A: Program compiles. But at runtime throws an error "NoSuchMethodError".
3. Q: What if I write static public void instead of public static void?
A: Program compiles and runs properly.
4. Q: What if I do not provide the String array as the argument to the method?
A: Program compiles but throws a runtime error "NoSuchMethodError".
5. Q: What is the first argument of the String array in main method?
A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
6. Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
A: It is empty. But not null.
7. Q: How can one prove that the array is not null but empty using one line of code?
A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.
Q: What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
Q: What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.
Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Q: Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.
Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.
Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.
Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.
Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.
What is Multithreading? Explain how Java supports programming for multitasking environment.
A thread is one of the processes of an application. In multithreading, an OS allows different threads of an application to run in parallel.
The multitasking environment can execute in two ways.
• Process based multitasking
• Thread based multitasking
Process based multitasking –Process based multitasking is when two different processes, running at different locations, execute simultaneously. E.g.: A user can write some text using editor and simultaneously play music.
Thread based multitasking – A thread is the smallest unit of a dispatchable code.
Two different tasks like printing a document and editing it simultaneously can be done in a thread based multitasking environment.
Threads can be implemented in Java using the Thread Class.
The threading concept says that the different blocks of the same program can be executed concurrently.
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q :Explain different way of using thread?
A :The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
A: Map is Interface and Hashmap is class that implements that.
Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.
Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.
What is Multithreading? Explain how Java supports programming for multitasking environment.
A thread is one of the processes of an application. In multithreading, an OS allows different threads of an application to run in parallel.
The multitasking environment can execute in two ways.
• Process based multitasking
• Thread based multitasking
Process based multitasking –Process based multitasking is when two different processes, running at different locations, execute simultaneously. E.g.: A user can write some text using editor and simultaneously play music.
Thread based multitasking – A thread is the smallest unit of a dispatchable code.
Two different tasks like printing a document and editing it simultaneously can be done in a thread based multitasking environment.
Threads can be implemented in Java using the Thread Class.
The threading concept says that the different blocks of the same program can be executed concurrently.
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.
Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.
Q :Explain different way of using thread?
A :The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
Give one Example of static Synchronized method in JDBC API?
A. getConnection() method in DriverManager class.Which is used to get object of Connection interface.
What is a Connection?A. Connection is an interface, which is used to make a connection between client and Database (ie opening a session with a particular database).
What is the difference between execute() ,executeUpdate() and executeQuery() ? where we will use them?
execute() method returns a boolean value (ie if the given query returns a resutset then it returns true else false), so depending upon the return value we can get the ResultSet object (getResultset()) or we can know how many rows have bean affected by our query (getUpdateCount()).That is we can use this method for Fetching queries and Non-Fetching queries.
Fetching queries are the queries which are used to fetch the records from database (ie which returns resutset) ex: Select * from emp.
Non-Fetching queries are the queries which are used to update,insert,create or delete the records from database ex: update emp set sal=10000 where empno=7809.
executeUpdate() method is used for nonfetching queries.which returns int value.
executeQuery() method is used for fetching queries which returns ResulSet object ,Which contains methods to fetch the values.
How is jndi useful for Database connection?
Ans: Server identified the object with JDNI name
JNDI (java naming directory interface)
What are the uses of jndi?
Ans: The role of the JNDI API in the J2EE platform is two fold.
a) It provides the means to perform standard operations to a directory service resource such as LDAP (Lightweight Directory Access Protocol),Novell Directory Services, or Netscape Directory Services.
b) A J2EE application utilizes JNDI to look up interfaces used to create, amongst other things, EJBs, and JDBC connection.
How vendor Naming registry supports JNDI?
What is the difference between JDBC and ODBC?
Ans: a) OBDC is for Microsoft and JDBC is for Java applications.
b) ODBC can't be directly used with Java because it uses a C interface.
c) ODBC makes use of pointers which have been removed totally from Java.
d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required.
e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms.
A. getConnection() method in DriverManager class.Which is used to get object of Connection interface.
What is a Connection?A. Connection is an interface, which is used to make a connection between client and Database (ie opening a session with a particular database).
What is the difference between execute() ,executeUpdate() and executeQuery() ? where we will use them?
execute() method returns a boolean value (ie if the given query returns a resutset then it returns true else false), so depending upon the return value we can get the ResultSet object (getResultset()) or we can know how many rows have bean affected by our query (getUpdateCount()).That is we can use this method for Fetching queries and Non-Fetching queries.
Fetching queries are the queries which are used to fetch the records from database (ie which returns resutset) ex: Select * from emp.
Non-Fetching queries are the queries which are used to update,insert,create or delete the records from database ex: update emp set sal=10000 where empno=7809.
executeUpdate() method is used for nonfetching queries.which returns int value.
executeQuery() method is used for fetching queries which returns ResulSet object ,Which contains methods to fetch the values.
How is jndi useful for Database connection?
Ans: Server identified the object with JDNI name
JNDI (java naming directory interface)
What are the uses of jndi?
Ans: The role of the JNDI API in the J2EE platform is two fold.
a) It provides the means to perform standard operations to a directory service resource such as LDAP (Lightweight Directory Access Protocol),Novell Directory Services, or Netscape Directory Services.
b) A J2EE application utilizes JNDI to look up interfaces used to create, amongst other things, EJBs, and JDBC connection.
How vendor Naming registry supports JNDI?
What is the difference between JDBC and ODBC?
Ans: a) OBDC is for Microsoft and JDBC is for Java applications.
b) ODBC can't be directly used with Java because it uses a C interface.
c) ODBC makes use of pointers which have been removed totally from Java.
d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required.
e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms.
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 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.
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.
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.
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.
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
What does a well-written OO program look like?
A well-written OO program exhibits recurring structures that promote abstraction, flexibility, modularity and elegance.
Can you have virtual functions in Java?
Yes, all functions in Java are virtual by default. This is actually a pseudo trick question because the word "virtual" is not part of the naming convention in Java (as it is in C++, C-sharp and VB.NET), so this would be a foreign concept for someone who has only coded in Java. Virtual functions or virtual methods are functions or methods that will be redefined in derived classes.
Jack developed a program by using a Map container to hold key/value pairs. He wanted to make a change to the map. He decided to make a clone of the map in order to save the original data on side. What do you think of it? ?
If Jack made a clone of the map, any changes to the clone or the original map would be seen on both maps, because the clone of Map is a shallow copy. So Jack made a wrong decision.
What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class?
Strategically speaking, threads created by implementing Runnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Runnable interface, you save a space for your class to extend another class now or in future.
What is NullPointerException and how to handle it?
When an object is not initialized, the default value is null. When the following things happen, the NullPointerException is thrown:
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.
An application needs to load a library before it starts to run, how to code?
One option is to use a static block to load a library before anything is called. For example,
class Test {
static {
System.loadLibrary("path-to-library-file");
}
....
}
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 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 is the difference between JFC Swing and AWT?
AWT has following characteristics:
-It has native C specific code
-Rendering of AWT controls is dependent upon underlying OS.
While JFC Swing is:
-Pure Java based
-Lightweight components
-Pluggable look and feel features
-Appearance of GUI developed using JFC Swing will be consistent across various OS.
-Swing uses a more efficient event model than AWT; therefore, Swing components can run more quickly than their AWT counterparts
In AWT, all GUI controls are referred asheavyweight components as they are dependent on underlying OS(e.g. Windows,Solaris etc.) to provide it(paint it and redraw it).An AWT button control in MacOS is actually a MacOS button.
All Swing components are lightweightcomponents(except for the top-level ones: JWindow, JFrame, JDialog, and JApplet) as they do not require underlying OS to provide them.JVM renders Swing components and hence they are platform independent but they have performance related issues as compared to heavyweight components which are faster to be rendered due to hardware acceleration.
All Swing components are lightweightcomponents(except for the top-level ones: JWindow, JFrame, JDialog, and JApplet) as they do not require underlying OS to provide them.JVM renders Swing components and hence they are platform independent but they have performance related issues as compared to heavyweight components which are faster to be rendered due to hardware acceleration.
The lightweight components have transparent pixels unlike heavyweights which have opaque pixels.Mouse events on a lightweight component fall through to its parent; while on a heavyweight component it does not.It is generally not recommended to mix heavyweight components with lightweight components while building the GUI.
How can a GUI component handle its own events?
A GUI component handles its events by implementing the required event listener interface.It adds its own event listener in order to keep a track of all events associated with it.AWT has Java1.0 and Java1.1 of Event handling in different manners:
In Java1.0:Event handling is based on inheritance.A program catches and processes GUI events by subclassing GUI components and override either action() or handleEvent() methods.There are two possibilities in this scenario:
a)Each component is subclassed to specifically handle its target events. The results in too many classes.
b)All events or a subset for an entire hierarchy for handling a particular container; results in container's overridden action() or handleEvent() method and complex conditional statement for events processing.
The event handling in Java 1.0 had issues like cumbersome to handle by developers,flitering of events was not too efficient as it was done in a single method handleEvent().
In Java 1.1 these issues are resolved through delegation based event model.The GUI code can be seprated from event handling code which is cleaner,flexible,easier to maintanin and robust.In delegation event model,java.util.EventObject is the root class for event handling.An event is propagated from "Source" object(responsible for firing the event) to "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated.
A listener is commonly an "adapter" object which implements the appropriate listener/(s) for an application to handl of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other.
There can be following types of events:
A low-level event represents a low-level input or window-system occurrence on a visual component on the screen.
The semantic events are defined at a higher-level to encapsulate the semantics of a UI component's model.
The low event class hierarchy:
-java.util.EventObject
-java.awt.AWTEvent
-java.awt.event.ComponentEvent (component resized, moved, etc.)
-java.awt.event.FocusEvent (component got focus, lost focus)
-java.awt.event.InputEvent
-java.awt.event.KeyEvent (component got key-press, key-release, etc.)
-java.awt.event.MouseEvent (component got mouse-down, mouse-move, etc.)
-java.awt.event.ContainerEvent
-java.awt.event.WindowEvent
The semantics event class hierarchy:
-java.util.EventObject
-java.awt.AWTEvent
-java.awt.event.ActionEvent ("do a command")
-java.awt.event.AdjustmentEvent ("value was adjusted")
-java.awt.event.ItemEvent ("item state has changed")
-java.awt.event.TextEvent ("the value of the text object changed")
The low-level listener interfaces in AWT are as follows:
java.util.EventListener
- java.awt.event.ComponentListener
- java.awt.event.ContainerListener
- java.awt.event.FocusListener
- java.awt.event.KeyListener
- java.awt.event.MouseListener
- java.awt.event.MouseMotionListener
- java.awt.event.WindowListener
The semantic listener interfaces in AWT are as follows:
java.util.EventListener
-java.awt.event.ActionListener
-java.awt.event.AdjustmentListener
-java.awt.event.ItemListener
-java.awt.event.TextListener
There are following Adapter classes in AWT :
java.awt.event.ComponentAdapter
java.awt.event.ContainerAdapter
java.awt.event.FocusAdapter
java.awt.event.KeyAdapter
java.awt.event.MouseAdapter
java.awt.event.MouseMotionAdapter
java.awt.event.WindowAdapter
What is the difference between invokeAndWait() and invokeLater()?
invokeAndWait is synchronous. It blocks until Runnable task is complete. InvokeLater is asynchronous. It posts an action event to the event queue and returns immediately. It will not wait for the task to complete
Why should any swing call back implementation execute quickly?
Callbacks are invoked by the event dispatch thread. Event dispatch thread blocks processing of other events as long as call back method executes.
What is an applet?
Applet is a java program that runs inside a web browser.
What is the difference between applications and applets?
Application must be run explicitly within Java Virtual Machine whereas applet loads and runs itself automatically in a java-enabled browser. Application starts execution with its main method whereas applet starts execution with its init method. Application can run with or without graphical user interface whereas applet must run within a graphical user interface. In order to run an applet we need a java enabled web browser or an appletviewer.
Which method is used by the applet to recognize the height and width?
getParameters().
When we should go for codebase in applet?
If the applet class is not in the same directory, codebase is used.
What is the lifecycle of an applet?
init( ) method - called when an applet is first loaded
start( ) method - called each time an applet is started
paint( ) method - called when the applet is minimized or maximized
stop( ) method - called when the browser moves off the applet's page
destroy( ) method - called when the browser is finished with the applet
Which method is used for setting security in applets?
setSecurityManager
What is an event and what are the models available for event handling?
Changing the state of an object is called an event. An event is an event object that describes a state of change. In other words, event occurs when an action is generated, like pressing a key on keyboard, clicking mouse, etc. There different types of models for handling events are event-inheritance model and event-delegation model
What are the advantages of the event-delegation model over the event-inheritance model?
Event-delegation model has two advantages over event-inheritance model. a)Event delegation model enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component's design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.
What is source and listener ?
A source is an object that generates an event. This occurs when the internal state of that object changes in some way. A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with a source to receive notifications about specific event. Second, it must implement necessary methods to receive and process these notifications.
What is controls and what are different types of controls in AWT?
Controls are components that allow a user to interact with your application. AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.
What is the difference between choice and list?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.
What is the difference between scrollbar and scrollpane?
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its own events and perform its own scrolling.
What is a layout manager and what are different types of layout managers available?
A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout , GridBagLayout, Boxlayout and SpringLayout
What is JFC?
JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.
What is AWT?
AWT stands for Abstract Window Toolkit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons. The Java Virtual Machine (JVM) is responsible for translating the AWT calls into the appropriate calls to the host operating system.
What are the differences between Swing and AWT?
AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, But Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.
What are heavyweight components ?
A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).
What is lightweight component?
A lightweight component is one that "borrows" the screen resource of an ancestor (which means it has no native resource of its own -- so it's "lighter").
What is double buffering ?
Double buffering is the process of use of two buffers rather than one to temporarily hold data being moved to and from an I/O device. Double buffering increases data transfer speed because one buffer can be filled while the other is being emptied.
What is an event?
Changing the state of an object is called an event.
What is an event handler ?
An event handler is a part of a computer program created to tell the program how to act in response to a specific event.
What is a layout manager?
A layout manager is an object that is used to organize components in a container.
What is clipping?
Clipping is the process of confining paint operations to a limited area or shape.
Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.
What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.
What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
Which method of the Component class is used to set the position and size of a component?
setBounds
How are the elements of different layouts organized?
The elements of a FlowLayout are organized in a top to bottom, left to right fashion. The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. The elements of a CardLayout are stacked, on top of the other, like a deck of cards. The elements of a GridLayout are of equal size and are laid out using the square of a grid. The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. It is the most flexible layout.
What are types of applets?
There are two different types of applets. Trusted Applets and Untrusted applets. Trusted Applets are applets with predefined security and Untrusted Applets are applets without any security.
What are the restrictions imposed by a Security Manager on Applets?
Applets cannot read or write files on the client machine that's executing it. They cannot load libraries or access native libraries. They cannot make network connections except to the host that it came from. They cannot start any program on the client machine. They cannot read certain system properties. Windows that an applet brings up look different than windows that an application brings up.
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 relationship between an event-listener interface and an event-adapter class?
An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.
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.
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 interface is extended by AWT event listeners?
All AWT event listeners extend the java.util.EventListener interface.
What is Canvas ?
Canvas is a Component subclass which is used for drawing and painting. Canvas is a rectangular area where the application can draw or trap input events.
What is default Look-and-Feel of a Swing Component?
Java Look-and-Feel.
What are the features of JFC?
Pluggable Look-and-Feel, Accessibility API, Java 2D API, Drag and Drop Support.
What does x mean in javax.swing?
Extension of java.
What are invisible components?
They are light weight components that perform no painting, but can take space in the GUI. This is mainly used for layout management.
What is the default layout for a ContentPane in JFC?
BorderLayout.
What does Realized mean?
Realized mean that the component has been painted on screen or that is ready to be painted. Realization can take place by invoking any of these methods. setVisible(true), show() or pack().
What is difference between Swing and JSF?
The key difference is that JSF runs on server. It needs a server like Tomcat or WebLogic or WebSphere. It displays HTML to the client. But Swing program is a stand alone application.
Why does JComponent class have add() and remove() methods but Component class does not?
JComponent is a subclass of Container and can contain other components and JComponents.
What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
What is the difference between AWT and SWT?
SWT (Standard Widget Toolkit) is a completely independent Graphical User Interface (GUI) toolkit from IBM. They created it for the creation of Eclipse Integrated Development Environment (IDE). AWT is from Sun Microsystems.
What is the difference between JFC & WFC?
JFC supports robust and portable user interfaces. The Swing classes are robust, compatible with AWT, and provide you with a great deal of control over a user interface. Since source code is available, it is relatively easy to extend the JFC to do exactly what you need it to do. But the number of third-party controls written for Swing is still relatively small.
WFC runs only on the Windows (32-bit) user interface, and uses Microsoft extensions to Java for event handling and ActiveX integration. Because ActiveX components are available to WFC programs, there are theoretically more controls available for WFC than for JFC. In practice, however, most ActiveX vendors do not actively support WFC, so the number of controls available for WFC is probably smaller than for JFC. The WFC programming model is closely aligned with the Windows platform.
What is a convertor?
Converter is an application that converts distance measurements between metric and U.S units.
What is the difference between a Canvas and a Scroll Pane?
Canvas is a component. ScrollPane is a container. Canvas is a rectangular area where the application can draw or trap input events. ScrollPane implements horizontal and vertical scrolling.
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 a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
Which is the super class of all event classes?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
How the Canvas class and the Graphics class are related?
A Canvas object provides access to a Graphics object via its paint() method.
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. A window can be modal.
What is the relationship between clipping and repainting?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
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.
When should the method invokeLater() be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
What is difference between trusted and untrusted applet?
A trusted applet is one which signed by a trusted authority. The trusted applet is installed on the local hard disk, in a directory on the CLASSPATH used by the program that you are using to run the applet. Usually, this is a Java-enabled browser, but it could be the appletviewer, or other Java programs that know how to load applets.
The applet is signed by an identity marked as trusted in your identity database.By default all applets downloaded in client browser are untrusted.
-They cannot read or write files to clients' local file system at all.
-They cannot start a program at client's machine.
-They cannot do network operations i.e. cannot do Socket programming.
-They cannot load libraries and use native codes.
Why threads block or enters to waiting state on I/O?
Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed.
What are transient variables in java?
Transient variables are variable that cannot be serialized.
How Observer and Observable are used?
Subclass of Observable class maintain a list of observers. Whenever an Observable object is updated, it invokes the update() method of each of its observers to notify the observers that it has a changed state. An observer is any object that implements the interface Observer.
What is synchronization
Synchronization is the ability to control the access of multiple threads to shared resources. Synchronization stops multithreading. With synchronization , at a time only one thread will be able to access a shared resource.
What is List interface ?
List is an ordered collection of objects.
What is a Vector?
Vector is a grow able array of objects.
What is the difference between yield() and sleep()?
When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.
What are Wrapper Classes ?
They are wrappers to primitive data types. They allow us to access primitives as objects.
Can we call finalize() method ?
Yes. Nobody will stop us to call any method , if it is accessible in our class. But a garbage collector cannot call an object's finalize method if that object is reachable.
What is the difference between time slicing and preemptive scheduling ?
In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.
What is the initial state of a thread when it is created and started?
The thread is in ready state.
Can we declare an anonymous class as both extending a class and implementing an interface?
No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both
What are the differences between boolean & operator and & operator
When an expression containing the & operator is evaluated, both operands are evaluated. And the & operator is applied to the operand. When an expression containing && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated otherwise the second part will not get executed. && is also called short cut and.
What is the use of the finally block?
Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. finally will not execute when the user calls System.exit().
What is an abstract method ?
An abstract method is a method that don't have a body. It is declared with modifier abstract.
What is EJB?
Enterprise JavaBeans (EJB) technology is the server-side component architecture for the Java 2 Platform, Enterprise Edition (J2EE) platform. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology.
What are the different type of Enterprise JavaBeans ?
There are 3 types of enterprise beans, namely: Session bean, Entity beans and Message driven beans.
What is Session Bean ?
Session bean represents a single client inside the J2EE server. To access the application deployed in the server the client invokes methods on the session bean. The session bean performs the task shielding the client from the complexity of the business logic.
Session bean components implement the javax.ejb.SessionBean interface. Session beans can act as agents modeling workflow or provide access to special transient business services. Session beans do not normally represent persistent business concepts. A session bean corresponds to a client server session. The session bean is created when a client requests some query on the database and exists as long as the client server session exists.
What are different types of session bean ?
There are two types of session beans, namely: Stateful and Stateless.
What is a Stateful Session bean?
Stateful session bean maintain the state of the conversation between the client and itself. When the client invokes a method on the bean the instance variables of the bean may contain a state but only for the duration of the invocation.
A stateful session bean is an enterprise bean (EJB component) that acts as a server-side extension of the client that uses it. The stateful session bean is created by a client and will work for only that client until the client connection is dropped or the bean is explicitly removed. The stateful session bean is EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateful". Stateful session beans are called "stateful" because they maintain a conversational state with the client. In other words, they have state or instance fields that can be initialized and changed by the client with each method invocation. The bean can use the conversational state as it process business methods invoked by the client.
What is stateless session bean ?
Stateless session beans are of equal value for all instances of the bean. This means the container can assign any bean to any client, making it very scalable.
A stateless session bean is an enterprise bean that provides a stateless service to the client. Conceptually, the business methods on a stateless session bean are similar to procedural applications or static methods; there is no instance state, so all the data needed to execute the method is provided by the method arguments. The stateless session bean is an EJB component that implements the javax.ejb.SessionBean interface and is deployed with the declarative attribute "stateless". Stateless session beans are called "stateless" because they do not maintain conversational state specific to a client session. In other words, the instance fields in a stateless session bean do not maintain data relative to a client session. This makes stateless session beans very lightweight and fast, but also limits their behavior. Typically an application requires less number of stateless beans compared to stateful beans.
What is an Entity Bean?
An entity bean represents a business object in a persistent storage mechanism. An entity bean typically represents a table in a relational database and each instance represents a row in the table. Entity bean differs from session bean by: persistence, shared access, relationship and primary key.
What are different types of entity beans?
There are two types of entity beans available. Container Managed Persistence (CMP) , Bean managed persistence (BMP).
What is CMP (Container Managed Persistence) ?
The term container-managed persistence means that the EJB container handles all database access required by the entity bean. The bean's code contains no database access (SQL) calls. As a result, the bean's code is not tied to a specific persistent storage mechanism (database). Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that use different databases, you won't need to modify or recompile the bean's code. So, your entity beans are more portable.
What is BMP (Bean managed persistence) ?
Bean managed persistence (BMP) occurs when the bean manages its persistence. Here the bean will handle all the database access. So the bean's code contains the necessary SQLs calls. So it is not much portable compared to CMP. Because when we are changing the database we need to rewrite the SQL for supporting the new database.
What is abstract schema ?
In order to generate the data access calls, the container needs information that you provide in the entity bean's abstract schema. It is a part of Deployment Descriptor. It is used to define the bean's persistent fields and relation ships.
When we should use Entity Bean ?
When the bean represents a business entity, not a procedure. we should use an entity bean. Also when the bean's state must be persistent we should use an entity bean. If the bean instance terminates or if the J2EE server is shut down, the bean's state still exists in persistent storage (a database).
When to Use Session Beans ?
At any given time, only one client has access to the bean instance. The state of the bean is not persistent, existing only for a short period (perhaps a few hours). The bean implements a web service. Under all the above circumstances we can use session beans.
When to use Stateful session bean?
The bean's state represents the interaction between the bean and a specific client. The bean needs to hold information about the client across method invocations. The bean mediates between the client and the other components of the application, presenting a simplified view to the client. Under all the above circumstances we can use a stateful session bean.
When to use a stateless session bean?
The bean's state has no data for a specific client. In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an email that confirms an online order. The bean fetches from a database a set of read-only data that is often used by clients. Such a bean, for example, could retrieve the table rows that represent the products that are on sale this month. Under all the above circumstance we can use a stateless session bean.
1 What is the difference between JSP and Servlets ?
JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.
2 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: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags
Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
3 What are the different ways for session tracking?
Cookies, URL rewriting, HttpSession, Hidden form fields
4 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
5 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 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.
In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.
6 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. The session is stored on the server.
7 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.
8 What is servlet context ?
The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.
9 What is a servlet ?
servlet is a java program that runs inside a web container.
10 Can we use the constructor, instead of init(), to initialize servlet?
Yes. But you will not get the servlet specific things from constructor. 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 constructor 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.
12 How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets, expressions.
13 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.
14 How can I implement a thread-safe JSP page?
You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.
15 What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.
16 What are the lifecycle of JSP?
When presented with JSP page the JSP engine does the following 7 phases.
Page translation: -page is parsed, and a java file which is a servlet is created.
Page compilation: page is compiled into a class file
Page loading : This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.
17 What are context initialization parameters?
Context initialization parameters are specified by the <context-param> in the web.xml file, these are initialization parameter for the whole application.
18 What is a Expression?
Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.
19 What is a Declaration?
It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.
20 What is a Scriptlet?
A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a <jsp:useBean>. Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method.
What is messaging and how is it different from RMI?
Messaging occurs between applications or software components which may or may not be distributive in nature.In enterprise applications where the possibility of distributed components across the geographies are too high, messaging comes as an obvious choice to make them communicate with each other.
In Java , middleware(which acts as an infrastructural support for messaging) level messaging is supported with Java Message Service(JMS) APIs.JMS is a specification (java.sun.com/products/jms ) that describes the properties and behavior of an information pipe for Java software. It also describes how Java client applications interact with the information pipe.
JMS helps business applications asynchronously send and receive critical business data and events.It supports both message queueing and publish-subscribe styles of messaging.
The constituents of JMS are producers,consumers and messages themselves through interfaces' abstraction.The beauty lies here in loose coupling and infact message broker systems need not go in details of message-contents, they just have to deliver them between systems reliably.There is not dependency on APIs of systems involved in message communications.
In case of RMI, the message passing is tightly coupled with APIs of remote application or component.That is what makes JMS as an obvious choice in enterprise applications for reliable messaging.
When is JMS needed?
JMS can be used in following scenarios:
- When distributed components,applications within an enterprise need to communicate with one another without creating any sort of dependencies(loose coupling support by JMS).This communication could either be synchronous or asynchronous.
- When an application has to communicate with a provider without worrying its availability,.i.e. in an asynchronous way.A synchronous communication occurs when message requested is consumed immediately that means both producer and consumer are up and running at the same time while in case of asynchronous communication it is not necessary to have both entities available at the same time. An application may like to send a message to other without waiting for response and keep on doing its job.
How Does the JMS API Work with the Java EE Platform?
The JMS API in the Java EE platform has the following features.
Application clients, Enterprise JavaBeans (EJB) components, and web components can send or synchronously receive a JMS message. Application clients can in addition receive JMS messages asynchronously. (Applets, however, are not required to support the JMS API.)
Message-driven beans, which are a kind of enterprise bean, enable the asynchronous consumption of messages. A JMS provider can optionally implement concurrent processing of messages by message-driven beans.
Message send and receive operations can participate in distributed transactions, which allow JMS operations and database accesses to take place within a single transaction.
The JMS API enhances the Java EE platform by
-allowing loosely coupled, reliable, asynchronous interactions among Java EE components and legacy systems capable of messaging.
-supporting distributed transactions and allowing for the concurrent consumption of messages. For more information, see the Enterprise JavaBeans specification, v3.0.
Moreover, a JMS provider can be integrated with the application server using the Java EE Connector architecture. You access the JMS provider through a resource adapter. This capability allows vendors to create JMS providers that can be plugged in to multiple application servers, and it allows application servers to support multiple JMS providers.
Explain JMS API Architecture.
A JMS application is consisted of the following parts as shown in the figure at the end of this post:
-JMS Provider is a messaging system that implements the JMS interfaces and provides administrative and control features.
-JMS Clients are any Java EE application component except Applets.
-Messages are objects that exchange information between JMS clients.
-Administrative objects are preconfigured JMS objects created by an administrator for the use of clients.
Administrative tools bind destinations and connection factories into a JNDI namespace. A JMS client can then use resource injection to access the administered objects in the namespace and then establish a logical connection to the same objects through the JMS provider.
Explain Point-to-Point Messaging Domain
The constituents of a point-to-point (PTP) product or application are message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from specific queue(s) . Queues retain all messages sent to them until the messages are consumed or until the messages expire.
So in PTP messaging domain:-
Each message has only one consumer.
There are no timing dependencies on a sender and a receiver of a message. The receiver can fetch the message oblivious of its availability when the client sent the message.
The receiver acknowledges the successful processing of a message.
PTP messaging is used when every message sent must be processed successfully by one consumer.
Explain Publish/Subscribe Messaging Domain.
In a publish/subscribe (pub/sub) product or application, clients(publishers as well as subscribers) address messages to a topic, which functions similar to a bulletin board. Both publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.
Pub/sub messaging has the following characteristics.
Each message can have multiple consumers.
Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.
1 What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment
2 What are stored procedures?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled. Each Database has it's own stored procedure language,
3 What is JDBC Driver ?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database.
4 What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class. Then we can open a connection. By using this connection , we can create a statement object and this object will help us to execute the query.
5 What is DriverManager ?
DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers.
6 What is a ResultSet ?
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
7 What is Connection?
Connection class represents a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
8 What does Class.forName return?
A class as loaded by the classloader.
9 What is Connection pooling?
Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.
10 What are the different JDB drivers available?
There are mainly four type of JDBC drivers available. They are:
Type 1 : JDBC-ODBC Bridge Driver - A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.
Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
Type 4: JDBC Net pure Java Driver - A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.
11 What is the fastest type of JDBC driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. 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).
12 Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading.
13 What is cold backup, hot backup, warm backup recovery?
Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is 'online backup' ) is a backup taken of each tablespace while the database is running and is being accessed by the users
14What is the advantage of denormalization?
Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
15 How do you handle your own transaction ?
Connection Object has a method called setAutocommit (boolean flag) . For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.