java_full-technical questions and answers

225
TAKEN FRM 75 TO 144 CONTENTS SERVLET.... ........... .......... ........... .......... ........... .......... ........... .......... ........... .......... ................ 55 XML.................................................................................................................................... 190 83. CAN MULTIPLE XML NAMESPACE DECLARATIONS BE IN SCOPE AT THE SAME TIME? ................................................................................................................................ 209 JAVA 1. What does a well-written OO program look like? A well-written OO program exhibits recurring structures that promote abstraction, flexibility, modularity and elegance. 2. 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. 3. 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. 4. What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class? Strategically speaking, threads created by implementing Runnab le 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. 5. 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 NullPointerExce ption 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. 6. 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("pa th-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. 7. What is a platform? A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000 and XP, Linux, Solaris, and MacOS. 8. What is transient variable? Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null. 9. 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. 10. What do you understand by Synchronization? 1

Upload: benaribo

Post on 02-Mar-2016

142 views

Category:

Documents


0 download

DESCRIPTION

Technical Interview on Java

TRANSCRIPT

Page 1: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 1/225

TAKEN FRM 75 TO 144

CONTENTS

SERVLET.............................................................................................................................55

XML.................................................................................................................................... 190

83. CAN MULTIPLE XML NAMESPACE DECLARATIONS BE IN SCOPE AT THE SAME

TIME? ................................................................................................................................ 209

JAVA

1. What does a well-written OO program look like?

A well-written OO program exhibits recurring structures that promote abstraction, flexibility, modularity andelegance.

2. 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 aforeign concept for someone who has only coded in Java. Virtual functions or virtual methods are functions ormethods that will be redefined in derived classes.

3. Jack developed a program by using a Map container to hold key/value pairs. He wanted to make a change tothe map. He decided to make a clone of the map in order to save the original data on side. What do you thinkof 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.

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

5. What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following things happen, theNullPointerException is thrown: --Calling the instance method of a null object. --Accessing or modifying thefield 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 aruntime exception. The best practice is to catch such exception even if it is not required by language design.

6. 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 calledfirst before any initialization happens. Note that the static block position may matter.

7. What is a platform?

A platform is the hardware or software environment in which a program runs. Most platforms can be describedas a combination of the operating system and hardware, like Windows 2000 and XP, Linux, Solaris, andMacOS.

8. What is transient variable?

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

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

10. What do you understand by Synchronization?

1

Page 2: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 2/225

Synchronization is a process of controlling the access of shared resources by the multiple threads in such amanner that only one thread can access one resource at a time. In non synchronized multithreadedapplication, 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.}}

11. What is Collection API?

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

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

13. What is similarities/difference between an Abstract class and Interface?

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

Neither Abstract classes or Interface can be instantiated.

14. How to define an Abstract class?

A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.Example of Abstract class:abstract class testAbstractClass {protected String myString;public String getMyString() {return myString;}public abstract string anyAbstractFunction();}

15. How to define an Interface?

In Java Interface defines the methods but does not implement them. Interface can include constants. A classthat implements the interfaces is bound to implement all the methods defined in Interface.Emaple of Interface:

public interface sampleInterface {public void functionOne();

public long CONSTANT_ONE = 1000;}

16. How to make a class or a bean serializable?

By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as oneclass in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.

17. How many methods in the Serializable interface?

There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the objectserialization tools that your class is serializable.

18. How many methods in the Externalizable interface?

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

2

Page 3: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 3/225

19. What is the difference between Serializalble and Externalizable interface?

When you use Serializable interface, your class is serialized automatically by default. But you can overridewriteObject() and readObject() two methods to control more complex object serailization process. When youuse Externalizable interface, you have a complete control over your class's serialization process.

20. What is a transient variable?

A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you

can mark that field transient or static.

21. Which containers use a border layout as their default layout?

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

22. 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. TheObserver interface is implemented by objects that observe Observable objects.

23. What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads toshared 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 tosignificant errors.

24. 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 onlyexecutes a synchronized method after it has acquired the lock for the method's object or class. Synchronizedstatements are similar to synchronized methods. A synchronized statement can only be executed after athread has acquired the lock for the object or class referenced in the synchronized statement.

25. 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 unsuccessfullyattempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waitingstate by invoking its (deprecated) suspend() method.

26. Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

27. What's new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

28. 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 displaynormally.

29. What method is used to specify a container's layout?

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

30. Which containers use a FlowLayout as their default layout?

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

31. What is thread?

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

32. What is multi-threading?

Multi-threading means various threads that run in a system.

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

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

3

Page 4: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 4/225

35. 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 anythread other than the one that explicitly claimed it.

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

37. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

38. 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() methodwhen the thread is initially executed.

39. 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 communicateeach other.

40. What are the high-level thread states?

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

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

42. 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 anobject's lock, it enters the waiting state until the lock becomes available.

43. What is the difference between Process and Thread?

A process can contain multiple threads. In most multithreading operating systems, a process gets its ownmemory 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 tothat process; that's why several threads may access the same object. Typically, even though they share acommon heap, threads have their own stack space. This is how one thread's invocation of a method is keptseparate 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 anrun on its own vs. Cannot run on its own Unit of allocation vs. Unit of execution Have its own memory spacevs. 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 anotherthread

44. What is the Collections API?

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

45. What is the List interface?The List interface provides support for ordered collections of objects.

46. What is the Vector class?

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

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

48. 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 theclass in which it is declared.

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

50. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

4

Page 5: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 5/225

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it isusually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bitand larger bit patterns.

51. Is sizeof a keyword?

The sizeof operator is not a keyword in Java.

52. What are wrapped classes?

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

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

54. 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 ahigher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time andthen reenters the pool of ready tasks. The scheduler then determines which task should execute next, basedon priority and other factors.

55. Name Component subclasses that support painting?

The Canvas, Frame, Panel, and Applet classes support painting.

56. What is a native method?

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

57. How can you write a loop indefinitely?

for(;;)--for loop; while(true)--always true, etc.

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

59. What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processingbefore the object is garbage collected.

60. Which class is the superclass for every class.

Object.

61. 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()

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

63. What is the numeric promotion?

Numeric promotion is used with both unary and binary bitwise operators. This means that byte, char, and shortvalues 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. Forexample: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.

64. Is the numeric promotion available in other plantform?

Yes. Because Java is implemented using a platform-independent virtual machine, bitwise operations alwaysyield the same result, even when run on machines that use radically different CPUs.

5

Page 6: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 6/225

65. 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 firstoperand 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 evaluationof the second operand is skipped.Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details asabove.

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

66. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

67. Which Container method is used to cause a container to be laid out and redisplayed?

validate()

68. 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 providesthe capability to specify a set of default values to be used.

69. What is the purpose of the Runtime class?

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

70. What is the purpose of the System class?

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

71. 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 isthrown or caught.

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

73. What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has noimplementation.

74. What is the difference between interface and abstract class?

interface contains methods that must be abstract; abstract class may contain concrete methods. interfacecontains variables that must be static and final; abstract class may contain non-final and final variables.members in an interface are public by default, abstract class may contain non-public members. interface isused to "implements"; whereas abstract class is used to "extends". interface can be used to achieve multiple

inheritance; abstract class can be used as a single inheritance. interface can "extends" another interface,abstract class can "extends" another class and "implements" multiple interfaces. interface is absolutelyabstract; abstract class can be invoked if a main() exists. interface is more flexible than abstract class becauseone class can only "extends" one super class, but "implements" multiple interfaces. If given a choice, useinterface instead of abstract class.

75. What is a static method?

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

76. What is a protected method?

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

77. What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class's outer class.A static inner class does not have any object instances.

78. What is an object's lock and which object's have locks?

6

Page 7: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 7/225

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

79. When can an object reference be cast to an interface reference?

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

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

81. What is the difference between a Window and a Frame?

Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. Forexample, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unixplatform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the

 java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Javaplatform communicates with the Motif Buttons using the Java Native Interface. For each and every componentadded to the application, there is an additional overhead tied to the local windowing system, which is whythese components are called heavy weight.

82. Which package has light weight components?

 javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweightcomponents.

83. What are peerless components?

The peerless components are called light weight components.

84. 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 aFont object

85. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream classhierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy isbyte-oriented.

86. What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Errorand Exception types.

87. What is the difference between throw and throws keywords?

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

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

89. What is the Map interface?

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

90. Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its superclasses.

91. Name primitive Java types.

The primitive types are byte, char, short, int, long, float, double, and boolean.

92. Which class should you use to obtain design information about an object?

The Class class is used to obtain information about an object's design.

92. How can a GUI component handle its own events?

7

Page 8: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 8/225

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

93. How are the elements of a GridBagLayout organized?

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

94. 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. SinceJava's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

95. What are the problems faced by Java programmers who don't use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed acrossmultiple windowing systems and finding a common sizing and positioning that will work within the constraintsimposed by each windowing system.

96. What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-staticvariables take on unique values with each object instance.

97. 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() tobe invoked by the AWT painting thread.

98. What is the purpose of the File class?

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

99. What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.

100. What restrictions are placed on method overriding?

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

101. What is casting?

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

102. Name Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

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

104. How are this() and super() used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

105. How is it possible for two String objects with identical values not to be equal under the == operator? Howare this() and super() used with constructors?

The == operator compares two objects to determine if they are the same objects in memory. It is possible fortwo String objects to have the same value, but located in different areas of memory.

106. What is an IO filter?

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

107. What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allowduplicate elements.

8

Page 9: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 9/225

108. What is the List interface?

The List interface provides support for ordered collections of objects.

109. 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 enabledwhen a listener is added to an object for a particular event. The enableEvents() method is used by objects thathandle events by overriding their event-dispatch methods.

110. What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile classprovides the methods needed to directly access data contained in any part of a file.

111. What interface must an object implement before it can be written to a stream as an object?

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

112. What is the ResourceBundle class?

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

113. What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its ownevents and performs its own scrolling.

114. What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A package is used to create a separate namespace for groups of classes and interfaces. Packages are also used to organize related classes and interfacesinto a single API unit and to control accessibility to these classes and interfaces.

115. What are the Object and Class classes used for?

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

116. What is Serialization and deserialization?

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

117. What is tunnelling?

Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to make RMI application get throughfirewall. In CS world, tunnelling means a way to transfer data.

118. Does the code in finally block get executed if there is an exception and a return statement in a catchblock?

If an exception occurs and there is a return statement in catch block, the finally block is still executed. The

finally block will not be executed when the System.exit(1) statement is executed earlier or the system shutdown earlier or the memory is used up earlier before the thread goes to finally block.

119. How do you restrict a user to cut and paste from the html page?

Using Servlet or client side scripts to lock keyboard keys. It is one of solutions.

120. Is Java a super set of JavaScript?

No. They are completely different. Some syntax may be similar.

121. What is a Container in a GUI?

A Container contains and arranges other components (including other containers) through the use of layoutmanagers, which use specific layout policies to determine where components should go as a function of thesize of the container.

122. How the object oriented approach helps us keep complexity of software development under control?

We can discuss such issue from the following aspects:

1. Objects allow procedures to be encapsulated with their data to reduce potential interference.

9

Page 10: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 10/225

2. Inheritance allows well-tested procedures to be reused and enables changes to make once and haveeffect in all relevant places.

3. The well-defined separations of interface and implementation allow constraints to be imposed oninheriting classes while still allowing the flexibility of overriding and overloading.

123. What is polymorphism?

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

124. What is design by contract?

The design by contract specifies the obligations of a method to any other methods that may use its servicesand also theirs to it. For example, the preconditions specify what the method required to be true when themethod is called. Hence making sure that preconditions are. Similarly, postconditions specify what must betrue when the method is finished, thus the called method has the responsibility of satisfying the postconditions.In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.

125. What are use cases?

A use case describes a situation that a program might encounter and what behavior the program should exhibitin that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally,

anticipate all the standard circumstances and many of the extraordinary circumstances possible so that theprogram will be robust.

126. What is scalability and performance?

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

127. What is the benefit of subclass?

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

128. How to add menushortcut to menu item?

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

129. Where and how can you use a private constuctor.

Private constructor can be used if you do not want any other class to instanstiate it by using new. Theinstantiation is done from a static public method, which is used when dealing with the factory method pattern.

130. In System.out.println(),what is System,out and println,pls explain?

System is a predefined final class,out is a PrintStream object acting as a field member and println is a built-inoverloaded method in the out object.

131. What is meant by "Abstract Interface"?

First, an interface is abstract. That means you cannot have any implementation in an interface. All the methodsdeclared in an interface are abstract methods or signatures of the methods.

132. Can you make an instance of an abstract class? For example - java.util.Calender is an abstractclass with a method getInstance() which returns an instance of the Calender class.

No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have anabstract class and you want to use a method which has been implemented, you may need to subclass thatabstract class, instantiate your subclass and then call that method.

133. What is the output of x > y? a:b = p*q when x=1,y=2,p=3,q=4?

When this kind of question has been asked, find the problems you think is necessary to ask back before yougive an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say

that the syntax is wrong. If the statement is rewritten as: x< returned. is a variable and true return statementy="2;" x the than less 1 because be would value a:(b="p*q);">

134. What is the difference between Swing and AWT components?

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

10

Page 11: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 11/225

135. Why Java does not support pointers?

Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to dealwith reference types without pointers. This is why Java and C-sharp shine.

136. Parsers? DOM vs SAX parser

Parsers are fundamental xml components, a bridge between XML documents and applications that process thatXML. The parser is responsible for handling xml syntax, checking the contents of the document against

constraints established in a DTD or Schema.DOM1. Tree of nodes2. Memory: Occupies more memory, preffered for small XML documents3. Slower at runtime4. Stored as objects5. Programmatically easy6. Ease of navigationSAX1. Sequence of events2. Doesn't use any memory preferred for large documents3. Faster at runtime4. Objects are to be created5. Need to write code for creating objects6. Backward navigation is not possible as it sequentially processes the document

137. Can you declare a class as private?

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

class MyPrivate {private static class MyKey {

String key = "12345";}public static void main(String[] args) {

System.out.println(new MyKey().key);//prints 12345}

}

138. What is the difference between shallow copy and deep copy?

Shallow copy shares the same reference with the original object like cloning, whereas the deep copy get aduplicate instance of the original object. If the shallow copy has been changed, the original object will bereflected and vice versa.

139. Can one create a method which gets a String and modifies it?

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

140. Why is multiple inheritance not possible in Java?

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

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

141. Can Java code be compiled to machine dependent executable file?

Yes. There are many tools out there. If you did so, the generated exe file would be run in the specific platform,not cross-platform.

142. What is the relationship between synchronized and volatile keyword?

The JVM is guaranteed to treat reads and writes of data of 32 bits or less as atomic.(Some JVM might treatreads and writes of data of 64 bits or less as atomic in future) For long or double variable, programmers shouldtake care in multi-threading environment. Either put these variables in a synchronized method or block, ordeclare them volatile.

143. This class (IncrementImpl) will be used by various threads concurrently; can you see the inherentflaw(s)? How would you improve it?

public class IncrementImpl {private static int counter = 0;public synchronized void increment() {

11

Page 12: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 12/225

counter++;}public int getCounter() {

return counter;}

}

The counter is static variable which is shared by multiple instances of this class. The increment() method issynchronized, but the getCounter() should be synchronized too. Otherwise the Java run-time system will notguarantee the data integrity and the race conditions will occur. The famous producer/consumer example listed

at Sun's thread tutorial site will tell more.one of solutions

public class IncrementImpl {private static int counter = 0;public synchronized void increment() {

counter++;}public synchronized int getCounter() {

return counter;}

}

144. What are the drawbacks of inheritance?

Since inheritance inherits everything from the super class and interface, it may make the subclass tooclustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation. Inaddition, the inheritance may make peers hardly understand your code if they don't know how your super-classacts and add learning curve to the process of development.Usually, when you want to use a functionality of a class, you may use subclass to inherit such function or usean instance of this class in your class. Which is better, depends on your specification.

145. Is there any other way that you can achieve inheritance in Java?

There are a couple of ways. As you know, the straight way is to "extends" and/or "implements". The other wayis to get an instance of the class to achieve the inheritance. That means to make the supposed-super-class bea field member. When you use an instance of the class, actually you get every function available from thisclass, but you may lose the dynamic features of OOP

146. Two methods have key words static synchronized and synchronized separately. What is the differencebetween them?

Both are synchronized methods. One is instance method, the other is class method. Method with static modifier

is a class method. That means the method belongs to class itself and can be accessed directly with class nameand is also called Singleton design. The method without static modifier is an instance method. That means theinstance method belongs to its object. Every instance of the class gets its own copy of its instance method.When synchronized is used with a static method, a lock for the entire class is obtained. When synchronized isused with a non-static method, a lock for the particular object (that means instance) of the class is obtained.Since both methods are synchronized methods, you are not asked to explain what is a synchronized method.You are asked to tell the difference between instance and class method. Of course, your explanation to howsynchronized keyword works doesn't hurt. And you may use this opportunity to show your knowledge scope.

147. How do you create a read-only collection?

The Collections class has six methods to help out here:1. unmodifiableCollection(Collection c)2. unmodifiableList(List list)3. unmodifiableMap(Map m)

4. unmodifiableSet(Set s)5. unmodifiableSortedMap(SortedMap m)6. unmodifiableSortedSet(SortedSet s)If you get an Iterator from one of these unmodifiable collections, when you call remove(), it will throw anUnsupportedOperationException.

148. Can a private method of a superclass be declared within a subclass?

Sure. A private field or method or inner class belongs to its declared class and hides from its subclasses. Thereis no way for private stuff to have a runtime overloading or overriding (polymorphism) features.

149. Why Java does not support multiple inheritance ?

This is a classic question. Yes or No depends on how you look at Java. If you focus on the syntax of "extends"and compare with C++, you may answer 'No' and give explanation to support you. Or you may answer 'Yes'.Recommend you to say 'Yes'.Java DOES support multiple inheritance via interface implementation. Some people may not think in this way.Give explanation to support your point.

150. What is the difference between final, finally and finalize?

12

Page 13: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 13/225

Short answer:final - declares constantfinally - relates with exception handlingfinalize - helps in garbage collectionIf asked to give details, explain:final field, final method, final classtry/finally, try/catch/finallyprotected void finalize() in Object class

151. What kind of security tools are available in J2SE 5.0?

There are three tools that can be used to protect application working within the scope of security policies set atremote sites.keytool -- used to manage keystores and certificates.

 jarsigner -- used to generate and verify JAR signatures.policytool -- used for managing policy files.There are three tools that help obtain, list and manage Kerberos tickets.kinit -- used to obtain Kerberos V5 tickets.tklist -- used to list entries in credential cache and key tab.ktab -- used to help manage entries in the key table.

152. How to make an array copy from System?

There is a method called arraycopy in the System class. You can do it:System.arraycopy(sourceArray, srcOffset, destinationArray, destOffset, numOfElements2Copy);When you use this method, the destinationArray will be filled with the elements of sourceArray at the length

specified.

153. Can we use System.arraycopy() method to copy the same array?

Yes, you can. The source and destination arrays can be the same if you want to copy a subset of the array toanother area within that array.

154. What is shallow copy or shallow clone in array cloning?

Cloning an array invloves creating a new array of the same size and type and copying all the old elements intothe new array. But such copy is called shallow copy or shallow clone because any changes to the object wouldbe reflected in both arrays.

155. When is the ArrayStoreException thrown?

When copying elements between different arrays, if the source or destination arguments are not arrays or theirtypes are not compatible, an ArrayStoreException will be thrown.

156. How to check two arrays to see if contents have the same types and contain the same elements?

One of options is to use the equals() method of Arrays class.Arrays.equals(a, b);If the array types are different, a compile-time error will happen.

157. Do not use the String contatenation operator in lengthy loops or other places where performance couldsuffer. Is that true?

Yes.

158. What are the different types of inner classes?

There are four different types of inner classes in Java. They are: a)Static member classes , a static memberclass has access to all static methods of the parent, or top-level, class b) Member classes, the member class isinstance specific and has access to any and all methods and members, even the parent's this reference c) Localclasses, are declared within a block of code and are visible only within that block, just as any other methodvariable. d) Anonymous classes, is a local class that has no name

159. In which case would you choose a static inner class?

Interesting one, static inner classes can access the outer class's protected and private fields. This is both apositive and a negitive point for us since we can, in essence, violate the encapsulation of the outer class bymucking up the outer class's protected and private fields. The only proper use of that capability is to writewhite-box tests of the class -- since we can induce cases that might be very hard to induce via normal black-box tests (which don't have access to the internal state of the object). Second advantage,if I can say, is that,we can this static concept to impose restriction on the inner class. Again as discussed in earlier point, an Innerclass has access to all the public, private and protected members of the parent class. Suppose you want to

restrict the access even to inner class, how would you go ahead? Making the inner class static enforces it toaccess only the public static members of the outer class( Since, protected and private members are notsupposed to be static and that static members can access only other static members). If it has to access anynon-static member, it has to create an instance of the outer class which leads to accessing only publicmembers.

13

Page 14: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 14/225

160. What is the differnce between final, finally and finalize?

final is used for making a class no-subclassable, and making a member variable as a constant which cannot bemodified. finally is usuall used to release all the resources utilized inside the try block. All the resources presentin the finalize method will be garbage collected whenever GC is called. Though finally and finalize seem to befor a similar task there is an interesting tweak here, usually I prefer finally than finalize unless it isunavoidable. This is because the code in finally block is guranteed of execution irrespective of occurance of exception, while execution of finalize is not guarenteed.finalize method is called by the garbage collector on anobject when the garbage collector determines that there are no more references to the object. Presumably thegarbage collector will, like its civil servant namesake, visit the heap on a regular basis to clean up resourcesthat are no longer in use. Garbage collection exists to prevent programmers from calling delete. This is awonderful feature. For example, if you can't call delete, then you can't accidentally call delete twice on thesame object. However, removing delete from the language is not the same thing as automatically cleaning up.To add to it, Garbage collection might not ever run. If garbage collection runs at all, and an object is no longerreferenced, then that object's finalize will run. Also, across multiple objects, finalize order is not predictable.The correct approach to resource cleanup in Java language programs does not rely on finalize. Instead, yousimply write explicit close methods for objects that wrap native resources. If you take this approach, you mustdocument that the close method exists and when it should be called. Callers of the object must then rememberto call close when they are finished with a resource.

161. What is weak reference in Java

A weak reference is one that does not prevent the referenced object from being garbage collected. You mightuse them to manage a HashMap to look up a cache of objects. A weak reference is a reference that does not

keep the object it refers to alive. A weak reference is not counted as a reference in garbage collection. If theobject is not referred to elsewhere as well, it will be garbage collected.

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

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up toone second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() isdefined in the class Object and the method sleep() is defined in the class Thread.

163. The following statement prints true or false, why?

byte[] a = { 1, 2, 3 };,byte[] b = (byte[]) a.clone();System.out.println(a == b);The false will be printed out. Because the two arrays have distinctive memory addresses. Starting in Java 1.2,we can use java.util.Arrays.equals(a, b) to compare whether two arrays have the same contents.

164. Why do we need to use getSystemResource() and getSystemResources() method to load resources?

Because we want to look for resources strictly from the system classpath, These methods use the systemClassLoader to locate resources, which gives you stricter control of the resources used by the application.

165.ArithmeticException?

The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number byzero. It is never thrown in floating-point operations.

166. What is a transient variable?

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

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

168. 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/OOperation is performed.

169. Wha is the output from System.out.println("Hello"+null);?

Hellonull

170. 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 anotherthread is in the process of using or updating that object's value. This often leads to significant errors.

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

14

Page 15: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 15/225

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

173. Is null a keyword?

The null value is not a keyword.

174. 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 displaynormally.

175. What method is used to specify a container's layout?

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

176. Which containers use a FlowLayout as their default layout?

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

177. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

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

179. which characters may be used as the second character of an identifier, but not as the first character of anidentifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after thefirst character of an identifier.

180. What is the List interface?

The List interface provides support for ordered collections of objects.

181. 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.182. What is the Vector class?

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

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

184. What is an Iterator interface?

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

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

186. Which method of the Component class is used to set the position and size of a component?

setBounds()

187. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it isusually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bitand larger bit patterns.

188. What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method,it returns to the waiting state.

189. Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing.

190. Is sizeof a keyword?

15

Page 16: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 16/225

The sizeof operator is not a keyword.

191. What are wrapper classes?

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

192. 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 programsto use up memory resources faster than they are garbage collected. It is also possible for programs to createobjects that are not subject to garbage collection.

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

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

195. What is the immediate superclass of the Applet class?

Panel

196. 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 ahigher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time andthen reenters the pool of ready tasks. The scheduler then determines which task should execute next, basedon priority and other factors.

197. Name three Component subclasses that support painting.

The Canvas, Frame, Panel, and Applet classes support painting.

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

199. What is the immediate superclass of the Dialog class?

Window.

200. What is clipping?

Clipping is the process of confining paint operations to a limited area or shape.

201. What is a native method?

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

202. Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

203. What are order of precedence and associativity, and how are they used?

Order of precedence determines the order in which operators are evaluated in expressions. Associatitydetermines whether an expression is evaluated left-to-right or right-to-left

204. When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O.

205. To what value is a variable of the String type automatically initialized?

The default value of a String type is null.

206. 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 theexception or declare it in its throws clause.

207. 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 orunchecked.

208. What is a task's priority and how is it used in scheduling?

16

Page 17: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 17/225

A task's priority is an integer value that identifies the relative order in which it should be executed with respectto other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

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

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

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

212. What is the range of the short type?

The range of the short type is -(2^15) to 2^15 - 1.

213. What is the range of the char type?

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

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

215. What is the immediate superclass of Menu?

What is the immediate superclass of Menu? MenuItem

216. What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processingbefore the object is garbage collected.

217. Which class is the immediate superclass of the MenuComponent class.

Object

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

219. 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 firstoperand 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 evaluationof the second operand is skipped.

220. Name three subclasses of the Component class.

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent

221. What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

222. Which Container method is used to cause a container to be laid out and redisplayed?

validate()

223. What is the purpose of the Runtime class?

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

224. How many times may an object's finalize() method be invoked by the garbage collector?

An object's finalize() method may only be invoked once by the garbage collector.

225. What is the purpose of the finally clause of a try-catch-finally statement? garbage collector?

The finally clause is used to provide the capability to execute code no matter whether or not an exception isthrown or caught.

226. What is the argument type of a program's main() method?

17

Page 18: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 18/225

A program's main() method takes an argument of the String[] type.

227. Which Java operator is right associative?

The = operator is right associative.

228. What is the Locale class?

The Locale class is used to tailor program output to the conventions of a particular geographic, political, orcultural region.

229. Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.

230. What is the difference between a break statement and a continue statement?

A break statement results in the termination of the statement to which it applies (switch, for, do, or while). Acontinue statement is used to end the current loop iteration and return control to the loop statement.

231. What must a class do to implement an interface?

It must provide all of the methods in the interface and identify the interface in its implements clause.

232. What method is invoked to cause an object to begin executing as a separate thread?

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

233. Name two subclasses of the TextComponent class.

TextField and TextArea

234. What is the advantage of the event-delegation model over the earlier event-inheritance model?

The event-delegation model has two advantages over the event-inheritance model. First, it enables eventhandling to be handled by objects other than the ones that generate the events (or their containers). Thisallows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. Thisperformance improvement is due to the fact that the event-delegation model does not have to repeatedlyprocess unhandled events, as is the case of the event-inheritance model.

235. Which containers may have a MenuBar?Frame

236. How are commas used in the initialization and iteration parts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a forstatement.

237. 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 wait for ashared resource. When a thread executes an object's wait() method, it enters the waiting state. It only entersthe ready state after another thread invokes the object's notify() or notifyAll() methods.

238. What is an abstract method?

An abstract method is a method whose implementation is deferred to a subclass.

239. How are Java source code files named?

A Java source code file takes the name of a public class or interface that is defined within the file. A sourcecode file may contain at most one public class or interface. If a public class or interface is defined within asource code file, then the source code file must take the name of the public class or interface. If no public classor interface is defined within a source code file, then the file must take on a name that is different than itsclasses and interfaces. Source code files use the .java extension.

240. What is the relationship between the Canvas class and the Graphics class?

A Canvas object provides access to a Graphics object via its paint() method.

241. What are the high-level thread states?

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

242. What value does read() return when it has reached the end of a file?

The read() method returns -1 when it has reached the end of a file.

18

Page 19: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 19/225

243. Can a Byte object be cast to a double value?

No, an object cannot be cast to a primitive value.

244. What is the difference between a static and a non-static inner class?

A non-static inner class may have object instances that are associated with instances of the class's outer class.A static inner class does not have any object instances.

245. What is the difference between the String and StringBuffer classes?

String objects are constants. StringBuffer objects are not.

246. If a variable is declared as private, where may the variable be accessed?

A private variable may only be accessed within the class in which it is declared.

247. What is an object's lock and which objects have locks?

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

248. What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.

249. How are the elements of a BorderLayout organized?

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

250. What is the % operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand bythe second operand.

251. When can an object reference be cast to an interface reference?

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

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

253. Which class is extended by all other classes?

The Object class is extended by all other classes.

254. Can an object be garbage collected while it is still reachable?

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected

255. Is the ternary operator written x : y ? z or x ? y : z ?

It is written x ? y : z.

256. 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 aFont object.

257. How is rounding performed under integer division?

The fractional part of the result is truncated. This is known as rounding toward zero.

258. 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 anobject's lock, it enters the waiting state until the lock becomes available.

259. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStreamclass hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy isbyte-oriented.

260. What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Errorand Exception types.

19

Page 20: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 20/225

261. If a class is declared without any access modifiers, where may the class be accessed?

A class that is declared without any access modifiers is said to have package access. This means that the classcan only be accessed by other classes and interfaces that are defined within the same package.

262. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

263. What is the Map interface?

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

264. Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its super classes.

265. For which statements does it make sense to use a label?

The only statements for which it makes sense to use a label are those statements that can enclose a break orcontinue statement.

266. What is the purpose of the System class?

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

267. Which TextComponent method is used to set a TextComponent to the read-only state?

setEditable()

268. How are the elements of a CardLayout organized?

The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

269. Is &&= a valid Java operator?

No, it is not.

267. Name the eight primitive Java types.

The eight primitive types are byte, char, short, int, long, float, double, and boolean.

268. Which class should you use to obtain design information about an object?

The Class class is used to obtain information about an object's design.

269. 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 windowthat requires repainting.

270. Is "abc" a primitive value?

The String literal "abc" is not a primitive value. It is a String object.

271. 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 particularkind of event. An event adapter provides a default implementation of an event-listener interface.

272. What restrictions are placed on the values of each case of a switch statement?During compilation, the values of each case of a switch statement must evaluate to a value that can bepromoted to an int value.

273. What modifiers may be used with an interface declaration?

An interface may be declared as public or abstract.

274. Is a class a subclass of itself?

A class is a subclass of itself.

275. What is the highest-level event class of the event-delegation model?

The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

276. What event results from the clicking of a button?

The ActionEvent event is generated as the result of the clicking of a button.

277. How can a GUI component handle its own events?

20

Page 21: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 21/225

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

278. What is the difference between a while statement and a do statement?

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A dostatement checks at the end of a loop to see whether the next iteration of a loop should occur. The dostatement will always execute the body of a loop at least once.

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

280. 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. SinceJava's layout managers aren't tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

281. What is the Collection interface?

The Collection interface provides support for the implementation of a mathematical bag - an unorderedcollection of objects that may contain duplicates.

282. What modifiers can be used with a local inner class?

A local inner class may be final or abstract.

283. What is the difference between static and non-static variables?

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-staticvariables take on unique values with each object instance.

284. 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() tobe invoked by the AWT painting thread.

285. What is the purpose of the File class?

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

286. Can an exception be rethrown?

Yes, an exception can be rethrown.

287. Which Math method is used to calculate the absolute value of a number?

The abs() method is used to calculate absolute values.

288. How does multithreading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching betweenexecuting tasks, it creates the impression that tasks execute sequentially.

289. When does the compiler supply a default constructor for a class?

The compiler supplies a default constructor for a class if no other constructors are provided.

290. When is the finally clause of a try-catch-finally statement executed?

The finally clause of the try-catch-finally statement is always executed unless the thread of executionterminates or an exception occurs within the execution of the finally clause.

291. Which class is the immediate superclass of the Container class?

Component

292. 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 theclass in which it is declared.

293. How can the Checkbox class be used to create a radio button?

By associating Checkbox objects with a CheckboxGroup.

294. Which non-Unicode letter characters may be used as the first character of an identifier?

21

Page 22: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 22/225

The non-Unicode letter characters $ and _ may appear as the first character of an identifier

295. What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.

296. What happens when you invoke a thread's interrupt method while it is sleeping or waiting?

When a task's interrupt() method is executed, the task enters the ready state. The next time the task entersthe running state, an InterruptedException is thrown.

297. What is casting?

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

298. What is the return type of a program's main() method?

A program's main() method has a void return type.

299. Name four Container classes.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

300. What is the difference between a Choice and a List?

A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices.Only one item may be selected from a Choice. A List may be displayed in such a way that several List items arevisible. A List supports the selection of one or more List items.

301. What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions.

302. What class allows you to read objects directly from a stream?

The ObjectInputStream class supports the reading of objects from input streams.

303. What is the difference between a field variable and a local variable?

A field variable is a variable that is declared as a member of a class. A local variable is a variable that isdeclared local to a method.

304. Under what conditions is an object's finalize() method invoked by the garbage collector?

The garbage collector invokes an object's finalize() method when it detects that the object has becomeunreachable.

305. How are this () and super () used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

306. What is the relationship between a method's throws clause and the exceptions that can be thrown duringthe method's execution?

A method's throws clause must declare any checked exceptions that are not caught within the body of themethod.

307. What is the difference between the JDK 1.02 event model and the event-delegation model introduced withJDK 1.1?

The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components arerequired to handle their own events. If they do not handle a particular event, the event is inherited by (orbubbled up to) the component's container. The container then either handles the event or it is bubbled up to itscontainer and so on, until the highest-level container has been tried. In the event-delegation model, specificobjects are designated as event handlers for GUI components. These objects implement event-listenerinterfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminatesthe processing required to support the bubbling of unhandled events.

308. How is it possible for two String objects with identical values not to be equal under the ==operator?

The == operator compares two objects to determine if they are the same object in memory. It is possible fortwo String objects to have the same value, but located indifferent areas of memory.

309. Why are the methods of the Math class static?

So they can be invoked as if they are a mathematical code library.

22

Page 23: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 23/225

310. What Checkbox method allows you to tell if a Checkbox is checked?

getState()

311. What state is a thread in when it is executing?

An executing thread is in the running state.

312. What are the legal operands of the instanceof operator?The left operand is an object reference or null value and the right operand is a class, interface, or array type.

313. How are the elements of a GridLayout organized?

The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.

314. What an I/O filter?

An I/O filter is an object that reads from one stream and writes to another, usually altering the data in someway as it is passed from one stream to another.

315. If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

316. What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allowduplicate elements.

317. What classes of exceptions may be thrown by a throw statement?

A throw statement may throw any expression that may be assigned to the Throwable type.

318. What are E and PI?

E is the base of the natural logarithm and PI is mathematical value pi.

319. Are true and false keywords?

The values true and false are not keywords.

320. What is a void return type?

A void return type indicates that a method does not return a value.

321. 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 enabledwhen a listener is added to an object for a particular event. The enableEvents() method is used by objects thathandle events by overriding their event-dispatch methods.

322. What is the difference between the File and RandomAccessFile classes?

The File class encapsulates the files and directories of the local file system. The RandomAccessFile classprovides the methods needed to directly access data contained in any part of a file.

323. What happens when you add a double value to a String?

The result is a String object.

324. What is your platform's default character encoding?

If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java onEnglish Solaris platforms, it is most likely 8859_1..

325. Which package is always imported by default?

The java.lang package is always imported by default.

326. What interface must an object implement before it can be written to a stream as an object?

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

327. How are this and super used?

this is used to refer to the current object instance. super is used to refer to the variables and methods of thesuperclass of the current object instance.

23

Page 24: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 24/225

328. What is the purpose of garbage collection?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program sothat their resources may be reclaimed and reused.

329. What is a compilation unit?

A compilation unit is a Java source code file.

330. What interface is extended by AWT event listeners?

All AWT event listeners extend the java.util.EventListener interface.

331. What restrictions are placed on method overriding?

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

332. How can a dead thread be restarted?

A dead thread cannot be restarted.

333. What happens if an exception is not caught?

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked,

which eventually results in the termination of the program in which it is thrown.

334. What is a layout manager?

A layout manager is an object that is used to organize components in a container.

335. Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException.

336. What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfullyattempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waitingstate by invoking its (deprecated) suspend() method.

337. Can an abstract class be final?

An abstract class may not be declared as final.

338. What is the ResourceBundle class?

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

339. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that isthrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program'stermination.

340. What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer andfloating-point operations may take place. In numerical promotion, byte, char, and short values are convertedto int values. The int values are also converted to long values, if necessary. The long and float values areconverted to double values, as required.

341. What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its ownevents and performs its own scrolling.

342. What is the difference between a public and a non-public class?

A public class may be accessed outside of its package. A non-public class may not be accessed outside of its

package.

343. To what value is a variable of the boolean type automatically initialized?

The default value of the boolean type is false.

344. Can try statements be nested?

24

Page 25: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 25/225

Try statements may be tested.

345. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. Thepostfix form returns the current value all of the expression and then performs the increment operation on thatvalue.

346. What is the purpose of a statement block?

A statement block is used to organize a sequence of statements as a single statement group.

347. What is a Java package and how is it used?

A Java package is a naming context for classes and interfaces. A package is used to create a separate namespace for groups of classes and interfaces. Packages are also used to organize related classes and interfacesinto a single API unit and to control accessibility to these classes and interfaces.

348. What modifiers may be used with a top-level class?

A top-level class may be public, abstract, or final.

349. What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the

classes and interfaces that are loaded by a Java program.

350. How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement areexamined in the order in which they appear. The first catch clause that is capable of handling the exception isexecuted. The remaining catch clauses are ignored.

351. Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object's finalize() method isinvoked and the object performs an operation which causes it to become accessible to reachable objects.

352. When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

353. What method must be implemented by all threads?

All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnableinterface.

354. What methods are used to get and set the text label displayed by a Button object?

getLabel() and setLabel()

355. Which Component subclass is used for drawing and painting?

Canvas

357. What are the two basic ways in which classes that can be run as threads may be defined?

A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.

358. What are the problems faced by Java programmers who don't use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed acrossmultiple windowing systems and finding a common sizing and positioning that will work within the constraintsimposed by each windowing system.

359. What is the difference between an if statement and a switch statement?

The if statement is used to select among two alternatives. It uses a boolean expression to decide whichalternative should be executed. The switch statement is used to select among multiple alternatives. It uses anint expression to determine which alternative should be executed.

360. Can there be an abstract class with no abstract methods in it?

yes.

361. Can an Interface be final?yes.

362. Can an Interface have an inner class?

25

Page 26: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 26/225

Yes public interface abc { static int i=0; void dd(); class a1 { a1() { int j; System.out.println("in interfia"); };public static void main(String a1[]) { System.out.println("in interfia"); } } }

363. Can we define private and protected modifiers for variables in interfaces?

Yes.

364. What is Externalizable?

Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in CompressedFormat. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

365. What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

366. What is a local, member and a class variable?

Variables declared within a method are "local" variables.Variables declared within the class i.e not within any methods are "member" variables (global variables).Variables declared within the class i.e not within any methods and are defined as "static" are class variables

367. I made my class Cloneable but I still get 'Can't access protected method clone. Why?

Yeah, some of the Java books, in particular "The Java Programming Language", imply that all you have to do in

order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was theintent at some point, but that's not the way it works currently. As it stands, you have to implement your ownpublic clone() method, even if it doesn't do anything special and just calls super.clone().

368. What are the different identifier states of a Thread?

The different identifiers of a Thread are:R - Running or runnable threadS - Suspended threadCW - Thread waiting on a condition variableMW - Thread waiting on a monitor lockMS - Thread suspended waiting on a monitor lock

369. What are some alternatives to inheritance?

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

370. Why isn't there operator overloading?

Because C++ has proven by example that operator overloading makes code almost impossible to maintain. Infact there very nearly wasn't even method overloading in Java, but it was thought that this was too useful forsome very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloadedmethods like writeInt() and writeByte().

371. What does it mean that a method or field is "static"?

Static variables and methods are instantiated only once per class. In other words they are class variables, notinstance variables. If you change the value of a static variable in a particular object, the value of that variablechanges for all instances of that class.Static methods can be referenced with the name of the class rather than the name of a particular object of theclass (though that works too). That's how library methods like System.out.println() work. out is a static field inthe java.lang.System class.

372. 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/oOperation is performed.

373. What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads toshared resources. Without synchronization, it is possible for one thread to modify a shared object while anotherthread is in the process of using or updating that object's value. This often leads to significant errors.

374. Is null a keyword?

The null value is not a keyword.

26

Page 27: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 27/225

375. Which characters may be used as the second character of an identifier,but not as the first character of anidentifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after thefirst character of an identifier.

376. Whats the difference between notify() and notifyAll()?

notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is

preferable (for efficiency) when only one blocked thread can benefit from the change (for example, whenfreeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume(for example, when releasing a "writer" lock on a file might permit all "readers" to resume).

377. Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?

The import statement does not bring methods into your local name space. It lets you abbreviate class names,but not get rid of them altogether. That's just the way it works, you'll get used to it. It's really a lot safer thisway.However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn't need to inherit from anything else, make it inherit from java.lang.Math. That *does* bringall the methods into your local name space. But you can't use this trick in an applet, because you have toinherit from java.awt.Applet. And actually, you can't use it on java.lang.Math at all, because Math is a "final"class which means it can't be extended.

378. Why are there no global variables in Java?

Global variables are considered bad form for a variety of reasons: · Adding state variables breaks referentialtransparency (you no longer can understand a statement or expression on its own: you need to understand itin the context of the settings of the global variables).· State variables lessen the cohesion of a program: you need to know more to understand how somethingworks. A major point of Object-Oriented programming is to break up global state into more easily understoodcollections of local state.· When you add one variable, you limit the use of your program to one instance. What you thought was global,someone else might think of as local: they may want to run two copies of your program at once.For these reasons, Java decided to ban global variables.

379. What does it mean that a class or member is final?

A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like Stringand Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier toachieve. Methods may be declared final as well. This means they may not be overridden in a subclass.Fields can be declared final, too. However, this has a completely different meaning. A final field cannot bechanged after it's initialized, and it must include an initializer statement where it's declared. For example,public final double c = 2.998;It's also possible to make a static field final to get the effect of C++'s const statement or some uses of C's#define, e.g. public static final double c = 2.998;

380. What does it mean that a method or class is abstract?

An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class isabstract with the abstract keyword like this:public abstract class Container extends Component {Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in thecurrent class. It exists only to be overridden in subclasses. It has no body. For example,public abstract float price();Abstract methods may only be included in abstract classes. However, an abstract class is not required to have

any abstract methods, though most of them do.Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declaredabstract.

381. What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.The Java platform has three elements:

1. Java programming language2. The Java Virtual Machine (Java VM)3. The Java Application Programming Interface (Java API)

382. What is the Java Virtual Machine?

The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.

383. What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities,such as graphical user interface (GUI) widgets.

27

Page 28: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 28/225

384. What is the package?

The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of relatedclasses and interfaces; these libraries are known as packages.

385. What is native code?

The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

386. Explain the user defined Exceptions?

User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An userdefined can created by simply sub-classing it to the Exception class. This allows custom exceptions to begenerated (using throw) and caught in the same way as normal exceptions.Example:class myCustomException extends Exception {

 // The class simply has to exist to be an exception}

387. Is Java code slower than native code?

Not really. As a platform-independent environment, the Java platform can be a bit slower than native code.However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performanceclose to that of native code without threatening portability.

388. Can main() method be overloaded?Yes. the main() method is a special method for a program entry. You can overload main() method in any ways.But if you change the signature of the main method, the entry point for the program will be gone.

389. What is the serialization?

The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties orfields and state information saved and restored to and from storage.

390. Explain the new Features of JDBC 2.0 Core API?

The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, andprovides inductrial-strength database computing capabilities.New Features in JDBC 2.0 Core API:

Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the toparticular row or to a position relative to its current positionJDBC 2.0 Core API provides the Batch Updates functionality to the java applications.Java applications can now use the ResultSet.updateXXX methods.New data types - interfaces mapping the SQL3 data typesCustom mapping of user-defined types (UTDs)Miscellaneous features, including performance hints, the use of character streams, full precision for

 java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestampvalues.

391. Explain garbage collection?

Garbage collection is one of the most important feature of Java. Garbage collection is also called automaticmemory management as JVM automatically removes the unused variables/objects (value is null) from thememory. User program cann't directly free the object from memory, instead it is the job of the garbagecollector to automatically free the objects that are no longer referenced by a program. Every class inheritsfinalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines

no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when nomore in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but thereis no guarantee when all the objects will garbage collected.

392. How you can force the garbage collection?

Garbage collection automatic process and can't be forced.

393. What is OOPS?

OOP is the common abbreviation for Object-Oriented Programming.

394. Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

395. Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into asingle entity. This keeps the data safe from outside interface and misuse. One way to think aboutencapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by othercode defined outside the wrapper.

28

Page 29: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 29/225

396. Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object.

397. Explain the Polymorphism principle.

The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to beused as as general category for different types of actions. The specific action is determined by the exact natureof the situation. The concept of polymorphism can be explained as "one interface, multiple methods".

398. Explain the different forms of Polymorphism.

From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:Method overloadingMethod overriding through inheritanceMethod overriding through the Java interface

399. What are Access Specifiers available in Java?

ccess specifiers are keywords that determines the type of access to the member of a class. These are:PublicProtectedPrivateDefaults

400. Describe the wrapper classes in Java.

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, aprimitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapperboolean java.lang.Booleanbyte java.lang.Bytechar java.lang.Characterdouble java.lang.Doublefloat java.lang.Floatint java.lang.Integerlong java.lang.Longshort java.lang.Shortvoid java.lang.Void

401. Question: Read the following program:

public class test {public static void main(String [] args) {int x = 3;int y = 1;if (x = y)System.out.println("Not equal");elseSystem.out.println("Equal");}

}What is the result?A. The output is “Equal” B. The output in “Not Equal” C. An error at " if (x = y)" causes compilation to fall.D. The program executes but no output is show on console.

Answer: C

402. The superclass constructor runs before the subclass constructor. The subclass's version of theoverridable method will be invoked before the subclass's constructor has been invoked. If the subclass'soverridable method depends on the proper initialization of the subclass (through the subclass constructor), themethod will most likely fail. Is that true?

Yes. It is true

403. Why are the interfaces more flexible than abstract classes?--An interface-defined type can be implemented by any class in a class hierarchy and can be extended byanother interface. In contrast, an abstract-class-defined type can be implemented only by classes that subclassthe abstract class.--An interface-defined type can be used well in polymorphism. The so-called interface type vs. implementationtypes.

29

Page 30: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 30/225

--Abstract classes evolve more easily than interfaces. If you add a new concrete method to an abstract class,the hierarchy system is still working. If you add a method to an interface, the classes that rely on the interfacewill break when recompiled.--Generally, use interfaces for flexibility; use abstract classes for ease of evolution (like expanding classfunctionality).

404. What are new language features in J2SE 5.0?

Generally:1. generics2. static imports3. annotations4. typesafe enums5. enhanced for loop6. autoboxing/unboxing7. varargs8. covariant return types

405. What is covariant return type?

A covariant return type lets you override a superclass method with a return type that subtypes the superclassmethod's return type. So we can use covariant return types to minimize upcasting and downcasting.

class Parent {Parent foo () {

System.out.println ("Parent foo() called");return this;

}}

class Child extends Parent {Child foo () {

System.out.println ("Child foo() called");return this;

}}

class Covariant {

public static void main(String[] args) {Child c = new Child();

Child c2 = c.foo(); // c2 is ChildParent c3 = c.foo(); // c3 points to Child

}}

406. What is the result of the following statement?

int i = 1, float f = 2.0f;i += f; //ok, the cast done automatically by the compileri = i + f; //errorThe compound assignment operators automatically include cast operations in their behaviors.

406. What is externalization? Where is it useful??

Use the Externalizable interface when you need complete control over your Bean's serialization (for example,

when writing and reading a specific file format).

407. Use the Externalizable interface when you need complete control over your Bean's serialization (forexample, when writing and reading a specific file format).No. Earlier order is maintained.

408. What will be the output on executing the following code.public class MyClass {public static void main (String args[] ) {int abc[] = new int [5];System.out.println(abc);}}

A Error array not initializedB 5C nullD Print some junk characters

Ans. D

30

Page 31: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 31/225

It will print some junk characters to the output. Here it will not give any compile time or runtime error becausewe have declared and initialized the array properly. Event if we are not assigning a value to the array, it willalways initialized to its defaults.

409. What will be the output on executing the following code.public class MyClass {public static void main (String args[] ) {int abc[] = new int [5];System.out.println(abc[0]);

}}

A Error array not initializedB 5C 0D Print some junk characters

Ans. C.

Here it will not give any compile time or runtime error because we have declared and initialized the arrayproperly. Event if we are not assigning a value to the array, it will always initialized to its defaults. So the arraywill be initialized with values zero.

410. What is a marker interface ?

An interface that contains no methods. Eg: Serializable, Cloneable, SingleThreadModel etc. It is used to justmark java classes that support certain capability.

411. What are tag interfaces?Tag interface is an alternate name for marker interface.

412. What are the restrictions placed on static method ?We cannot override static methods. We cannot access any object variables inside static method. Also the thisreference also not available in static methods.

413. What is JVM?JVM stands for Java Virtual Machine. It is the run time for java programs. All are java programs are runninginside this JVM only. It converts java byte code to OS specific commands. In addition to governing theexecution of an application's byte codes, the virtual machine handles related tasks such as managing thesystem's memory, providing security against malicious code, and managing multiple threads of programexecution.

414. What is JIT?JIT stands for Just In Time compiler. It compiles java byte code to native code.

Design Patterns and Java Internals

415. What are ClassLoaders?A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class.Given the name of a class, a class loader should attempt to locate or generate data that constitutes a definitionfor the class. A typical strategy is to transform the name into a file name and then read a "class file" of thatname from a file system.Every Class object contains a reference to the ClassLoader that defined it.Class objects for array classes are not created by class loaders, but are created automatically as required bythe Java runtime. The class loader for an array class, as returned by Class.getClassLoader() is the same as theclass loader for its element type; if the element type is a primitive type, then the array class has no classloader.Applications implement subclasses of ClassLoader in order to extend the manner in which the Java virtualmachine dynamically loads classes.

416.What is Service Locator pattern?The Service Locator pattern locates J2EE (Java 2 Platform, Enterprise Edition) services for clients and thusabstracts the complexity of network operation and J2EE service lookup as EJB (Enterprise JavaBean) Home andJMS (Java Message Service) component factories. The Service Locator hides the lookup process'simplementation details and complexity from clients. To improve application performance, Service Locatorcaches service objects to eliminate unnecessary JNDI (Java Naming and Directory Interface) activity that

occurs in a lookup operation.

417. What is Session Facade pattern?Session facade is one design pattern that is often used while developing enterprise applications. It isimplemented as a higher level component (i.e.: Session EJB), and it contains all the iteractions between lowlevel components (i.e.: Entity EJB). It then provides a single interface for the functionality of an application or

31

Page 32: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 32/225

part of it, and it decouples lower level components simplifying the design. Think of a bank situation, where youhave someone that would like to transfer money from one account to another. In this type of scenario, theclient has to check that the user is authorized, get the status of the two accounts, check that there are enoughmoney on the first one, and then call the transfer. The entire transfer has to be done in a single transactionotherwise is something goes south, the situation has to be restored.As you can see, multiple server-side objects need to be accessed and possibly modified. Multiple fine-grainedinvocations of Entity (or even Session) Beans add the overhead of network calls, even multiple transaction. Inother words, the risk is to have a solution that has a high network overhead, high coupling, poor reusabilityand mantainability.The best solution is then to wrap all the calls inside a Session Bean, so the clients will have a single point toaccess (that is the session bean) that will take care of handling all the rest.

418. What is Data Access Object pattern? The Data Access Object (or DAO) pattern:separates a data resource's client interface from its data access mechanismsadapts a specific data resource's access API to a generic client interfaceThe DAO pattern allows data access mechanisms to change independently of the code that uses the data.The DAO implements the access mechanism required to work with the data source. The data source could be apersistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database,or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets. Thebusiness component that relies on the DAO uses the simpler interface exposed by the DAO for its clients. TheDAO completely hides the data source implementation details from its clients. Because the interface exposedby the DAO to clients does not change when the underlying data source implementation changes, this patternallows the DAO to adapt to different storage schemes without affecting its clients or business components.Essentially, the DAO acts as an adapter between the component and the data source.

419. How can we make a class Singleton

A) If the class is Serializable

class Singleton implements Serializable{

private static Singleton instance;

private Singleton() { }

public static synchronized Singleton getInstance(){if (instance == null)

instance = new Singleton();return instance;

}

 /**If the singleton implements Serializable, then this

* method must be supplied.*/protected Object readResolve() {

return instance;}

 /**This method avoids the object fro being cloned*/public Object clone() {

throws CloneNotSupportedException ; //return instance;

}}

B) If the class is NOT Serializable

class Singleton{private static Singleton instance;private Singleton() { }

public static synchronized Singleton getInstance(){

if (instance == null)instance = new Singleton();

return instance;}

 /**

32

Page 33: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 33/225

This method avoids the object from being cloned**/public Object clone() {

throws CloneNotSupportedException ; //return instance;

}

}

420. Can we make an EJB singleton?This is a debatable question, and for every answer we propose there can be contradictions. I propose 2solutions fo the same. Remember that EJB's are distributed componenets and can be deployed on differentJVM's in a Distributed environmenti) Follow the steps as given belowMake sure that your serviceLocator is deployed on only one JVM.In the serviceLocator create a HashTable/HashMap(You are the right judge to choose between these two)When ever a request comes for an EJB to a serviceLocator, it first checks in the HashTable if an entry alreadyexists in the table with key being the JNDI name of EJB. If key is present and value is not null, return theexisting reference, else lookup the EJB in JNDI as we do normally and add an entry into the Hashtable beforereturning it to the client. This makes sure that you maintain a singleton of EJB.ii) In distributed environment our components/Java Objects would be running on different JVM's. So thenormal singleton code we write for maintaining single instance works fine for single JVM, but when the classcould be loaded in multiple JVM's and Instantiated in multiple JVM's normal singleton code does not work. Thisis because the ClassLoaders being used in the different JVM's are different from each other and there is no

defined mechanism to check and compare what is loaded in another JVM. A solution could be(Not tested yet.Need your feedback on this) to write our own ClassLoader and pass this classLoader as argument, wheneverwe are creating a new Instance and make sure that only one instance is created for the proposed class.Thiscan be done easily.

421. How is static Synchronization different form non-static synchronization?When Synchronization is applied on a static Member or a static block, the lock is performed on the Class andnot on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not onclass. [Trail 2: There is a class called Class in Java whose object is associated with the object(s) of your class.All the static members declared in your class will have reference in this class(Class). As long as your classexists in memory this object of Class is also present. Thats how even if you create multiple objects of yourclass only one Class object is present and all your objects are linked to this Class object. Even though one of your object is GCed after some time, this object of Class is not GCed untill all the objects associated with it areGCed.This means that when ever you call a "static synchronized" block, JVM locks access to this Class object and not

any of your objects. Your client can till access the non-static members of your objects.

422. What are class members and Instance members?Any global members(Variables, methods etc.) which are static are called as Class level members and thosewhich are non-static are called as Instance level members.

423. Name few Garbage collection algorithms?Here they go:

Mark and SweepReference countingTracing collectorsCopying collectorsHeap compaction

Mark-compact collectors

424. Does Java pass by Value or reference?Its uses Reference while manipulating objects but pass by value when sending method arguments. Those whofeel why I added this simple question in this section while claiming to be maintaining only strong andinteresting questions, go ahead and answer following questions.

a)What is the out put of:

import java.util.*;

class TestCallByRefWithObject{

ArrayList list = new ArrayList(5);

public void remove(int index){list.remove(index);

}

public void add(Object obj){list.add(obj);

33

Page 34: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 34/225

}

public void display(){System.out.println(list);

}

public static void main(String[] args){

TestCallByRefWithObject test = new TestCallByRefWithObject();

test.add("1");test.add("2");test.add("3");test.add("4");test.add("5");

test.remove(4);test.display();

}}

b) And now what is the output of:

import java.util.*;

class TestCallByRefWithInt{

int i = 5;

public void decrement(int i){i--;

}

public void increment(int i){i++;

}

public void display(){

System.out.println("\nValue of i is : " +i);}

public static void main(String[] args){

TestCallByRefWithInt test = new TestCallByRefWithInt();

test.increment(test.i);

test.display();}

}

425. How is static Synchronization different form non-static synchronization?When Synchronization is applied on a static Member or a static block, the lock is performed on the Class and

not on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not onclass. [Trail 2: There is a class called Class in Java whose object is associated with the object(s) of your class.All the static members declared in your class will have reference in this class(Class). As long as your classexists in memory this object of Class is also present. Thats how even if you create multiple objects of yourclass only one Class object is present and all your objects are linked to this Class object. Even though one of your object is GCed after some time, this object of Class is not GCed untill all the objects associated with it areGCed.This means that when ever you call a "static synchronized" block, JVM locks access to this Class object and notany of your objects. Your client can till access the non-static members of your objects.

426. Why Thread is faster compare to process?A thread is never faster than a process. If you run a thread(say there's a process which has spawned only onethread) in one JVM and a process in another and that both of them require same resources then both of themwould take same time to execute. But, when a program/Application is thread based(remember here there willbe multiple threads running for a single process) then definetly a thread based appliation/program is fasterthan a process based application. This is because, when ever a process requires or waits for a resource CPUtakes it out of the critical section and allocates the mutex to another process.Before deallocating the ealier one, it stores the context(till what state did it execute that process) in registers.Now if this deallocated process has to come back and execute as it has got the resource for which it waswaiting, then it can't go into critical section directly. CPU asks that process to follow scheduling algorithm. Sothis process has to wait again for its turn. While in the case of thread based application, the application is still

34

Page 35: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 35/225

with CPU only that thread which requires some resource goes out, but its co threads(of sameprocess/apllication) are still in the critical section. Hence it directly

427. When and How is an object considered as Garbage by a GC?An object is considered garbage when it can no longer be reached from any pointer in the running program.The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objectsleft over are then considered garbage.

428. Can we force Garbage collection? java follows a philosophy of automatic garbage collection, you can suggest or encourage the JVM to performgarbage collection but you can not force it. Once a variable is no longer referenced by anything it is availablefor garbage collection. You can suggest garbage collection with System.gc(), but this does not guarantee whenit will happen. Local variables in methods go out of scope when the method exits. At this point the methods areeligible for garbage collection. Each time the method comes into scope the local variables are re-created.

429. What are generations in Garbage Collection terminolgy? What is its relevance?Garbage Collectors make assumptions about how our application runs. Most common assumption is that anobject is most likely to die shortly after it was created: called infant mortality. This assumes that an object thathas been around for a while, will likely stay around for a while. GC organizes objects into generations (young,tenured, and perm). This tells that if an object lives for more than certain period of time it is moved from onegeneration to another generations( say from young -> tenured -> permanent). Hence GC will be run morefrequently at the young generations and rarely at permanent generations. This reduces the overhead on GCand gives faster response time.

430. What is a Throughput Collector?The throughput collector is a generational collector similar to the default collector but with multiple threadsused to do the minor collection. The major collections are essentially the same as with the default collector. Bydefault on a host with N CPUs, the throughput collector uses N garbage collector threads in the collection. Thenumber of garbage collector threads can be controlled with a command line option.

431. When to Use the Throughput Collector?Use the throughput collector when you want to improve the performance of your application with largernumbers of processors. In the default collector garbage collection is done by one thread, and thereforegarbage collection adds to the serial execution time of the application. The throughput collector uses multiplethreads to execute a minor collection and so reduces the serial execution time of the application. A typicalsituation is one in which the application has a large number of threads allocating objects. In such anapplication it is often the case that a large young generation is needed

432. What is AggressiveHeap?The -XX:+AggressiveHeap option inspects the machine resources (size of memory and number of processors)and attempts to set various parameters to be optimal for long-running, memory allocation-intensive jobs. Itwas originally intended for machines with large amounts of memory and a large number of CPUs, but in theJ2SE platform, version 1.4.1 and later it has shown itself to be useful even on four processor machines. Withthis option the throughput collector (-XX:+UseParallelGC) is used along with adaptive sizing (-XX:+UseAdaptiveSizePolicy). The physical memory on the machines must be at least 256MB beforeAggressiveHeap can be used.

433. What is a Concurrent Low Pause Collector?The concurrent low pause collector is a generational collector similar to the default collector. The tenuredgeneration is collected concurrently with this collector. This collector attempts to reduce the pause timesneeded to collect the tenured generation. It uses a separate garbage collector thread to do parts of the major

collection concurrently with the applications threads. The concurrent collector is enabled with the command lineoption -XX:+UseConcMarkSweepGC. For each major collection the concurrent collector will pause all theapplication threads for a brief period at the beginning of the collection and toward the middle of the collection.The second pause tends to be the longer of the two pauses and multiple threads are used to do the collectionwork during that pause. The remainder of the collection is done with a garbage collector thread that runsconcurrently with the application. The minor collections are done in a manner similar to the default collector,and multiple threads can optionally be used to do the minor collection.

434. When to Use the Concurrent Low Pause Collector?Use the concurrent low pause collector if your application would benefit from shorter garbage collector pausesand can afford to share processor resources with the garbage collector when the application is running.Typically applications which have a relatively large set of long-lived data (a large tenured generation), and runon machines with two or more processors tend to benefit from the use of this collector. However, this collectorshould be considered for any application with a low pause time requirement. Optimal results have beenobserved for interactive applications with tenured generations of a modest size on a single processor.

435. What is Incremental Low Pause Collector?The incremental low pause collector is a generational collector similar to the default collector. The minorcollections are done with the same young generation collector as the default collector. Do not use either -XX:+UseParallelGC or -XX:+UseParNewGC with this collector. The major collections are done incrementally on the

35

Page 36: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 36/225

tenured generation. This collector (also known as the train collector) collects portions of the tenured generationat each minor collection. The goal of the incremental collector is to avoid very long major collection pauses bydoing portions of the major collection work at each minor collection. The incremental collector will sometimesfind that a non-incremental major collection (as is done in the default collector) is required in order to avoidrunning out of memory.

436. When to Use the Incremental Low Pause Collector?Use the incremental low pause collector when your application can afford to trade longer and more frequentyoung generation garbage collection pauses for shorter tenured generation pauses. A typical situation is one in

which a larger tenured generation is required (lots of long-lived objects), a smaller young generation willsuffice (most objects are short-lived and don't survive the young generation collection), and only a singleprocessor is available.

437. How do you enable the concurrent garbage collector on Sun's JVM?-Xconcgc options allows us to use concurrent garbage collector (1.2.2_07+)we can also use -XX:+UseConcMarkSweepGC which is available beginning with J2SE 1.4.1.

 

Java Questions

1. What is abstract

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

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

3. What is abstract method

A method that has no implementation.

4. What is Abstract Window Toolkit (AWT)

A collection of graphical user interface (GUI) components that were implemented using native-platformversions of the components. These components provide that subset of functionality which is common to allnative platforms. Largely supplanted by the Project Swing component set. See also Swing.

5. What is access control

The methods by which interactions with resources are limited to collections of users or programs for thepurpose of enforcing integrity, confidentiality, or availability constraints.

6. What is ACIDThe acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation, anddurability.

7. What is actual parameter list

The arguments specified in a particular method call. See also formal parameter list.

8. What is API

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

9. What is applet

A component that typically executes in a Web browser, but can execute in a variety of other applications ordevices that support the applet programming model.

10. What is ASCII

American Standard Code for Information Interchange. A standard assignment of 7-bit numeric codes tocharacters. See also Unicode.

11. What is atomic

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

12. What is authentication

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

13. What is autoboxing

Automatic conversion between reference and primitive types.

14. What is bean

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

15. What is binary operator

An operator that has two arguments.16. What is bitwise operator

An operator that manipulates the bits of one or more of its operands individually and in parallel. Examplesinclude the binary logical operators (&, |, ^), the binary shift operators (<< , >>, >>> ) and the unary one'scomplement operator (~).

36

Page 37: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 37/225

17. What is block

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

18. What is boolean

Refers to an expression or variable that can have only a true or false value. The Java programming languageprovides the boolean type and the literal values true and false.

19. What is break

A Java keyword used to resume program execution at the statement immediately following the currentstatement. If followed by a label, the program resumes execution at the labeled statement.

20. What is bytecode

Machine-independent code generated by the Java compiler and executed by the Java interpreter.

21. What is case

A Java keyword that defines a group of statements to begin executing if a value specified matches the valuedefined by a preceding switch keyword.

22. What is casting

Explicit conversion from one data type to another.

23. What is catch

A Java keyword used to declare a block of statements to be executed in the event that a Java exception, or runtime error, occurs in a preceding try block.

24. What is "abstract schema"

The part of an entity bean's deployment descriptor that defines the bean's persistent fields and relationships.

25. What is "abstract schema name"

A logical name that is referenced in EJB QL queries.

26. What is "access control"

The methods by which interactions with resources are limited to collections of users or programs for thepurpose of enforcing integrity, confidentiality, or availability constraints.

27. What is "ACID"

The acronym for the four properties guaranteed by transactions: atomicity, consistency, isolation, anddurability.

28. What is "activation"

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

29. What is "anonymous access"

Accessing a resource without authentication.

30. What is class

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

31. What is class method

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

32. What is class variable

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

33. What is classpath

An environmental variable which tells the Java virtual machine1 and Java technology-based applications whereto find the class libraries, including user-defined class libraries.

34. What is client

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

35. What is codebase

Works together with the code attribute in the <APPLET> tag to give a complete specification of where to findthe main applet class file: code specifies the name of the file, and codebase specifies the URL of the directorycontaining the file.

36. What is comment

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

37. What is commit

The point in a transaction when all updates to any resources involved in the transaction are made permanent.38. What is compilation unit

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

39. What is compiler

37

Page 38: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 38/225

A program to translate source code into code to be executed by a computer. The Java compiler translatessource code written in the Java programming language into bytecode for the Java virtual machine1. See alsointerpreter.

40. What is compositing

The process of superimposing one image on another to create a single image.

41. What is constructor

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

42. What is constA reserved Java keyword not used by current versions of the Java programming language.

43. What is continue

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

44. What is conversational state

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

45. What is CORBA

Common Object Request Broker Architecture. A language independent, distributed object model specified bythe Object Management Group (OMG).

46. What is core classA public class (or interface) that is a standard member of the Java Platform. The intent is that the core classesfor the Java platform, at minimum, are available on all operating systems where the Java platform runs. Aprogram written entirely in the Java programming language relies only on core classes, meaning it can runanywhere. .

47. What is core packages

The required set of APIs in a Java platform edition which must be supported in any and all compatibleimplementations.

48. What is credentials

The information describing the security attributes of a principal. Credentials can be acquired only throughauthentication or delegation.

49. What is critical section

A segment of code in which a thread uses resources (such as certain instance variables) that can be used by

other threads, but that must not be used by them at the same time.50. What is declaration

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

51. What is default

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

52. What is definition

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

53. What is delegation

An act whereby one principal authorizes another principal to use its identity or privileges with somerestrictions.

54. What is deprecation

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

55. What is derived from

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

56. What is distributed

Running in more than one address space.

57. What is distributed application

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

58. What is do

A Java keyword used to declare a loop that will iterate a block of statements. The loop's exit condition can be

specified with the while keyword.59. What is DOM

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

60. What is double

38

Page 39: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 39/225

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

61. What is double precision

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

62. What is DTD

Document Type Definition. A description of the structure and properties of a class of XML files.

63. What is else

A Java keyword used to execute a block of statements in the case that the test condition with the if keywordevaluates to false.

64. What is EmbeddedJava Technology

The availability of Java 2 Platform, Micro Edition technology under a restrictive license agreement that allows alicensee to leverage certain Java technologies to create and deploy a closed-box application that exposes noAPIs.

65. What is encapsulation

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

66. What is enum

A Java keyword used to declare an enumerated type.

67. What is enumerated typeA type whose legal values consist of a fixed set of constants.

68. What is exception

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

69. What is exception handler

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

70. What is executable content

An application that runs from within an HTML file. See also applet.

71. What is extends

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

72. What is field

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

73. What is final

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

74. What is finally

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

75. What is float

A Java keyword used to define a floating point number variable.76. What is for

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

77. What is FTP

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

78. What is formal parameter list

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

79. What is garbage collection

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

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

81. What is goto

39

Page 40: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 40/225

This is a reserved Java keyword. However, it is not used by current versions of the Java programminglanguage.

82. What is group

A collection of principals within a given security policy domain.

83. What is GUI

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

84. What is hexadecimal

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

85. What is hierarchy

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

86. What is HTML

HyperText Markup Language. This is a file format, based on SGML, for hypertext documents on the Internet. Itis very simple and allows for the embedding of images, sounds, video streams, form fields and simple textformatting. References to other objects are embedded using URLs.

87. What is HTTP

HyperText Transfer Protocol. The Internet protocol, based on TCP/IP, used to fetch hypertext objects from

remote hosts. See also TCP/IP.88. What is HTTPS

HyperText Transfer Protocol layered over the SSL protocol.

89. What is IDL

Interface Definition Language. APIs written in the Java programming language that provide standards-basedinteroperability and connectivity with CORBA (Common Object Request Broker Architecture).

90. What is identifier

The name of an item in a program written in the Java programming language.

91. What is IIOP

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

92. What is if 

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

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

94. What is implements

A Java keyword included in the class declaration to specify any interfaces that are implemented by the currentclass.

95. What is import

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

96. What is inheritance

The concept of classes automatically containing the variables and methods defined in their supertypes. Seealso superclass, subclass.

97. What is instance

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

98. What is instance method

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

99. What is instance variable

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

100. What is instanceof 

A two-argument Java keyword that tests whether the runtime type of its first argument is assignment

compatible with its second argument.101. What is int

A Java keyword used to define a variable of type integer.

102. What is interface

40

Page 41: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 41/225

A Java keyword used to define a collection of method definitions and constant values. It can later beimplemented by classes that define this interface with the "implements" keyword.

103. What is Internet

An enormous network consisting of literally millions of hosts from many organizations and countries around theworld. It is physically put together from many smaller networks and data travels by a common set of protocols.

104. What is IP

Internet Protocol. The basic protocol of the Internet. It enables the unreliable delivery of individual packetsfrom one host to another. It makes no guarantees about whether or not the packet will be delivered, how long

it will take, or if multiple packets will arrive in the order they were sent. Protocols built on top of this add thenotions of connection and reliability. See also TCP/IP.

105. What is interpreter

A module that alternately decodes and executes every statement in some body of code. The Java interpreterdecodes and executes bytecode for the Java virtual machine1. See also compiler, runtime system.

106. What is JAIN

See: Java APIs for Integrated Networks (JAIN)

107. What is JAR

JAR (Java Archive) is a platform-independent file format that aggregates many files into one. Multiple appletswritten in the Java programming language, and their requisite components (.class files, images, sounds andother resource files) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTPtransaction. It also supports file compression and digital signatures.

108. What is Java

A set of technologies for creating and safely running software programs in both stand-alone and networkedenvironments.

109. What is Java 2 Platform

The second generation of the Java platform. (The first generation was the JDK.) Also see "Java Platform" and"Java Platform Editions".

110. What is Java 2 Platform, Enterprise Edition (J2EE platform)

See Java 2 Platform, Enterprise Edition, under Java Platform Editions.

111. What is Java 2 Platform, Micro Edition (J2ME platform)

See Java 2 Platform, Micro Edition, under Java Platform Editions.

112. What is Java 2 Platform, Standard Edition (J2SE platform)

See Java 2 Platform, Standard Edition, under Java Platform Editions.

113. What is Java 2 SDK, Standard Edition

The Software Development Kit (SDK) is development environment for building applications, applets, andcomponents using the Java programming language. This SDK provides a reference implementation of the J2SEplatform.

114. What is Java APIs for Integrated Networks (JAIN)

enables the rapid development of Next Generation telecom products and services on the Java platform.

115. What is Java Card API

An ISO 7816-4 compliant application environment focused on smart cards.

116. What is Java Compatibility Kit (JCK)

A test suite, a set of tools, and other requirements used to certify a Java platform implementation conformantboth to the applicable Java platform specifications and to Java Software reference implementations.

117.What is Java Database Connectivity (JDBC)

An industry standard for database-independent connectivity between the Java platform and a wide range of 

databases. The JDBC provides a call-level API for SQL-based database access.118. What is Java Development Kit (JDK)

A software development environment for writing applets and applications in the Java programming language.Technically, the JDK is the correct name for all versions of the Java platform from 1.0 to 1.1.x.

119. What is Java Foundation Classes (JFC)

An extension that adds graphical user interface class libraries to the Abstract Windowing Toolkit (AWT).

120. What is Java IDL

Java Interface Definition Language

121. What is Java Interface Definition Language (IDL)

A set of Java APIs that provide CORBA (Common Object Request Broker Architecture) interoperability andconnectivity capabilities for the J2EE platform. These capabilities enable J2EE applications to invoke operationson remote network services using the OMG IDL and IIOP.

122. What is Java Media APIs

A set of APIs that support the integration of audio and video clips, 2D fonts, graphics, and images as well as3D models and telephony.

123. What is Java Media Framework

The core framework supports clocks for synchronizing between different media (e.g., audio and video output).The standard extension framework allows users to do full audio and video streaming.

41

Page 42: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 42/225

124. What is Java Naming and Directory Interface (JNDI)

A set of APIs that assists with the interfacing to multiple naming and directory services.

125. What is Java Native Interface

A standard programming interface for writing Java native methods and embedding the JVM into nativeapplications. The primary goal is binary compatibility of native method libraries across all JVM implementationson a given platform.

126. What is Java Platform

Consists of class libraries, a Java virtual machine (JVM) and class loader (which comprise the runtime

environment) and a compiler, debugger and other tools (which comprise the development kit). In addition, theruntime platform is subject to a set of compatibility requirements to ensure consistent and compatibleimplementations. Implementations that meet the compatibility requirements may qualify for Sun's targetedcompatibility brands. Java 2 is the current generation of the Java Platform.

127. What is Java Platform Editions

A Java platform "edition" is a definitive and agreed-upon version of the Java platform that provides thefunctionality needed over a broad market segment. An edition is comprised of two kinds of API sets: (i) "corepackages," which are essential to all implementations of a given platform edition, and (ii) "optional packages,"which are available for a given platform edition and which may be supported in a compatible implementation.

128. There are 3 distinct editions of the Java Platform:

* Java 2 Platform, Enterprise Edition:The edition of the Java platform that is targeted at enterprises to enable development, deployment, andmanagement of multi-tier server-centric applications.* Java 2 Platform, Micro Edition:The edition of the Java platform that is targeted at small, standalone or connectable consumer and embeddeddevices to enable development, deployment, and management of applications that can scale from smart cardsthrough mobile devices and set-top boxes to conventional computing devices.* Java 2 Platform, Standard Edition:The edition of the Java platform that enables development, deployment, and management of cross-platform,general-purpose applications.

129. What is Java Remote Method Invocation (RMI)

A distributed object model for Java program to Java program, in which the methods of remote objects writtenin the Java programming language can be invoked from other Java virtual machines1, possibly on differenthosts.

130. What is Java Runtime Environment (JRE)

A subset of the Java Development Kit (JDK) for end-users and developers who want to redistribute the runtimeenvironment alone. The Java runtime environment consists of the Java virtual machine1, the Java core classes,and supporting files.

131. What is Java virtual machine1

A software "execution engine" that safely and compatibly executes the byte codes in Java class files on amicroprocessor (whether in a computer or in another electronic device).

132. What is JavaBeans

A portable, platform-independent reusable component model. A component that conforms to this model iscalled a bean.

133. What is JavaCheck

A tool for checking compliance of applications and applets to a specification.

134. What is JavaSafe

A tool for tracking and managing source file changes, written in Java.

135. What is JavaScript

A Web scripting language that is used in both browsers and Web servers. Like all scripting languages, it is usedprimarily to tie other components together or to accept user input.

136. What is JavaSpaces

A technology that provides distributed persistence and data exchange mechanisms for code in Java.

137. What is JDBC

Java Database Connectivity.

138. What is JDK

Java Development Kit. A software development environment for writing applets and application in Java .

139. What is JFC

Java Foundation Classes.

140. What is Jini Technology

A set of Java APIs that may be incorporated an optional package for any Java 2 Platform Edition. The Jini APIs

enable transparent networking of devices and services and eliminates the need for system or networkadministration intervention by a user. The Jini technology is currently an optional package available on all Javaplatform editions.

141. What is JNDI

Java Naming and Directory Interface.

142. What is JNI

42

Page 43: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 43/225

Java Native Interface.

143. What is JRE

Java Runtime Environment

144. What is Just-in-time (JIT) Compiler

A compiler that converts all of the bytecode into native machine code just as a Java program is run. Thisresults in run-time speed improvements over code that is interpreted by a Java virtual machine.

145. What is JVM

Java Virtual Machine (JVM).146. What is keyword

Java sets aside words as keywords - these words are reserved by the language itself and therefore are notavailable as names for variables or methods.

147. What is lexical

Pertaining to how the characters in source code are translated into tokens that the compiler can understand.

148. What is linker

A module that builds an executable, complete program from component machine code modules. The Javalinker creates a runnable program from compiled classes. See also compiler, interpreter, runtime system.

149. What is literal

The basic representation of any integer, floating point, or character value. For example, 3.0 is a double-precision floating point literal, and "a" is a character literal.

150. What is local variable

A data item known within a block, but inaccessible to code outside the block. For example, any variable definedwithin a method is a local variable and can't be used outside the method.

151. What is long

A Java keyword used to define a variable of type long.

152. What is member

A field or method of a class. Unless specified otherwise, a member is not static.

153. What is method

A function defined in a class. See also instance method, class method. Unless specified otherwise, a method isnot static.

154. What is multithreaded

Describes a program that is designed to have parts of its code execute concurrently. See also thread.

155. What is native

A Java keyword that is used in method declarations to specify that the method is not implemented in the sameJava source file, but rather in another language.

156. What is new

A Java keyword used to create an instance of a class.

157. What is null

The null type has one value, the null reference, represented by the literal null, which is formed from ASCIIcharacters. A null literal is always of the null type.

158. What is object

The principal building blocks of object-oriented programs. Each object is a programming unit consisting of data(instance variables) and functionality (instance methods). See also class.

159. What is object-oriented design

A software design method that models the characteristics of abstract or real objects using classes and objects.

160. What is octal What is object-oriented design

The numbering system using 8 as its base, using the numerals 0-7 as its digits. In programs written in theJava programming language, octal numbers must be preceded with 0. See also hexadecimal.

161. What is optional packages

The set or sets of APIs in a Java platform edition which are available with and may be supported in acompatible implementation. Over time, optional packages may become required in an edition as themarketplace requires them.

162. What is ORB

Object Request Broker. A library than enables CORBA objects to locate and communicate with one another.

163. What is OS principal

A principal native to the operating system on which the Java platform is executing.

164. What is OTS

Object Transaction Service. A definition of the interfaces that permit CORBA objects to participate intransactions.

165. What is overloading

Using one identifier to refer to multiple items in the same scope. In the Java programming language, you canoverload methods but not variables or operators.

166. What is overriding

43

Page 44: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 44/225

Providing a different implementation of a method in a subclass of the class that originally defined the method.

167. What is package

A group of types. Packages are declared with the package keyword.

168. What is peer

In networking, any functional unit in the same layer as another entity.

169. What is persistence

The protocol for transferring the state of a bean between its instance variables and an underlying database.

170. What is pixelThe picture element on a display area, such as a monitor screen or printed page. Each pixel is individuallyaccessible.

171. What is POA

Portable Object Adapter. A CORBA standard for building server-side applications that are portable acrossheterogeneous ORBs.

172. What is primary key

An object that uniquely identifies an entity bean within a home.

173. What is primitive type

A variable data type in which the variable's value is of the appropriate size and format for its type: a number, acharacter, or a boolean value.

174. What is principal

The identity assigned to an entity as a result of authentication

175. What is privateA Java keyword used in a method or variable declaration. It signifies that the method or variable can only beaccessed by other elements of its class.

176. What is privilege

A security attribute that does not have the property of uniqueness and which may be shared by manyprincipals. An example of a privilege is a group.

177. What is process

A virtual address space containing one or more threads.

178. What is property

Characteristics of an object that users can set, such as the color of a window.

179. What is profiles

A profile is a collection of Java APIs that complements one or more Java 2 Platform Editions by adding domain-

specific capabilities. Profiles may also include other defined profiles. A profile implementation requires a Java 2Platform Edition to create a complete development and deployment environment in a targeted vertical market.Each profile is subject to an associated set of compatibility requirements. Profiles may be usable on one ormore editions.

180. Some examples of profiles within the Java 2 Platform, Micro Edition are:

* Personal Profile- for non-PC products that need to display Web-compatible Java-based content* Java Card - for secure smart cards and other severely memory-constrained devices.

181. What is protected

A Java keyword used in a method or variable declaration. It signifies that the method or variable can only beaccessed by elements residing in its class, subclasses, or classes in the same package.

182. What is public

A Java keyword used in a method or variable declaration. It signifies that the method or variable can beaccessed by elements residing in other classes.

183. What is rasterA two-dimensional rectangular grid of pixels.

184. What is realm

See security policy domain. Also, a string, passed as part of an HTTP request during basic authentication, thatdefines a protection space. The protected resources on a server can be partitioned into a set of protectionspaces, each with its own authentication scheme and/or authorization database.

185. What is realm

A variable data type in which the variable's value is an address.

186. What is return

A Java keyword used to finish the execution of a method. It can be followed by a value required by the methoddefinition.

187. What is RMI

See Java Remote Method Invocation.188. What is rollback

The point in a transaction when all updates to any databases involved in the transaction are reversed.

189. What is root

44

Page 45: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 45/225

In a hierarchy of items, the one item from which all other items are descended. The root item has nothingabove it in the hierarchy. See also hierarchy, class, package.

190. What is RPC

Remote Procedure Call. Executing what looks like a normal procedure call (or method invocation) by sendingnetwork packets to some remote host.

191. What is runtime system

The software environment in which programs compiled for the Java virtual machine1 can run. The runtimesystem includes all the code necessary to load programs written in the Java programming language,

dynamically link native methods, manage memory, handle exceptions, and an implementation of the Javavirtual machine, which may be a Java interpreter.

192. What is SAX

Simple API for XML. An event-driven, serial-access mechanism for accessing XML documents.

193. What is sandbox

Comprises a number of cooperating system components, ranging from security managers that execute as partof the application, to security measures designed into the Java virtual machine1 and the language itself. Thesandbox ensures that an untrusted, and possibly malicious, application cannot gain access to systemresources.

194. What is scope

A characteristic of an identifier that determines where the identifier can be used. Most identifiers in the Javaprogramming environment have either class or local scope. Instance and class variables and methods haveclass scope; they can be used outside the class and its subclasses only by prefixing them with an instance of the class or (for class variables and methods) with the class name. All other variables are declared withinmethods and have local scope; they can be used only within the enclosing block.195. What is Secure Socket Layer (SSL)

A protocol that allows communication between a Web browser and a server to be encrypted for privacy.

196. What is security attributes

A set of properties associated with a principal. Security attributes can be associated with a principal by anauthentication protocol.

197. What is security context

An object that encapsulates the shared state information regarding security between two entities.

198. What is security policy domain

A scope over which security policies are defined and enforced by a security administrator. A security policydomain has the following characteristics:It has a collection of users (or principals).It uses a well defined authentication protocol(s) for authenticating users (or principals).It may have groups to simplify setting of security policies.

199. What is security technology domain

A scope over which the same security mechanism is used to enforce a security policy. Multiple security policydomains can exist within a single technology domain.

200. What is serialization

The encoding of objects, and the objects reachable from them, into a stream of bytes and the complementaryreconstruction of the object graph from the stream.

201. What is short

A Java keyword used to define a variable of type short.

202. What is single precision

In the Java language specification, describes a floating point number with 32 bits of data. See also doubleprecision.

203. What is SGMLStandardized Generalized Markup Language. An ISO/ANSI/ECMA standard that specifies a way to annotate textdocuments with information about types of sections of a document.

204. What is SOAP

The Simple Object Access Protocol (SOAP) uses a combination of XML-based data structuring and the HyperText Transfer Protocol (HTTP) to define a standardized method for invoking methods in objects distributed indiverse operating environments across the Internet.

205. What is SQL

Structured Query Language. The standardized relational database language for defining database objects andmanipulating data.

206. What is static

A Java keyword used to define a variable as a class variable. Classes maintain one copy of class variablesregardless of how many instances exist of that class. static can also be used to define a method as a classmethod. Class methods are invoked by the class instead of a specific instance, and can only operate on classvariables.

207. What is static field

Another name for class variable.

208. What is static method

45

Page 46: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 46/225

Another name for class method.

209. What is stream

A stream is simply a byte-stream of data that is sent from a sender to a receiver. There are two basiccategories, so the java.io package includes two abstract classes (InputStream and OutputStream).

210. What is subarray

An array that is inside another array.

211. What is subclass

A class that is derived from a particular class, perhaps with one or more classes in between. See alsosuperclass, supertype.212. What is subtype

If type X extends or implements type Y, then X is a subtype of Y. See also supertype.

213. What is superclass

A class from which a particular class is derived, perhaps with one or more classes in between. See alsosubclass, subtype.

214. What is super

A Java keyword used to access members of a class inherited by the class in which it appears.

215. What is supertype

The supertypes of a type are all the interfaces and classes that are extended or implemented by that type. Seealso subtype, superclass.

216. What is switch

A Java keyword used to evaluate a variable that can later be matched with a value specified by the casekeyword in order to execute a group of statements.

217. What is Swing

A collection of graphical user interface (GUI) components that runs uniformly on any native platform whichsupports the Java virtual machine*. Because they are written entirely in the Java programming language,these components may provide functionality above and beyond that provided by native-platform equivalents.(Contrast with AWT.)

218. What is synchronized

A keyword in the Java programming language that, when applied to a method or code block, guarantees thatat most one thread at a time executes that code.

219. What is TCP/IP

Transmission Control Protocol based on IP. This is an Internet protocol that provides for the reliable delivery of streams of data from one host to another. See also IP.

220. What is Technology Compatibility Kit (TCK)A test suite, a set of tools, and other requirements used to certify an implementation of a particular Suntechnology conformant both to the applicable specifications and to Sun or Sun-designated referenceimplementations.

221. What is thin client

A system that runs a very light operating system with no local system administration and executes applicationsdelivered over the network.

222. What is this

A Java keyword that can be used to represent an instance of the class in which it appears. this can be used toaccess class variables and methods.

223. What is thread

The basic unit of program execution. A process can have several threads running concurrently, eachperforming a different job, such as waiting for events or performing a time-consuming job that the program

doesn't need to complete before going on. When a thread has finished its job, the thread is suspended ordestroyed. See also process.

224. What is throw

A Java keyword that allows the user to throw an exception or any class that implements the "throwable"interface.

225. What is throws

A Java keyword used in method declarations that specify which exceptions are not handled within the methodbut rather passed to the next higher level of the program.

226. What is transaction

An atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which either complete or roll back. Transactions enable multiple users to access the same data concurrently.

227. What is transaction isolation level

The degree to which the intermediate state of the data being modified by a transaction is visible to other

concurrent transactions and data being modified by other transactions is visible to it.228. What is transaction manager

Provides the services and management functions required to support transaction demarcation, transactionalresource management, synchronization, and transaction context propagation.

229. What is transient

46

Page 47: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 47/225

A keyword in the Java programming language that indicates that a field is not part of the serialized form of anobject. When an object is serialized, the values of its transient fields are not included in the serialrepresentation, while the values of its non-transient fields are included.

230. What is try

A Java keyword that defines a block of statements that may throw a Java language exception. If an exceptionis thrown, an optional catch block can handle specific exceptions thrown within the try block. Also, an optionalfinally block will be executed regardless of whether an exception is thrown or not.

231. What is type

A class or interface.232. What is Unicode

A 16-bit character set defined by ISO 10646. See also ASCII. All source code in the Java programmingenvironment is written in Unicode.

234. What is URI

Uniform Resource Identifier. A compact string of characters for identifying an abstract or physical resource. AURI is either a URL or a URN. URLs and URNs are concrete entities that actually exist; A URI is an abstractsuperclass.

235. What is URL

Uniform Resource Locator. A standard for writing a text reference to an arbitrary piece of data in the WWW. AURL looks like "protocol://host/localinfo" where protocol specifies a protocol to use to fetch the object (likeHTTP or FTP), host specifies the Internet name of the host on which to find it, and localinfo is a string (often afile name) passed to the protocol handler on the remote host.

236. What is URNUniform Resource Name. A unique identifier that identifies an entity, but doesn't tell where it is located. Asystem can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Weblocation to change, while still allowing the entity to be found.

237. What is variable

An item of data named by an identifier. Each variable has a type, such as int or Object, and a scope. See alsoclass variable, instance variable, local variable.

238. What is virtual machine

An abstract specification for a computing device that can be implemented in different ways, in software orhardware. You compile to the instruction set of a virtual machine much like you'd compile to the instruction setof a microprocessor. The Java virtual machine consists of a bytecode instruction set, a set of registers, a stack,a garbage-collected heap, and an area for storing methods.

239. What is void

A Java keyword used in method declarations to specify that the method does not return any value. void canalso be used as a nonfunctional statement.

240. What is volatile

A Java keyword used in variable declarations that specifies that the variable is modified asynchronously byconcurrently running threads.

241. What is Web server

Software that provides services to access the Internet, an intranet, or an extranet. A Web server hosts Websites, provides support for HTTP and other protocols, and executes server-side programs (such as CGI scriptsor servlets) that perform certain functions.

242. What is while

A Java keyword used to declare a loop that iterates a block of statements. The loop's exit condition is specifiedas part of the while statement.

243. What is world readable files

Files on a file system that can be viewed (read) by any user. For example: files residing on Web servers canonly be viewed by Internet users if their permissions have been set to world readable.

244. What is wrapper

An object that encapsulates and delegates to another object to alter its interface or behavior in some way.

245. What is XML

Extensible Markup Language. A markup language that allows you to define the tags (markup) needed toidentify the data and text in XML documents.

JSP

1. What is a JSP and what is it used for?

Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EEplatform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jspfiles. A JSP compiler is used in the background to generate a Servlet from the JSP page.

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 thengroup your tags into collections called tag libraries that can be used in any number of JSP files. To use custom

47

Page 48: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 48/225

JSP tags, you need to define three separate components:1. the tag handler class that defines the tag\'s behavior2. the tag library descriptor file that maps the XML element names to the tag implementations3. the JSP file that uses the tag library

When the first two components are done, you can use the tag by using taglib directive:

Then you are ready to use the tags you defined. Let's say the tag prefix is test:MyJSPTag or JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes.

You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class.

Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple andaccessible 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. Customtags 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 servletand 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 two kinds of comments in JSP and what's the difference between them.

<%-- JSP Comment --%>

<!-- HTML Comment -->

4. What is JSP technology?

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

5. What is JSP page?

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

6. What are the implicit objects?

Implicit objects are objects that are created by the web container and contain information related to aparticular request, page, or application. They are:--request--response--pageContext--session--application--out--config--page--exception

7. How many JSP scripting elements and what are they?

There are three scripting language elements:--declarations--scriptlets--expressions

8. Why are JSP pages the preferred API for creating a web-based client program?

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pagesenable cleaner and more module application design because they provide a way to separate applicationsprogramming from web page design. This means personnel involved in web page design do not need tounderstand Java programming language syntax to do their jobs.

9. Is JSP technology extensible?

YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulatedin tag libraries.

10. Can we use the constructor, instead of init(), to initialize servlet?

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

48

Page 49: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 49/225

11. How can a servlet refresh automatically if some new data has entered the database?

You can use a client-side Refresh or Server Push.

12. The code in a finally clause will never fail to execute, right?

Using System.exit(1); in try block will not allow finally code to execute.

13. How many messaging models do JMS provide for and what are they?JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

14. What information is needed to create a TCP Socket?

The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

15. What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded adriver, it is available for making a connection with a DBMS.

16. How to Retrieve Warnings?

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do notstop the execution of an application, as exceptions do; they simply alert the user that something did nothappen as planned. A warning can be reported on a Connection object, a Statement object (includingPreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has agetWarnings method, which you must invoke in order to see the first warning reported on the calling object

SQLWarning warning = stmt.getWarnings();if (warning != null){

while (warning != null){

System.out.println(\"Message: \" + warning.getMessage());System.out.println(\"SQLState: \" + warning.getSQLState());System.out.print(\"Vendor error code: \");System.out.println(warning.getErrorCode());warning = warning.getNextWarning();

}}

17. How many JSP scripting elements are there and what are they?

There are three scripting language elements: declarations, scriptlets, expressions.

18. In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?

Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should takecare of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at thepage level.

19. What are stored procedures? How is it useful?

A stored procedure is a set of statements/commands which reside in the database. The stored procedure ispre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query isrun. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor.Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems stilldo it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved inSQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when youwant to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connectionmay be significant in these cases.

20. How do I include static files within a JSP page?

Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the fileattribute. Although you can also include static resources using the action, this is not advisable as the inclusionis then performed for each and every request.

21. Why does JComponent have add() and remove() methods but Component does not?because JComponent is a subclass of Container, and can contain other components and jcomponents. How canI implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement theSingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > withinyour JSP page.

49

Page 50: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 50/225

22. How can I enable session tracking for JSP pages if the browser has disabled cookies?

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking usingURL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair.However, for this to be effective, you need to append the session ID for each and every link that is part of yourservlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods:response.encodeURL() associates a session ID with a given URL, and if you are using redirection,response.encodeRedirectURL() can be used by giving the redirected URL as input.Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser;

if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider thefollowing example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other.Basically, we create a new session within hello1.jsp and place an object within this session. The user can thentraverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract theobject that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL()within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automaticallyappended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookiesenabled. Then disable cookie support, restart the brower, and try again. Each time you should see themaintenance of the session across pages.Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to supportURL rewriting.hello1.jsphello2.jsphello2.jsp<%

Integer i= (Integer )session.getValue("num");out.println("Num value in session is "+i.intValue());

23. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSPpage from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pagesto prevent them from being cached at the browser. You need both the statements to take care of some of theolder browser versions.

24. How do you restrict page errors display in the JSP page?

You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage="error.jsp")inyour jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it willautomatically call the error page.

25. What JSP lifecycle methods can I override?You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and

 jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like databaseconnections, network connections, and so forth for the JSP page. It is good programming practice to free anyallocated resources within jspDestroy().The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and aretypically declared as JSP declarations:

26. How do I perform browser redirection from a JSP page?

You can use the response implicit object to redirect the browser to a different resource, as:response.sendRedirect("http://www.exforsys.com/path/error.html");You can also physically alter the Location HTTP header attribute, as shown below:You can also use the:Also note that you can only use this before any output has been sent to the client. I beleve this is the case with

the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using >

27. How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to have uncaught runtime exceptions automaticallyforwarded to an error processing page.For example:redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during requestprocessing. Within error.jsp, if you indicate that it is an error-processing page, via the directive:

the Throwable object describing the exception may be accessed within the error page via the exception implicitobject.Note: You must always use a relative URL as the value for the errorPage attribute.

28. How do I use comments within a JSP page?

You can use "JSP-style" comments to selectively block out code while debugging or simply to comment yourscriptlets. JSP comments are not visible at the client.For example:--%>You can also use HTML-style comments anywhere within your JSP page. These comments are visible at theclient. For example:Of course, you can also use comments supported by your JSP scripting language within your scriptlets.

50

Page 51: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 51/225

29. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in theHttpSession from inside an EJB?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as "passed-by-value", that means that it's read-only in the EJB.If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the ServletContainer.The "pass-byreference" can be used between EJBs Remote Interfaces, as they are remotereferences.While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "badpractice" in terms of object oriented design. This is because you are creating an unnecessary coupling between

back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb'sapi. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create aclass that acts as a value object (or structure) that holds all the data you need to pass back and forth betweenfront-end/back-end.Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction willbe flexible enough to support it.

30. How can I implement a thread-safe JSP page?

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is doneby adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

31. How can I declare methods within my JSP page?

You can declare methods for use within your JSP page as declarations. The methods can then be invokedwithin any other methods you declare, or within JSP scriptlets and expressions.Do note that you do not have direct access to any of the JSP implicit objects like request, response, sessionand so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables asparameters to the methods you declare.For example:Another Example:file1.jsp:file2.jsp<%test(out);% >

32. Can I stop JSP execution while in the midst of processing a request?

Yes. Preemptive termination of request processing on an error condition is a good way to maximize thethroughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use thereturn statement when you want to terminate further processing.

33. Can a JSP page process HTML FORM data?

Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet()or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicitobject within a scriptlet or expression as.

34. Is there a way to reference the "this" variable within a JSP page?

Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to theservlet generated by the JSP page.

35. How do you pass control from one JSP page to another?

Use the following ways to pass control of a request from one servlet to another or one jsp to another.The RequestDispatcher object ‘s forward method to pass the control.The response.sendRedirect method

36. Is there a way I can set the inactivity lease period on a per-session basis?

Typically, a default inactivity lease period for all sessions is set within your JSPengine admin screen orassociated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage theinactivity lease period on a per-session basis.This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has beencreated.

37. How does a servlet communicate with a JSP page?

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted bya browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp,by means of a request dispatcher for downstream processing.

public void doPost (HttpServletRequest request, HttpServletResponse response){

try {govi.FormBean f = new govi.FormBean();String id = request.getParameter("id");f.setName(request.getParameter("name"));f.setAddr(request.getParameter("addr"));f.setAge(request.getParameter("age"));

51

Page 52: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 52/225

 //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . .

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

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default requestscope via the useBean action.

 jsp:useBean id="fBean" class="govi.FormBean" scope="request"/ jsp:getPropertyname="fBean" property="name" / jsp:getProperty name="fBean" property="addr"

 / jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean"property="personalizationInfo" /

38. How do I include static files within a JSP page?Static resources should always be included using the JSP include directive. This way, the inclusion is performed

 just once during the translation phase.The following example shows the syntax:< % @ include file="copyright.html" % >Do note that you should always supply a relative URL for the file attribute. Although you can also include staticresources using the action, this is not advisable as the inclusion is then performed for each and every request.How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? Oneshould be very careful when having JSP pages extend custom servlet classes as opposed to the default onegenerated by the JSP engine. In doing so, you may lose out on any advanced optimization that may beprovided by the JSPengine.In any case, your new superclass has to fulfill the contract with the JSP engine by: Implementing theHttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all themethods in the Servlet interface are declared final.Additionally, your servlet superclass also needs to do the following:

The service() method has to invoke the _jspService() methodThe init() method has to invoke the jspInit() methodThe destroy() method has to invoke jspDestroy()If any of the above conditions are not satisfied, the JSP engine may throw a translation error. Once thesuperclass has been developed, you can have your JSP extend it as follows:

39. Can you make use of a ServletOutputStream object from within a JSP page?

No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit objectout) for replying to clients.A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(),although from an implementational perspective, it is not.A page author can always disable the default buffering for any page using a page directive as:

40. Can a JSP page instantiate a serialized bean?

No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serializedbean.For example:

A couple of important points to note. Although you would have to name your serialized file "filename.ser", youonly indicate "filename" as the value for the beanName attribute. Also, you will have to place your serializedfile within the WEB-INFjspbeans directory for it to be located by the JSP engine.

41. What is JSP?

Let's consider the answer to that from two different perspectives: that of an HTML designer and that of a Javaprogrammer.If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the abilityto seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamiccontent, which is embedded within the other HTML/XML content you author. Even better, JSP technologyprovides the means by which programmers can create new HTML/XML tags and JavaBeans components, which

provide new features for HTML designers without those designers needing to learn how to program.Note: A common misconception is that Java code embedded in a JSP page is transmitted with the HTML andexecuted by the user agent (such as a browser). This is not the case. A JSP page is translated into a Javaservlet and executed on the server. JSP statements embedded in the JSP page become part of the servletgenerated from the JSP page. The resulting servlet is executed on the server. It is never visible to the useragent.

52

Page 53: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 53/225

If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writingservlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTMLpages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it.Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSPcode is executed, and the results are returned to the user.

42. How do I mix JSP and SSI #include?

Answer 1If you're just including raw HTML, use the #include directive as usual inside your .jsp file.But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If yourdata.inc file contains jsp code you will have to useThe is used for including non-JSP files.Answer 2If you're just including raw HTML, use the #include directive as usual inside your .jsp file.<!--#include file="data.inc"-->But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. RonelSumibcay ([email protected]) says: If your data.inc file contains jsp code you will have to use<%@ vinclude="data.inc" %>The <!--#include file="data.inc"--> is used for including non-JSP files.

43. How do I mix JSP and SSI #include? What is the difference between include directive & jsp:include action?

Difference between include directive and1. provides the benifits of automatic recompliation,smaller class size ,since the code corresponding to the

included page is not present in the servlet for every included jsp page and option of specifying the additionalrequest parameter.2.The also supports the use of request time attributes valus for dynamically specifying included page whichdirective does not.3.the include directive can only incorporate contents from a static document.4. can be used to include dynamically generated output eg. from servlets.5.include directive offers the option of sharing local variables,better run time efficiency.6.Because the include directive is processed during translation and compilation,it does not impose anyrestrictions on output buffering.

44. How do you prevent the Creation of a Session in a JSP Page and why? What is the difference betweeninclude directive & jsp:include action?

By default, a JSP page will automatically create a session for the request if one does not exist.However, sessions consume resources and if it is not necessary to maintain a session, one should not be

created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by notcreating useless sessions.

45. How do I use a scriptlet to initialize a newly instantiated bean?

A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automaticallyinvoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setPropertytags to initialize the newly instantiated bean, although you are not restricted to using those alone.The following example shows the "today" property of the Foo bean initialized to the current date when it isinstantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.value=""/ >

46. How can I set a cookie and delete a cookie from within a JSP page?

A cookie, mycookie, can be deleted using the following scriptlet:

47. How do you connect to the database from JSP?

A Connection to a database can be established from a jsp page by writing the code to establish a connectionusing a jsp scriptlets.Further then you can use the resultset object "res" to read data in the following way.

48. What is the page directive is used to prevent a JSP page from automatically creating a session?

<%@ page session="false">

49. How do you delete a Cookie within a JSP?

Cookie mycook = new Cookie("name","value");response.addCookie(mycook);Cookie killmycook = new Cookie("mycook","value");

killmycook.setMaxAge(0);killmycook.setPath("/");killmycook.addCookie(killmycook);

50. Can we implement an interface in a JSP?

No

53

Page 54: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 54/225

51. What is the difference between ServletContext and PageContext?

ServletContext: Gives the information about the containerPageContext: Gives the information about the Request

52. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resourcecontext.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

53. How to pass information from JSP to included JSP?Using <%jsp:param> tag.

54. How is JSP include directive different from JSP include action.

When a JSP include directive is used, the included file's code is added into the added JSP page at pagetranslation time, this happens before the JSP page is translated into a servlet. While if any page is includedusing action tag, the page's output is returned back to the added page. This happens at runtime.

55. Can we override the jspInit(), _jspService() and jspDestroy() methods?

We can override jspinit() and jspDestroy() methods but not _jspService().

56. Why is _jspService() method starting with an '_' while other life cycle methods do not?

 _jspService() method will be written by the container hence any methods which are not to be overridden bythe end user are typically written starting with an '_'. This is the reason why we don't override _jspService()method in any JSP page.

57.Explain the life cycle of JSP?

Any JSP page goes through 7 phases in its entire lifecyclePhase Name DescriptionPage translation The page is parsed and a Java file containing

the corresponding servlet is created.Page compilation The Java file is compiled.Load class The compiled class is loaded.Create instance An instance of the servlet is created.Call jspInit() This method is called before any other

method to allow initialization.

Call _jspService() This method is called for each request.Call jspDestroy() This method is called when the servlet containerdecides to take the servlet out of service.

58.What happens when a page is statically included in another JSP page?

An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc.) in the currentpage. This process of including a file is also called as static include.

59. A JSP page, include.jsp, has a instance variable "int a", now this page is statically included in another JSPpage, index.jsp, which has a instance variable "int a" declared. What happens when the index.jsp page isrequested by the client?

Compilation error, as two variables with same name can't be declared. This happens because, when a page isincluded statically, entire code of included page becomes part of the new page. at this time there are twodeclarations of variable 'a'. Hence compilation error.

60. Can you override jspInit() method? If yes, In which cases?ye, we can. We do it usually when we need to intialize any members which are to be available for a servlet/JSPthroughout its lifetime.

61. What is the difference between directive include and jsp include?

<%@ include> : Used to include static resources during translation time. : Used to include dynamic content orstatic content during runtime.

62. What is the difference between RequestDispatcher and sendRedirect?

RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirectwith new request and response objects.

63. How does JSP handle runtime exceptions?Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page isintended to URL redirecting of a JSP.

64. How can my application get to know when a HttpSession is removed?

54

Page 55: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 55/225

Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement thefunctionality what you need in valueUnbound() method.Create an instance of that class and put that instance in HttpSession

SERVLET

1. What is Servlet?

A servlet is a Java technology-based Web component, managed by a container called servlet container orservlet engine, that generates dynamic content and interacts with web clients via a request\/responseparadigm.

2. Why is Servlet so popular?

Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code thatcan be loaded dynamically into and run by a Java technology-enabled Web server.

3. What is servlet container?

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

4. When a client request is sent to the servlet container, how does the container choose which servlet toinvoke?

The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls itwith objects representing the request and response.

5. If a servlet is not properly initialized, what exception may be thrown?

During initialization or service of a request, the servlet instance can throw an UnavailableException or aServletException.

6. Given the request path below, which are context path, servlet path and path info?

 /bookstore/education/index.html

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

7. What is filter? Can filter be used as request or response?

A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and headerinformation. Filters do not generally create a response or respond to a request as servlets do, rather theymodify or adapt the requests for a resource, and modify or adapt responses from a resource.

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

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

9. What is new in ServletRequest interface?(Servlet 2.4)

The following methods have been added to ServletRequest 2.4 version:public int getRemotePort()public java.lang.String getLocalName()public java.lang.String getLocalAddr()public int getLocalPort()

10. Request parameter How to find whether a parameter exists in the request object?

1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));2. boolean hasParameter = request.getParameterMap().contains(theParameter);(which works in Servlet 2.3+)

11. How can I send user authentication information while makingURLConnection?

You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP

authorization.

12. Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't.The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors witharguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet

55

Page 56: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 56/225

containers still will only call your no-arg constructor. So you won't have access to a ServletConfig orServletContext.

13. How can a servlet refresh automatically if some new data has entered the database?

You can use a client-side Refresh or Server Push

14. The code in a finally clause will never fail to execute, right?

Using System.exit(1); in try block will not allow finally code to execute.

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

16. Difference between GET and POST

In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to260 characters, not secure, faster, quick and easy.In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL andimposes no size limitations on the form's output. It is used to send a chunk of data to the server to beprocessed, more versatile, most secure.

17. What is session?

The session is an object used by a servlet to track a user's interaction with a Web application across multipleHTTP requests.

18. What is servlet mapping?

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to maprequests to servlets.

19. What is servlet context ?

The servlet context is an object that contains a servlet's view of the Web application within which the servlet isrunning. Using the context, a servlet can log events, obtain URL references to resources, and set and storeattributes that other servlets in the context can use. (answer supplied by Sun's tutorial).

20. Which interface must be implemented by all servlets?

Servlet interface.

21. Explain the life cycle of Servlet.

Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( usinginit()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.

22. When is the servlet instance created in the life cycle of servlet? What is the importance of configuring aservlet?

An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method isused to configure this servlet instance. This method is called only once in the life time of a servlet, hence itmakes sense to write all those configuration details about a servlet which are required for the whole life of aservlet in this method.

23. Why don't we write a constructor in a servlet?

Container writes a no argument constructor for our servlet.

24. When we don't write any constructor for the servlet, how does container create an instance of servlet?

Container creates instance of servlet by calling Class.forName(className).newInstance().

25. Once the destroy() method is called by the container, will the servlet be immediately destroyed? Whathappens to the tasks(threads) that the servlet might be executing at that time?

Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that areexecuting the servlet’s service() method to finish.

26. What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext?

We can give relative URL when we use ServletRequest and not while using ServletContext.

27. Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we canuse the same while calling ServletRequest.getRequestDispatcher()?

Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

56

Page 57: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 57/225

JDBC

1. What is new in JDBC 2.0?

With the JDBC 2.0 API, you will be able to do the following:

• Scroll forward and backward in a result set or move to a specific row(TYPE_SCROLL_SENSITIVE,previous(), last(), absolute(), relative(), etc.)

• Make updates to database tables using methods in the Java programming language instead of using

SQL commands.(updateRow(), insertRow(), deleteRow(), etc.)• Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch())

• Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.

2. How to move the cursor in scrollable resultsets?(new feature in JDBC 2.0)

a. create a scrollable ResultSet object.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery("SELECT COLUMN_1,COLUMN_2 FROM TABLE_NAME");

b. use a built in methods like afterLast(), previous(), beforeFirst(), etc. to scroll the resultset.

srs.afterLast();while (srs.previous()) {

String name = srs.getString("COLUMN_1");float salary = srs.getFloat("COLUMN_2");//...

c. to find a specific row, use absolute(), relative() methods.

srs.absolute(4); // cursor is on the fourth rowint rowNum = srs.getRow(); // rowNum should be 4srs.relative(-3);int rowNum = srs.getRow(); // rowNum should be 1srs.relative(2);int rowNum = srs.getRow(); // rowNum should be 3

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

3. How to update a resultset programmatically? (new feature in JDBC 2.0)

a. create a scrollable and updatable ResultSet object.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

ResultSet uprs = stmt.executeQuery("SELECT COLUMN_1,COLUMN_2 FROM TABLE_NAME");

b. move the cursor to the specific position and use related method to update data and then, call updateRow()method.

uprs.last();uprs.updateFloat("COLUMN_2", 25.55);//update last row's datauprs.updateRow();//don't miss this method, otherwise,

 // the data will be lost.

4. How to insert and delete a row programmatically? (new feature in JDBC 2.0)

Make sure the resultset is updatable.

1. move the cursor to the specific position.uprs.moveToCurrentRow();

2. set value for each column.

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

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

uprs.insertRow();

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

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

To see the changes call refreshRow();

57

Page 58: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 58/225

uprs.refreshRow();

5. What is JDBC?

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

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

7. What is JDBC Driver interface?

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by theJDBC API. Each vendor driver must provide implementations of the

 java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

8. What are the common tasks of JDBC?

Create an instance of a JDBC driver or load JDBC drivers through jdbc.driversRegister a driverSpecify a databaseOpen a database connection

Submit a queryReceive resultsProcess results

9. How to use JDBC to connect Microsoft Access?

There is a specific tutorial at javacamp.org. Check it out.

10. What are four types of JDBC driver?

Type 1 Drivers

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

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

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

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

11. Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the jdbc calls into vendor specificprotocol calls and it directly interacts with the database.

12. What is the query used to display all tables names in SQL Server (Query analyzer)?

select * from information_schema.tables

13. How many types of JDBC Drivers are present and what are they?

There are 4 types of JDBC DriversType 1: JDBC-ODBC Bridge DriverType 2: Native API Partly Java Driver

Type 3: Network protocol DriverType 4: JDBC Net pure Java Driver

14. What is the fastest type of JDBC driver?

58

Page 59: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 59/225

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

SQL

SQLSQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to yourdatabase.

SQL*PLUSSQL*PLUS is an application that recognizes & executes SQL commands & specialized SQL*Plus commands thatcan customize reports, provide help & edit facility & maintain system variables.

NVLNVL : Null value function converts a null value to a non-null value for the purpose of evaluating an expression.Numeric Functions accept numeric I/P & return numeric values. They are MOD, SQRT, ROUND, TRUNC & POWER.

Date FunctionsDate Functions are ADD_MONTHS, LAST_DAY, NEXT_DAY, MONTHS_BETWEEN & SYSDATE.

Character FunctionsCharacter Functions are INITCAP, UPPER, LOWER, SUBSTR & LENGTH. Additional functions are GREATEST & LEAST. Group Functions returns results based upon groups of rows rather than one result per row, use groupfunctions. They are AVG, COUNT, MAX, MIN & SUM.

TTITLE & BTITLETTITLE & BTITLE are commands to control report headings & footers.

COLUMNCOLUMN command define column headings & format data values.

BREAKBREAK command clarify reports by suppressing repeated values, skipping lines & allowing for controlled breakpoints.

COMPUTEcommand control computations on subsets created by the BREAK command.

SETSET command changes the system variables affecting the report environment.

SPOOLSPOOL command creates a print file of the report.

JOINJOIN is the form of SELECT command that combines info from two or more tables.Types of Joins are Simple (Equijoin & Non-Equijoin), Outer & Self join.Equijoin returns rows from two or more tables joined together based upon a equality condition in the WHEREclause.Non-Equijoin returns rows from two or more tables based upon a relationship other than the equality conditionin the WHERE clause.Outer Join combines two or more tables returning those rows from one table that have no direct match in theother table.Self Join joins a table to itself as though it were two separate tables.

UnionUnion is the product of two or more tables.

IntersectIntersect is the product of two tables listing only the matching rows.

59

Page 60: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 60/225

MinusMinus is the product of two tables listing only the non-matching rows.

Correlated SubqueryCorrelated Subquery is a subquery that is evaluated once for each row processed by the parent statement.Parent statement can be Select, Update or Delete. Use CRSQ to answer multipart questions whose answerdepends on the value in each row processed by parent statement.

Multiple columnsMultiple columns can be returned from a Nested Subquery.

SequencesSequences are used for generating sequence numbers without any overhead of locking. Drawback is that aftergenerating a sequence number if the transaction is rolled back, then that sequence number is lost.

SynonymsSynonyms is the alias name for table, views, sequences & procedures and are created for reasons of Securityand Convenience.Two levels are Public - created by DBA & accessible to all the users. Private - Accessible to creator only.Advantages are referencing without specifying the owner and Flexibility to customize a more meaningfulnaming convention.

IndexesIndexes are optional structures associated with tables used to speed query execution and/or guaranteeuniqueness. Create an index if there are frequent retrieval of fewer than 10-15% of the rows in a large tableand columns are referenced frequently in the WHERE clause. Implied tradeoff is query speed vs. update speed.Oracle automatically update indexes. Concatenated index max. is 16 columns.

Data typesMax. columns in a table is 255. Max. Char size is 255, Long is 64K & Number is 38 digits.Cannot Query on a long column.Char, Varchar2 Max. size is 2000 & default is 1 byte.Number(p,s) p is precision range 1 to 38, s is scale -84 to 127.Long Character data of variable length upto 2GB.Date Range from Jan 4712 BC to Dec 4712 AD.Raw Stores Binary data (Graphics Image & Digitized Sound). Max. is 255 bytes.

Mslabel Binary format of an OS label. Used primarily with Trusted Oracle.

Order of SQL statement executionWhere clause, Group By clause, Having clause, Order By clause & Select.

TransactionTransaction is defined as all changes made to the database between successive commits.

CommitCommit is an event that attempts to make data in the database identical to the data in the form. It involveswriting or posting data to the database and committing data to the database. Forms check the validity of thedata in fields and records during a commit. Validity check are uniqueness, consistency and db restrictions.

PostingPosting is an event that writes Inserts, Updates & Deletes in the forms to the database but not committingthese transactions to the database.

RollbackRollback causes work in the current transaction to be undone.

SavepointSavepoint is a point within a particular transaction to which you may rollback without rolling back the entiretransaction.

Set TransactionSet Transaction is to establish properties for the current transaction.

LockingLocking are mechanisms intended to prevent destructive interaction between users accessing data. Locks areused to achieve.

60

Page 61: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 61/225

ConsistencyConsistency : Assures users that the data they are changing or viewing is not changed until the are thro' withit.

IntegrityAssures database data and structures reflects all changes made to them in the correct sequence. Locks ensuredata integrity and maximum concurrent access to data. Commit statement releases all locks. Types of locksare given below.Data Locks protects data i.e. Table or Row lock.

Dictionary Locks protects the structure of database object i.e. ensures table's structure does not change for theduration of the transaction.Internal Locks & Latches protects the internal database structures. They are automatic.Exclusive Lock allows queries on locked table but no other activity is allowed.Share Lock allows concurrent queries but prohibits updates to the locked tables.Row Share allows concurrent access to the locked table but prohibits for a exclusive table lock.Row Exclusive same as Row Share but prohibits locking in shared mode.Shared Row Exclusive locks the whole table and allows users to look at rows in the table but prohibit othersfrom locking the table in share or updating them.Share Update are synonymous with Row Share.

DeadlockDeadlock is a unique situation in a multi user system that causes two or more users to wait indefinitely for alocked resource. First user needs a resource locked by the second user and the second user needs a resourcelocked by the first user. To avoid dead locks, avoid using exclusive table lock and if using, use it in the samesequence and use Commit frequently to release locks.

Mutating TableMutating Table is a table that is currently being modified by an Insert, Update or Delete statement.Constraining Table is a table that a triggering statement might need to read either directly for a SQL statementor indirectly for a declarative Referential Integrity constraints. Pseudo Columns behaves like a column in atable but are not actually stored in the table. E.g. Currval, Nextval, Rowid, Rownum, Level etc.

SQL*LoaderSQL*Loader is a product for moving data in external files into tables in an Oracle database. To load data fromexternal files into an Oracle database, two types of input must be provided to SQL*Loader : the data itself andthe control file. The control file describes the data to be loaded. It describes the Names and format of the datafiles, Specifications for loading data and the Data to be loaded (optional). Invoking the loader sqlloadusername/password controlfilename <options>.

1. The most important DDL statements in SQL are:

CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table

CREATE INDEX - creates an index (search key)

DROP INDEX - deletes an index

2. Operators used in SELECT statements.

= Equal<> or != Not equal> Greater than< Less than>= Greater than or equal<= Less than or equalBETWEEN Between an inclusive rangeLIKE Search for a pattern

3. SELECT statements:

SELECT column_name(s) FROM table_nameSELECT DISTINCT column_name(s) FROM table_nameSELECT column FROM table WHERE column operator valueSELECT column FROM table WHERE column LIKE pattern

SELECT column,SUM(column) FROM table GROUP BY columnSELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition valueNote that single quotes around text values and numeric values should not be enclosed in quotes. Doublequotes may be acceptable in some databases.

4. The SELECT INTO Statement is most often used to create backup copies of tables or for archiving records.

61

Page 62: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 62/225

SELECT column_name(s) INTO newtable [IN externaldatabase] FROM sourceSELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE column_name operatorvalue

5. The INSERT INTO Statements:

INSERT INTO table_name VALUES (value1, value2,....)INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

6. The Update Statement:UPDATE table_name SET column_name = new_value WHERE column_name = some_value

7. The Delete Statements:

DELETE FROM table_name WHERE column_name = some_valueDelete All Rows:DELETE FROM table_name or DELETE * FROM table_name

8. Sort the Rows:

SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..SELECT column1, column2, ... FROM table_name ORDER BY columnX DESCSELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC

9. The IN operator may be used if you know the exact value you want to return for at least one of the columns.SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)

10. BETWEEN ... AND

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values canbe numbers, text, or dates.

11. What is the use of CASCADE CONSTRAINTS?

When this clause is used with the DROP command, a parent table can be dropped even when a child tableexists.

12. Why does the following command give a compilation error?

DROP TABLE &TABLE_NAME; Variable names should start with an alphabet. Here the table name starts with an'&' symbol.

13. Which system tables contain information on privileges granted and privileges obtained?

USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

14. Which system table contains information on constraints on all the tables created?obtained?

USER_CONSTRAINTS.

15. What is the difference between TRUNCATE and DELETE commands?

< TRUNCATE. with and DELETE used be can clause WHERE back. rolled cannot operation TRUNCATE but back,Hence command. DML a is whereas command DDL>

16. State true or false. !=, <>, ^= all denote the same operation?

True.

17. State true or false. EXISTS, SOME, ANY are operators in SQL?

True.

18. What will be the output of the following query?

SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;?

19. What does the following query do?

SELECT SAL + NVL(COMM,0) FROM EMP;?

This displays the total salary of all employees. The null values in the commission column will be replaced by 0and added to salary.

20. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?

The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.

62

Page 63: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 63/225

21. Which command executes the contents of a specified file?

START or @.

22. What is the value of comm and sal after executing the following query if the initial value of ‘sal’ is 10000UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;?

sal = 11000, comm = 1000.

23. Which command displays the SQL command in the SQL buffer, and then executes it?

RUN.

24. What command is used to get back the privileges offered by the GRANT command?

REVOKE.

25. What will be the output of the following query? SELECTDECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO.

Explanation : The query checks whether a given string is a numerical digit.

26. Which date function is used to find the difference between two dates?

MONTHS_BETWEEN.

27. What operator performs pattern matching?

LIKE operator.

28. What is the use of the DROP option in the ALTER TABLE command?

It is used to drop constraints specified on the table.

29. What operator tests column for the absence of data?

IS NULL operator.

30. What are the privileges that can be granted on a table by a user to others?

Insert, update, delete, select, references, index, execute, alter, all.

31. Which function is used to find the largest integer less than or equal to a specific value?

FLOOR.

32. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?

Data Definition Language (DDL).

33. What is the use of DESC in SQL?

DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descendingorder.Explanation :The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending

order.

34. What command is used to create a table by copying the structure of another table?

CREATE TABLE .. AS SELECT commandExplanation:To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as inthe following.CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the newtable.

35. TRUNCATE TABLE EMP;DELETE FROM EMP;Will the outputs of the above two commands differ?

Both will result in deleting all the rows in the table EMP..

36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?

1200.

63

Page 64: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 64/225

37. What are the wildcards used for pattern matching.?

 _ for single character substitution and % for multi-character substitution.

38. What is the parameter substitution symbol used with INSERT INTO command?

39. What's an SQL injection?

SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run.

40. What is difference between TRUNCATE & DELETE

TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire onTRUNCATEDELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire onDELETE.

41. What is a join? Explain the different types of joins?

Join is a query, which retrieves related columns or rows from multiple tables.Self Join - Joining the table with itself.Equi Join - Joining two tables by equating two common columns.Non-Equi Join - Joining two tables by equating two common columns.Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding

 join value in the other table.

42. What is the sub-query?

Sub-query is a query whose return values are used in filtering conditions of the main query.

43. What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.

44. Explain CONNECT BY PRIOR?

Retrieves rows in hierarchical order eg.select empno, ename from emp where.

45. Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)),INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nthposition of string1.SUBSTR (String1 n, m)SUBSTR returns a character string of size m in string1, starting from n-th position of string1.

46. Explain UNION, MINUS, UNION ALL and INTERSECT?

INTERSECT - returns all distinct rows selected by both queries. MINUS - returns all distinct rows selected bythe first query but not by the second. UNION - returns all distinct rows selected by either query UNION ALL -returns all rows selected by either query, including all duplicates.

47. What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber arethe components of ROWID.

48. What is the fastest way of accessing a row in a table?

Using ROWID.CONSTRAINTS

49. What is an integrity constraint?

Integrity constraint is a rule that restricts values to a column in a table.

50. What is referential integrity constraint?

Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tablesbased on the values of primary key or unique key of the referenced table.

51. What is the usage of SAVEPOINTS?

SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of atransaction. Maximum of five save points are allowed.

64

Page 65: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 65/225

52. What is ON DELETE CASCADE?

When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removingdependent foreign key values if a referenced primary or unique key value is removed.

53. What are the data types allowed in a table?

CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

54. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type?

CHAR pads blank spaces to the maximum length.VARCHAR2 does not pad blank spaces.For CHAR the maximum length is 255 and 2000 for VARCHAR2.

55. How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause orORDER BY?

Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

56. What are the pre-requisites to modify datatype of a column and to add a column with NOT NULLconstraint?

- To modify the datatype of a column the column must be empty.

- To add a column with NOT NULL constrain, the table must be empty.

57. Where the integrity constraints are stored in data dictionary?

The integrity constraints are stored in USER_CONSTRAINTS.

58. How will you activate/deactivate integrity constraints?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLECONSTRAINT.

59. If unique key constraint on DATE column is created, will it validate the rows that are inserted withSYSDATE?

It won't, Because SYSDATE format contains time attached with it.

60. What is a database link?

Database link is a named path through which a remote database can be accessed.

60. How to access the current value and next value from a sequence? Is it possible to access the current valuein a session before accessing next value?

Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value in thesession, current value can be accessed.

60.What is CYCLE/NO CYCLE in a Sequence?

CYCLE specifies that the sequence continue to generate values after reaching either maximum or minimumvalue. After pan-ascending sequence reaches its maximum value, it generates its minimum value. After adescending sequence reaches its minimum, it generates its maximum.

NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimumvalue.

61. What are the advantages of VIEW?

- To protect some of the columns of a table from other users.- To hide complexity of a query.- To hide complexity of calculations.

62. Can a view be updated/inserted/deleted? If Yes - under what conditions?

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from oneor more tables then insert, update and delete is not possible.

63. If a view on a single base table is manipulated will the changes be reflected on the base table?

If changes are made to the tables and these tables are the base tables of a view, then the changes will bereference on the view.

64. Which of the following statements is true about implicit cursors?

65

Page 66: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 66/225

1. Implicit cursors are used for SQL statements that are not named.2. Developers should use implicit cursors with great care.3. Implicit cursors are used in cursor for loops to handle data processing.4. Implicit cursors are no longer a feature in Oracle.

65. Which of the following is not a feature of a cursor FOR loop?

1. Record type declaration.2. Opening and parsing of SQL statements.3. Fetches records from cursor.4. Requires exit condition to be defined.

66. A developer would like to use referential datatype declaration on a variable. The variable name isEMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. Howwould the developer define this variable using referential datatypes?

1. Use employee.lname%type.2. Use employee.lname%rowtype.3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.4. Declare it to be type LONG.

67. Which three of the following are implicit cursor attributes?

1. %found2. %too_many_rows

3. %notfound4. %rowcount5. %rowtype

68. If left out, which of the following would cause an infinite loop to occur in a simple loop?

1. LOOP2. END LOOP3. IF-THEN4. EXIT

69. Which line in the following statement will produce an error?

1. cursor action_cursor is2. select name, rate, action

3. into action_record4. from action_table;5. There are no errors in this statement.

70. The command used to open a CURSOR FOR loop is

1. open2. fetch3. parse4. None, cursor for loops handle cursor opening implicitly.

71. What happens when rows are found using a FETCH statement

1. It causes the cursor to close2. It causes the cursor to open

3. It loads the current row values into variables4. It creates the variables to hold the current row values

72. Read the following code:10. CREATE OR REPLACE PROCEDURE find_cpt11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)12. IS13. BEGIN14. IF v_cost_per_ticket > 8.5 THEN15. SELECT cost_per_ticket16. INTO v_cost_per_ticket17. FROM gross_receipt18. WHERE movie_id = v_movie_id;19. END IF;20. END;

Which mode should be used for V_COST_PER_TICKET?1. IN2. OUT3. RETURN4. IN OUT

66

Page 67: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 67/225

73. Read the following code:22. CREATE OR REPLACE TRIGGER update_show_gross23. {trigger information}24. BEGIN25. {additional code}26. END;

The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which triggerinformation will you add?

1. WHEN (new.cost_per_ticket > 3.75)2. WHEN (:new.cost_per_ticket > 3.753. WHERE (new.cost_per_ticket > 3.75)4. WHERE (:new.cost_per_ticket > 3.75)

74. What is the maximum number of handlers processed before the PL/SQL block is exited when an exceptionoccurs?

1. Only one2. All that apply3. All referenced4. None

77. For which trigger timing can you reference the NEW and OLD qualifiers?

1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger

78. Read the following code:CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)RETURN number IS

v_yearly_budget NUMBER;

BEGINSELECT yearly_budgetINTO v_yearly_budgetFROM studioWHERE id = v_studio_id;

RETURN v_yearly_budget;END;Which set of statements will successfully invoke this function within SQL*Plus?1. VARIABLE g_yearly_budget NUMBEREXECUTE g_yearly_budget := GET_BUDGET(11);2. VARIABLE g_yearly_budget NUMBEREXECUTE :g_yearly_budget := GET_BUDGET(11);3. VARIABLE :g_yearly_budget NUMBEREXECUTE :g_yearly_budget := GET_BUDGET(11);4. VARIABLE g_yearly_budget NUMBER

31. CREATE OR REPLACE PROCEDURE update_theater32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS33. BEGIN34. UPDATE theater

35. SET name = v_name36. WHERE id = v_theater_id;37. END update_theater;

79. When invoking this procedure, you encounter the error:ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.How should you modify the function to handle this error?1. An user defined exception must be declared and associated with the error code and handled in theEXCEPTION section.2. Handle the error in EXCEPTION section by referencing the error code directly.3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.

80. Read the following code:

40. CREATE OR REPLACE PROCEDURE calculate_budget IS41. v_budget studio.yearly_budget%TYPE;42. BEGIN43. v_budget := get_budget(11);44. IF v_budget < 3000045. THEN46. set_budget(11,30000000);

67

Page 68: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 68/225

47. END IF;48. END;

You are about to add an argument to CALCULATE_BUDGET. What effect will this have?1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.3. Only the CALCULATE_BUDGET procedure needs to be recompiled.4. All three procedures are marked invalid and must be recompiled.

81. Which procedure can be used to create a customized error message?1. RAISE_ERROR2. SQLERRM3. RAISE_APPLICATION_ERROR4. RAISE_SERVER_ERROR

82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue toenable this trigger?1. ALTER TRIGGER check_theater ENABLE;2. ENABLE TRIGGER check_theater;3. ALTER TABLE check_theater ENABLE check_theater;4. ENABLE check_theater;

83. Examine this database trigger

52. CREATE OR REPLACE TRIGGER prevent_gross_modification53. {additional trigger information}54. BEGIN55. IF TO_CHAR(sysdate, DY) = MON56. THEN57. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);58. END IF;59. END;

This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entireDELETE statement. What additional information must you add?1. BEFORE DELETE ON gross_receipt2. AFTER DELETE ON gross_receipt3. BEFORE (gross_receipt DELETE)4. FOR EACH ROW DELETED FROM gross_receipt

84. Examine this function:61. CREATE OR REPLACE FUNCTION set_budget62. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS63. BEGIN64. UPDATE studio65. SET yearly_budget = v_new_budgetWHERE id = v_studio_id;

IF SQL%FOUND THENRETURN TRUEl;ELSERETURN FALSE;END IF;

COMMIT;END;

Which code must be added to successfully compile this function?1. Add RETURN right before the IS keyword.2. Add RETURN number right before the IS keyword.3. Add RETURN boolean right after the IS keyword.4. Add RETURN boolean right before the IS keyword.

85. Under which circumstance must you recompile the package body after recompiling the packagespecification?1. Altering the argument list of one of the package constructs2. Any change made to one of the package constructs3. Any SQL statement change made to one of the package constructs

4. Removing a local variable from the DECLARE section of one of the package constructs

86. Procedure and Functions are explicitly executed. This is different from a database trigger. When is adatabase trigger executed?1. When the transaction is committed2. During the data manipulation statement

68

Page 69: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 69/225

3. When an Oracle supplied package references the trigger4. During a data manipulation statement and when the transaction is committed

87. Which Oracle supplied package can you use to output values and messages from database triggers, storedprocedures and functions within SQL*Plus?1. DBMS_DISPLAY 2. DBMS_OUTPUT 3. DBMS_LIST 4. DBMS_DESCRIBE

88. What occurs if a procedure or function terminates with failure without being handled?

1. Any DML statements issued by the construct are still pending and can be committed or rolled back.2. Any DML statements issued by the construct are committed3. Unless a GOTO statement is used to continue processing within the BEGIN section, the construct terminates.

4. The construct rolls back any DML statements issued and returns the unhandled exception to the callingenvironment.

89. Examine this code71. BEGIN72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;73. END;

For this code to be successful, what must be true?1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist onlyin the body of the THEATER_PCK package.2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package.

3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCKpackage.4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist inthe specification of the THEATER_PCK package.

90 A stored function must return a value based on conditions that are determined at runtime. Therefore, theSELECT statement cannot be hard-coded and must be created dynamically when the function is executed.Which Oracle supplied package will enable this feature?

1. DBMS_DDL2. DBMS_DML3. DBMS_SYN4. DBMS_SQL

90 A stored function must return a value based on conditions that are determined at runtime. Therefore, theSELECT statement cannot be hard-coded and must be created dynamically when the function is executed.Which Oracle supplied package will enable this feature?

1. DBMS_DDL2. DBMS_DML3. DBMS_SYN4. DBMS_SQL

91 How to implement ISNUMERIC function in SQL *Plus ?

Method 1:

Select length (translate (trim (column_name),' +-.0123456789',' ')) from dual ;

Will give you a zero if it is a number or greater than zero if not numeric (actually gives the count of nonnumeric characters)

Method 2:

select instr(translate('wwww','abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),'X')FROM dual;

It returns 0 if it is a number, 1 if it is not.

92 How to Select last N records from a Table?

select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm)where a > ( select (max(rownum)-10) from clm)

Here N = 10

The following query has a Problem of performance in the execution of the following query where the tableter.ter_master have 22231 records. So the results are obtained after hours.

Cursor rem_master(brepno VARCHAR2) IS

69

Page 70: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 70/225

select a.* from ter.ter_master awhere NOT a.repno in (select repno from ermast) and(brepno = 'ALL' or a.repno > brepno)Order by a.repno

What are steps required tuning this query to improve its performance?

-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO

-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution path that Oracle takes.If you are using Cost Based Optimizer mode, then be sure that your statistics on TER_MASTER are up-to-date.-Also, you can change your SQL to:

SELECT a.*FROM ter.ter_master aWHERE NOT EXISTS (SELECT b.repno FROM ermast bWHERE a.repno=b.repno) AND(a.brepno = 'ALL' or a.repno > a.brepno)ORDER BY a.repno;

93 What is the difference between Truncate and Delete interms of Referential Integrity?

DELETE removes one or more records in a table, checking referential Constraints (to see if there are dependentchild records) and firing any DELETE triggers. In the order you are deleting (child first then parent) There willbe no problems.

TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it only checks for theexistence (and status) of another foreign key Pointing to the table. If one exists and is enabled, then you willget The following error. This is true even if you do the child tables first.ORA-02266: unique/primary keys in table referenced by enabled foreign keysYou should disable the foreign key constraints in the child tables before issuing the TRUNCATE command, thenre-enable them afterwards.

94. What does preemptive in preemptive multitasking mean ?

Preemptive refers to the fact that each task is alloted fixed time slots and at the end of that time slot the nexttask is started.

95. What does the OLTP stands for ?

OLTP stands for On Line Transaction Processing

96. What is the most important requirement for OLTP ?

OLTP requires real time response.

97. In a client server environment, what would be the major work that the client deals with ?

The client deals with the user interface part of the system.

98. Why is the most of the processing done at the sever ?

To reduce the network traffic and for application sharing and implementing business rules.

99. What does teh term upsizing refer to ?

Applications that have outgrown their environment are re-engineered to run in a larger environment. This is

upsizing.

100. What does one do when one is rightsizing ?

With rightsizing, one would move applications to the most appropriate server platforms.

101. What does the term downsizing refer to ?

A host based application is re-engineered to run in smaller or LAN based environment.

102. What is event trigger ?

An event trigger, a segment of code which is associated with each event and is fired when the event occurs.

103. Why do stored procedures reduce network traffic ?

When a stored procedure is called, only the procedure call is sent to the server and not the statements that theprocedure contains.

CLIENT/SERVER

70

Page 71: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 71/225

104. What are the types of processes that a server runs ?

Foreground process and Background process.

105. What is a event handler ?

An event handler is a routine that is written to respond to a particular event.

106. What is an integrity constraint ?

An integrity constraint allows the definition of certain restrictions, at the table level, on the data that is enteredinto a table.

107. What are the various uses of database triggers ?

Database triggers can be used to enforce business rules, to maintain derived values and perform value-basedauditing.

108. What is a transaction ?

A transaction is a set of operations that begin when the first DML is issued and end when a commit or rollbackis issued. BEGIN COMMIT/ROLLBACK are the boundries of a transaction.

109. Why are the integrity constraints preferred to database triggers ?

Because it is easier to define an integrity constraint than a database trigger.

110. Why is it better to use an integrity constraint to validate data in a table than to use a stored procedure ?

Because an integrity constraint is automatically checked while data is inserted into a table. A stored has to bespecifically invoked.

111. What are the three components of a client server model ?

A Client,A Server andA Network/Communication software.

112. What are the advantages of client/server model ?

Flexibility of the system, scalability, cost saving, centralised control and implementation of business rules,increase of developers productivity, portability, improved network and resource utilization.

113. What are the disadvantages of the client/server model ?

Heterogeneity of the system results in reduced reliablity. May not be suitable for all applications. Managing andtuning networks becomes difficult.

114. What are the different topologies available for network ?

Star,Bus,Ring.

115. What is the first work of Client process ?

A client process at first establishes connection with the Server.

115. What are the responsibilities of a Server ?

1. Manage resources optimally across multiple clients.2. Controlling database access and security.3. Protecting the databse and recovering it from crashes.4. Enforcing integrity rules globally.

116. In a Client/Server context, what does API (Application Programming Interface) refer to ?

An API, in a Client/Server context, is a specification of a set of functions for communication between the clientand the server.

117. Give some examples of standard API??s ?Open Database Connectivity (ODBC),Integrated Database Application Programming Interface (IDAPI),XOpenSQL/CLI

71

Page 72: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 72/225

118. What is the main advantage of developing an application using an API ?

The application can be connected to any back end server that is supported by the API.

119. What is the main disadvantage of developing an application using an API ?

The application cannot use any special features of the backend server.

120. Why is an event driven program referred to a passive program ?

Because an event driven program is always waiting for something to happen before processing.

120. What are the four types of events ?

1. System Events.2. Control Events3. User Events4. Other Events.

121. What is the difference between file server and a database server ?

A file server just transfers all the data requested by all its client and the client processes the data while adatabase server runs the query and sends only the query output.

122. What is inheritance ?

Inheritance is a method by which properties and methods of an existing object are automatically passed to anyobject derived from it.

123. What are the two components of ODBC ?

1. An ODBC manager/administrator and2. ODBC driver.

124. What is the function of a ODBC manager ?

The ODBC Manager manages all the data sources that exists in the system.

125. What is the function of a ODBC Driver ?

The ODBC Driver allows the developer to talk to the back end database.

126. What description of a data source is required for ODBC ?

The name of the DBMS, the location of the source and the database dependent information.

127. How is a connection establised by ODBC ?

ODBC uses the description of the datasource available in the ODBC.INI file to load the required drivers toaccess that particular back end database.

PL/SQL

1. Describe the difference between a procedure, function and anonymous pl/sql block.Level: LowExpected answer : Candidate should mention use of DECLARE statement, a function must return avalue while a procedure doesn?t have to.

2. What is a mutating table error and how can you get around it?Level: IntermediateExpected answer: This happens with triggers. It occurs because the trigger is trying to update a row itis currently using. The usual fix involves either use of views or temporary tables so the database isselecting from one while updating the other.

3. Describe the use of %ROWTYPE and %TYPE in PL/SQLLevel: LowExpected answer: %ROWTYPE allows you to associate a variable with an entire table row. The %TYPEassociates a variable with a single column type.

4. What packages (if any) has Oracle provided for use by developers?Level: Intermediate to highExpected answer: Oracle provides the DBMS_ series of packages. There are many which developersshould be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK,DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE. If they canmention a few of these and describe how they used them, even better. If they include the SQLroutines provided by Oracle, great, but not really what was asked.

72

Page 73: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 73/225

5. Describe the use of PL/SQL tablesLevel: IntermediateExpected answer: PL/SQL tables are scalar arrays that can be referenced by a binary integer. Theycan be used to hold values for use in later queries or calculations. In Oracle 8 they will be able to beof the %ROWTYPE designation, or RECORD.

6. When is a declare statement needed ?Level: LowThe DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone, non-storedPL/SQL procedures. It must come first in a PL/SQL stand alone file if it is used.

7. In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented if youuse the %NOTFOUND cursor variable in the exit when statement? Why?Level: IntermediateExpected answer: OPEN then FETCH then LOOP followed by the exit when. If not specified in thisorder will result in the final return being done twice because of the way the %NOTFOUND is handledby PL/SQL.

2.

3.

8. What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?Level: IntermediateExpected answer: SQLCODE returns the value of the error number for the last error encountered. TheSQLERRM returns the actual error message for the last error encountered. They can be used in

exception handling to report, or, store in an error log table, the error that occurred in the code. Theseare especially useful for the WHEN OTHERS exception.

9. How can you find within a PL/SQL block, if a cursor is open?Level: LowExpected answer: Use the %ISOPEN cursor status variable.

10. How can you generate debugging output from PL/SQL?Level:Intermediate to highExpected answer: Use the DBMS_OUTPUT package. Another possible method is to just use the SHOWERROR command, but this only shows errors. The DBMS_OUTPUT package can be used to showintermediate results from loops and the status of variables as the procedure is executed. The newpackage UTL_FILE can also be used.

11. What are the types of triggers?

Level:Intermediate to highExpected Answer: There are 12 types of triggers in PL/SQL that consist of combinations of theBEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:BEFORE ALL ROW INSERTAFTER ALL ROW INSERTBEFORE INSERTAFTER INSERT etc.

SQL/ SQLPlus

1. How can variables be passed to a SQL routine?Level: LowExpected answer: By use of the & symbol. For passing in variables the numbers 1-8 can be used (&1,&2,...,&8) to pass the values after the command into the SQLPLUS session. To be prompted for aspecific variable, place the ampersanded variable in the code itself:"select * from dba_tables where owner=&owner_name;" . Use of double ampersands tells SQLPLUS toresubstitute the value for each subsequent use of the variable, a single ampersand will cause areprompt for the value unless an ACCEPT statement is used to get the value from the user.

2. You want to include a carriage return/linefeed in your output from a SQL script, how can you dothis?Level: Intermediate to highExpected answer: The best method is to use the CHR() function (CHR(10) is a return/linefeed) andthe concatenation function "||". Another method, although it is hard to document and isn?t alwaysportable is to use the return/linefeed as a part of a quoted string.

3. How can you call a PL/SQL procedure from SQL?Level: IntermediateExpected answer: By use of the EXECUTE (short form EXEC) command.

4. How do you execute a host operating system command from within SQL?

Level: LowExpected answer: By use of the exclamation point "!" (in UNIX and some other OS) or the HOST (HO)command.

5. You want to use SQL to build SQL, what is this called and give an exampleLevel: Intermediate to high

73

Page 74: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 74/225

Expected answer: This is called dynamic SQL. An example would be:set lines 90 pages 0 termout off feedback off verify off spool drop_all.sqlselect ?drop user ?||username||? cascade;? from dba_userswhere username not in ("SYS?,?SYSTEM?);spool off Essentially you are looking to see that they know to include a command (in this case DROPUSER...CASCADE;) and that you need to concatenate using the ?||? the values selected from thedatabase.

6. What SQLPlus command is used to format output from a select?Level: lowExpected answer: This is best done with the COLUMN command.

7. You want to group the following set of select returns, what can you group on?Max(sum_of_cost), min(sum_of_cost), count(item_no), item_noLevel: IntermediateExpected answer: The only column that can be grouped on is the "item_no" column, the rest haveaggregate functions associated with them.

8. What special Oracle feature allows you to specify how the cost based system treats a SQLstatement?Level: Intermediate to highExpected answer: The COST based system allows the use of HINTs to control the optimizer pathselection. If they can give some example hints such as FIRST ROWS, ALL ROWS, USING INDEX,

STAR, even better.

9. You want to determine the location of identical rows in a table before attempting to place a uniqueindex on the table, how can this be done?Level: HighExpected answer: Oracle tables always have one guaranteed unique column, the rowid column. If youuse a min/max function against your rowid and then select against the proposed primary key you cansqueeze out the rowids of the duplicate rows pretty quick. For example:select rowid from emp ewhere e.rowid > (select min(x.rowid)from emp xwhere x.emp_no = e.emp_no);In the situation where multiple columns make up the proposed key, they must all be used in thewhere clause.

10. What is a Cartesian product?Level: LowExpected answer: A Cartesian product is the result of an unrestricted join of two or more tables. Theresult set of a three table Cartesian product will have x * y * z number of rows where x, y, zcorrespond to the number of rows in each table involved in the join.

11. You are joining a local and a remote table, the network manager complains about the trafficinvolved, how can you reduce the network traffic?Level: HighExpected answer: Push the processing of the remote data to the remote instance by using a view topre-select the information for the join. This will result in only the data required for the join being sentacross.

12. What is the default ordering of an ORDER BY clause in a SELECT statement?Level: Low

Expected answer: Ascending13. What is tkprof and how is it used?Level: Intermediate to highExpected answer: The tkprof tool is a tuning tool used to determine cpu and execution times for SQLstatements. You use it by first setting timed_statistics to true in the initialization file and then turningon tracing for either the entire database via the sql_trace parameter or for the session using theALTER SESSION command. Once the trace file is generated you run the tkprof tool against the tracefile and then look at the output from the tkprof tool. This can also be used to generate explain planoutput.

14. What is explain plan and how is it used?Level: Intermediate to highExpected answer: The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you musthave an explain_table generated in the user you are running the explain plan for. This is created usingthe utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving asits argument the SQL statement to be explained. The explain_plan table is then queried to see theexecution plan of the statement. Explain plans can also be run using tkprof.

15. How do you set the number of lines on a page of output? The width?Level: LowExpected answer: The SET command in SQLPLUS is used to control the number of lines generated per

74

Page 75: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 75/225

page and the width of those lines, for example SET PAGESIZE 60 LINESIZE 80 will generate reportsthat are 60 lines long with a line width of 80 characters. The PAGESIZE and LINESIZE options can beshortened to PAGES and LINES.

16. How do you prevent output from coming to the screen?Level: LowExpected answer: The SET option TERMOUT controls output to the screen. Setting TERMOUT OFFturns off screen output. This option can be shortened to TERM.

17. How do you prevent Oracle from giving you informational messages during and after a SQLstatement execution?Level: LowExpected answer: The SET options FEEDBACK and VERIFY can be set to OFF.

18. How do you generate file output from SQL?Level: LowExpected answer: By use of the SPOOL command

J2EE

1. What is J2EE?

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

2. What is the J2EE module?

A J2EE module consists of one or more J2EE components for the same container type and one componentdeployment descriptor of that type.

3. What are the components of J2EE application?

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with itsrelated classes and files and communicates with other components. The J2EE specification defines the followingJ2EE components:

• Application clients and applets are client components.

• Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.

• Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.

Resource adapter components provided by EIS and tool vendors.

4. What are the four types of J2EE modules?

1. Application client module2. Web module3. Enterprise JavaBeans module4. Resource adapter module

5. What does application client module contain?

The application client module contains:--class files,--an application client deployment descriptor.Application client modules are packaged as JAR files with a .jar extension.

6. What does web module contain?

The web module contains:--JSP files,--class files for servlets,--GIF and HTML files, and--a Web deployment descriptor.Web modules are packaged as JAR files with a .war (Web ARchive) extension

7. What are the differences between Ear, Jar and War files? Under what circumstances should we use eachone?

There are no structural differences between the files; they are all archived using zip-jar compression. However,they are intended for different purposes.--Jar files (files with a .jar extension) are intended to hold generic libraries of Java classes, resources, auxiliary

files, etc.--War files (files with a .war extension) are intended to contain complete Web applications. In this context, aWeb application is defined as a single group of files, classes, resources, .jar files that can be packaged andaccessed as one servlet context.--Ear files (files with a .ear extension) are intended to contain complete enterprise applications. In this context,an enterprise application is defined as a collection of .jar files, resources, classes, and multiple Webapplications.

75

Page 76: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 76/225

Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJBcontainers, etc.

8. What is the difference between Session bean and Entity bean?one?

The Session bean and Entity bean are two main parts of EJB container.Session Bean--represents a workflow on behalf of a client--one-to-one logical mapping to a client.--created and destroyed by a client--not permanent objects--lives its EJB container(generally) does not survive system shut down--two types: stateless and stateful beansEntity Bean--represents persistent data and behavior of this data--can be shared among multiple clients--persists across multiple invocations--findable permanent objects--outlives its EJB container, survives system shutdown--two types: container managed persistence(CMP) and bean managed persistence(BMP)

9. What is "applet"

A J2EE component that typically executes in a Web browser but can execute in a variety of other applicationsor devices that support the applet programming model.

10. What is "applet container"

A container that includes support for the applet programming model.

11. What is "application assembler"

A person who combines J2EE components and modules into deployable application units.

12. What is "application client"

A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have accessto some J2EE platform APIs.

13. What is "application client container"

A container that supports application client components.

14. What is "application client module"

A software unit that consists of one or more classes and an application client deployment descriptor.

15. What is "application component provider"

A vendor that provides the Java classes that implement components' methods, JSP page definitions, and anyrequired deployment descriptors.

16. What is "application configuration resource file"

An XML file used to configure resources for a JavaServer Faces application, to define navigation rules for theapplication, and to register converters, validators, listeners, renderers, and components with the application.

17. What is "archiving"

The process of saving the state of an object and restoring it.

18. What is "asant"

A Java-based build tool that can be extended using Java classes. The configuration files are XML-based, callingout a target tree where various tasks get executed.

19. What is "attribute"What is "asant"

A qualifier on an XML tag that provides additional information.

20. What is authentication ?

The process that verifies the identity of a user, device, or other entity in a computer system, usually as aprerequisite to allowing access to resources in a system. The Java servlet specification requires three types of authentication-basic, form-based, and mutual-and supports digest authentication.

21. What is authorization?

76

Page 77: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 77/225

The process by which access to a method or resource is determined. Authorization depends on thedetermination of whether the principal associated with a request through authentication is in a given securityrole. A security role is a logical grouping of users defined by the person who assembles the application. Adeployer maps security roles to security identities. Security identities may be principals or groups in theoperational environment.

22. What is authorization constraint

An authorization rule that determines who is permitted to access a Web resource collection.

23. What is B2B

B2B stands for Business-to-business.

24. What is backing bean

A JavaBeans component that corresponds to a JSP page that includes JavaServer Faces components. Thebacking bean defines properties for the components on the page and methods that perform processing for thecomponent. This processing includes event handling, validation, and processing associated with navigation.

25. What is basic authentication

An authentication mechanism in which a Web server authenticates an entity via a user name and passwordobtained using the Web application's built-in authentication mechanism.

26. What is bean-managed persistence

The mechanism whereby data transfer between an entity bean's variables and a resource manager is managedby the entity bean.

27. What is bean-managed transaction

A transaction whose boundaries are defined by an enterprise bean.

28. What is binding (XML)

Generating the code needed to process a well-defined portion of XML data.

29. What is binding (JavaServer Faces technology)

Wiring UI components to back-end data sources such as backing bean properties.

30. What is build file

The XML file that contains one or more asant targets. A target is a set of tasks you want to be executed. Whenstarting asant, you can select which targets you want to have executed. When no target is given, the project'sdefault target is executed.

31. What is business logic

The code that implements the functionality of an application. In the Enterprise JavaBeans architecture, thislogic is implemented by the methods of an enterprise bean.

32.What is business method

A method of an enterprise bean that implements the business logic or rules of an application.

33. What is callback methodsComponent methods called by the container to notify the component of important events in its life cycle.

34. What is caller

Same as caller principal.

35. What is caller principal

The principal that identifies the invoker of the enterprise bean method.

36. What is cascade delete

A deletion that triggers another deletion. A cascade delete can be specified for an entity bean that hascontainer-managed persistence.

37. What is CDATA

A predefined XML tag for character data that means "don't interpret these characters," as opposed to parsedcharacter data (PCDATA), in which the normal rules of XML syntax apply. CDATA sections are typically used toshow examples of XML syntax.

77

Page 78: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 78/225

38. What is certificate authority

A trusted organization that issues public key certificates and provides identification to the bearer.

39. What is client-certificate authentication

An authentication mechanism that uses HTTP over SSL, in which the server and, optionally, the clientauthenticate each other with a public key certificate that conforms to a standard that is defined by X.509 PublicKey Infrastructure.

40. What is comment

In an XML document, text that is ignored unless the parser is specifically told to recognize it.

41. What is commit

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

42. What is component contract

The contract between a J2EE component and its container. The contract includes life-cycle management of thecomponent, a context interface that the instance uses to obtain various information and services from itscontainer, and a list of services that every container must provide for its components.

43. What is component-managed sign-on

A mechanism whereby security information needed for signing on to a resource is provided by an applicationcomponent.

44. What is connector

A standard extension mechanism for containers that provides connectivity to enterprise information systems. Aconnector is specific to an enterprise information system and consists of a resource adapter and applicationdevelopment tools for enterprise information system connectivity. The resource adapter is plugged in to acontainer through its support for system-level contracts defined in the Connector architecture.

45. What is Connector architecture

An architecture for integration of J2EE products with enterprise information systems. There are two parts tothis architecture: a resource adapter provided by an enterprise information system vendor and the J2EEproduct that allows this resource adapter to plug in. This architecture defines a set of contracts that a resource

adapter must support to plug in to a J2EE product-for example, transactions, security, and resourcemanagement.

46. What is container

An entity that provides life-cycle management, security, deployment, and runtime services to J2EEcomponents. Each type of container (EJB, Web, JSP, servlet, applet, and application client) also providescomponent-specific services.

47. What is container-managed persistence

The mechanism whereby data transfer between an entity bean's variables and a resource manager is managedby the entity bean's container.

48. What is container-managed sign-on

The mechanism whereby security information needed for signing on to a resource is supplied by the container.

49. What is container-managed transaction

A transaction whose boundaries are defined by an EJB container. An entity bean must use container-managedtransactions.

50. What is content

In an XML document, the part that occurs after the prolog, including the root element and everything itcontains.

51. What is context attribute

An object bound into the context associated with a servlet.

52. What is context root

A name that gets mapped to the document root of a Web application.

53. What is conversational state

78

Page 79: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 79/225

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

54. What is CORBA

Common Object Request Broker Architecture. A language-independent distributed object model specified bythe OMG.

55. What is create method

A method defined in the home interface and invoked by a client to create an enterprise bean.

56. What is credentials

The information describing the security attributes of a principal.

57. What is CSS

Cascading style sheet. A stylesheet used with HTML and XML documents to add a style to all elements markedwith a particular tag, for the direction of browsers or other presentation mechanisms.

58. What is CTS

Compatibility test suite. A suite of compatibility tests for verifying that a J2EE product complies with the J2EEplatform specification.

59. What is data

The contents of an element in an XML stream, generally used when the element does not contain anysubelements. When it does, the term content is generally used. When the only text in an XML structure iscontained in simple elements and when elements that have subelements have little or no data mixed in, thenthat structure is often thought of as XML data, as opposed to an XML document.

60. What is DDP

Document-driven programming. The use of XML to define applications.

61. What is declaration

The very first thing in an XML document, which declares it as XML. The minimal declaration is . The declarationis part of the document prolog.

62. What is declarative securityMechanisms used in an application that are expressed in a declarative syntax in a deployment descriptor.

63. What is delegation

An act whereby one principal authorizes another principal to use its identity or privileges with somerestrictions.

64. What is deployer

A person who installs J2EE modules and applications into an operational environment.

65. What is deployment

The process whereby software is installed into an operational environment.

66. What is deployment descriptor

An XML file provided with each module and J2EE application that describes how they should be deployed. Thedeployment descriptor directs a deployment tool to deploy a module or application with specific containeroptions and describes specific configuration requirements that a deployer must resolve.

67. What is destination

A JMS administered object that encapsulates the identity of a JMS queue or topic. See point-to-pointmessaging system, publish/subscribe messaging system.

68. What is digest authentication

An authentication mechanism in which a Web application authenticates itself to a Web server by sending theserver a message digest along with its HTTP request message. The digest is computed by employing a one-wayhash algorithm to a concatenation of the HTTP request message and the client's password. The digest is

typically much smaller than the HTTP request and doesn't contain the password.

69. What is distributed application

79

Page 80: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 80/225

An application made up of distinct components running in separate runtime environments, usually on differentplatforms connected via a network. Typical distributed applications are two-tier (client-server), three-tier(client-middleware-server), and multitier (client-multiple middleware-multiple servers).

67. What is document

In general, an XML structure in which one or more elements contains text intermixed with subelements.

68. What is Document Object Model

An API for accessing and manipulating XML documents as tree structures. DOM provides platform-neutral,language-neutral interfaces that enables programs and scripts to dynamically access and modify content andstructure in XML documents.

69. What is document root

The top-level directory of a WAR. The document root is where JSP pages, client-side classes and archives, andstatic Web resources are stored.

70. What is DTD

Document type definition. An optional part of the XML document prolog, as specified by the XML standard. TheDTD specifies constraints on the valid tags and tag sequences that can be in the document. The DTD has anumber of shortcomings, however, and this has led to various schema proposals. For example, the DTD entrysays that the XML element called username contains parsed character data-that is, text alone, with no other

structural elements under it. The DTD includes both the local subset, defined in the current file, and theexternal subset, which consists of the definitions contained in external DTD files that are referenced in the localsubset using a parameter entity.

71. What is durable subscription

In a JMS publish/subscribe messaging system, a subscription that continues to exist whether or not there is acurrent active subscriber object. If there is no active subscriber, the JMS provider retains the subscription'smessages until they are received by the subscription or until they expire.

72. What is EAR file

Enterprise Archive file. A JAR archive that contains a J2EE application.

73. What is ebXML

Electronic Business XML. A group of specifications designed to enable enterprises to conduct business throughthe exchange of XML-based messages. It is sponsored by OASIS and the United Nations Centre for theFacilitation of Procedures and Practices in Administration, Commerce and Transport (U.N./CEFACT).

74. What is EJB

Enterprise JavaBeans.

75. What is EJB container

A container that implements the EJB component contract of the J2EE architecture. This contract specifies aruntime environment for enterprise beans that includes security, concurrency, life-cycle management,transactions, deployment, naming, and other services. An EJB container is provided by an EJB or J2EE server.

76. What is EJB container providerA vendor that supplies an EJB container.

77. What is EJB context

A vendor that supplies an EJB container. An object that allows an enterprise bean to invoke services providedby the container and to obtain the information about the caller of a client-invoked method.

78. What is EJB home object

An object that provides the life-cycle operations (create, remove, find) for an enterprise bean. The class for theEJB home object is generated by the container's deployment tools. The EJB home object implements theenterprise bean's home interface. The client references an EJB home object to perform life-cycle operations onan EJB object. The client uses JNDI to locate an EJB home object.

79. What is EJB JAR fileA JAR archive that contains an EJB module.

80. What is EJB module

A deployable unit that consists of one or more enterprise beans and an EJB deployment descriptor.

80

Page 81: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 81/225

81. What is EJB object

An object whose class implements the enterprise bean's remote interface. A client never references anenterprise bean instance directly; a client always references an EJB object. The class of an EJB object isgenerated by a container's deployment tools.

82. What is EJB server

Software that provides services to an EJB container. For example, an EJB container typically relies on a

transaction manager that is part of the EJB server to perform the two-phase commit across all the participatingresource managers. The J2EE architecture assumes that an EJB container is hosted by an EJB server from thesame vendor, so it does not specify the contract between these two entities. An EJB server can host one ormore EJB containers.

83. What is EJB server provider

A vendor that supplies an EJB server.

83. What is EJB server provider

What is element

A unit of XML data, delimited by tags. An XML element can enclose other elements.

84. What is empty tagA tag that does not enclose any content.

85. What is enterprise bean

A J2EE component that implements a business task or business entity and is hosted by an EJB container;either an entity bean, a session bean, or a message-driven bean.

86. What is enterprise bean provider

An application developer who produces enterprise bean classes, remote and home interfaces, and deploymentdescriptor files, and packages them in an EJB JAR file.

87. What is enterprise information system

The applications that constitute an enterprise's existing system for handling companywide information. Theseapplications provide an information infrastructure for an enterprise. An enterprise information system offers a

well-defined set of services to its clients. These services are exposed to clients as local or remote interfaces orboth. Examples of enterprise information systems include enterprise resource planning systems, mainframetransaction processing systems, and legacy database systems.

88. What is enterprise information system resource

An entity that provides enterprise information system-specific functionality to its clients. Examples are a recordor set of records in a database system, a business object in an enterprise resource planning system, and atransaction program in a transaction processing system.

89. What is Enterprise JavaBeans (EJB)

A component architecture for the development and deployment of object-oriented, distributed, enterprise-levelapplications. Applications written using the Enterprise JavaBeans architecture are scalable, transactional, andsecure.

90. What is Enterprise JavaBeans Query Language (EJB QL)

Defines the queries for the finder and select methods of an entity bean having container-managed persistence.A subset of SQL92, EJB QL has extensions that allow navigation over the relationships defined in an entitybean's abstract schema.

91. What is an entity

A distinct, individual item that can be included in an XML document by referencing it. Such an entity referencecan name an entity as small as a character (for example, <, which references the less-than symbol or leftangle bracket, <). An entity reference can also reference an entire document, an external entity, or a collectionof DTD definitions.

92. What is entity bean

An enterprise bean that represents persistent data maintained in a database. An entity bean can manage its

own persistence or can delegate this function to its container. An entity bean is identified by a primary key. If the container in which an entity bean is hosted crashes, the entity bean, its primary key, and any remotereferences survive the crash.

93. What is entity reference

81

Page 82: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 82/225

A reference to an entity that is substituted for the reference when the XML document is parsed. It canreference a predefined entity such as < or reference one that is defined in the DTD. In the XML data, thereference could be to an entity that is defined in the local subset of the DTD or to an external XML file (anexternal entity). The DTD can also carve out a segment of DTD specifications and give it a name so that it canbe reused (included) at multiple points in the DTD by defining a parameter entity.

94. What is error

A SAX parsing error is generally a validation error; in other words, it occurs when an XML document is notvalid, although it can also occur if the declaration specifies an XML version that the parser cannot handle. Seealso fatal error, warning.

95. What is Extensible Markup Language

XML.

96. What is external entity

An entity that exists as an external XML file, which is included in the XML document using an entity reference.

96. What is external subset

That part of a DTD that is defined by references to external DTD files.

97. What is fatal error

A fatal error occurs in the SAX parser when a document is not well formed or otherwise cannot be processed.See also error, warning.

98. What is filter

An object that can transform the header or content (or both) of a request or response. Filters differ from Webcomponents in that they usually do not themselves create responses but rather modify or adapt the requestsfor a resource, and modify or adapt responses from a resource. A filter should not have any dependencies on aWeb resource for which it is acting as a filter so that it can be composable with more than one type of Webresource.

99. What is filter chain

A concatenation of XSLT transformations in which the output of one transformation becomes the input of thenext.

100. What is finder method

A method defined in the home interface and invoked by a client to locate an entity bean.

101. What is form-based authentication

An authentication mechanism in which a Web container provides an application-specific form for logging in.This form of authentication uses Base64 encoding and can expose user names and passwords unless allconnections are over SSL.

102. What is general entity

An entity that is referenced as part of an XML document's content, as distinct from a parameter entity, which isreferenced in the DTD. A general entity can be a parsed entity or an unparsed entity.

103. What is group

An authenticated set of users classified by common traits such as job title or customer profile. Groups are alsoassociated with a set of roles, and every user that is a member of a group inherits all the roles assigned to thatgroup.

104. What is handle

An object that identifies an enterprise bean. A client can serialize the handle and then later deserialize it toobtain a reference to the enterprise bean.

105. What is home handle

An object that can be used to obtain a reference to the home interface. A home handle can be serialized andwritten to stable storage and deserialized to obtain the reference.

107. What is home interface

One of two interfaces for an enterprise bean. The home interface defines zero or more methods for managingan enterprise bean. The home interface of a session bean defines create and remove methods, whereas thehome interface of an entity bean defines create, finder, and remove methods.

108. What is HTML

82

Page 83: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 83/225

Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables theembedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic textformatting.

109. What is HTTP

Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTPmessages consist of requests from client to server and responses from server to client.

110. What is HTTPS

HTTP layered over the SSL protocol.

111. What is IDL

Interface Definition Language. A language used to define interfaces to remote CORBA objects. The interfacesare independent of operating systems and programming languages.

112. What is IIOP

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

113. What is impersonation

An act whereby one entity assumes the identity and privileges of another entity without restrictions andwithout any indication visible to the recipients of the impersonator's calls that delegation has taken place.

Impersonation is a case of simple delegation.

114. What is initialization parameter

A parameter that initializes the context associated with a servlet.

115. What is ISO 3166

The international standard for country codes maintained by the International Organization for Standardization(ISO).

116. What is ISV

Independent software vendor.

117. What is J2EE

Java 2 Platform, Enterprise Edition.

118. What is J2EE application

Any deployable unit of J2EE functionality. This can be a single J2EE module or a group of modules packagedinto an EAR file along with a J2EE application deployment descriptor. J2EE applications are typically engineeredto be distributed across multiple computing tiers.

119. What is J2EE component

A self-contained functional software unit supported by a container and configurable at deployment time. TheJ2EE specification defines the following J2EE components: Application clients and applets are components thatrun on the client. Java servlet and JavaServer Pages (JSP) technology components are Web components thatrun on the server. Enterprise JavaBeans (EJB) components (enterprise beans) are business components thatrun on the server. J2EE components are written in the Java programming language and are compiled in thesame way as any program in the language. The difference between J2EE components and "standard" Javaclasses is that J2EE components are assembled into a J2EE application, verified to be well formed and incompliance with the J2EE specification, and deployed to production, where they are run and managed by theJ2EE server or client container.

120. What is J2EE module

A software unit that consists of one or more J2EE components of the same container type and one deploymentdescriptor of that type. There are four types of modules: EJB, Web, application client, and resource adapter.Modules can be deployed as stand-alone units or can be assembled into a J2EE application

121. What is J2EE product

An implementation that conforms to the J2EE platform specification.

122. What is J2EE product provider

A vendor that supplies a J2EE product.

123. What is J2EE server

The runtime portion of a J2EE product. A J2EE server provides EJB or Web containers or both.

83

Page 84: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 84/225

124. What is J2ME

Abbreviate of Java 2 Platform, Micro Edition.

125. What is J2SE

Abbreviate of Java 2 Platform, Standard Edition.

126. What is JAR

Java archive. A platform-independent file format that permits many files to be aggregated into one file.127. What is Java 2 Platform, Enterprise Edition (J2EE)

An environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developingmultitiered, Web-based applications.

128. What is Java 2 Platform, Micro Edition (J2ME)

A highly optimized Java runtime environment targeting a wide range of consumer products, including pagers,cellular phones, screen phones, digital set-top boxes, and car navigation systems.

129. What is Java 2 Platform, Standard Edition (J2SE)

The core Java technology platform.

130. What is Java API for XML Processing (JAXP)An API for processing XML documents. JAXP leverages the parser standards SAX and DOM so that you canchoose to parse your data as a stream of events or to build a tree-structured representation of it. JAXPsupports the XSLT standard, giving you control over the presentation of the data and enabling you to convertthe data to other XML documents or to other formats, such as HTML. JAXP provides namespace support,allowing you to work with schema that might otherwise have naming conflicts.

131. What is Java API for XML Registries (JAXR)

An API for accessing various kinds of XML registries.

132. What is Java API for XML-based RPC (JAX-RPC)

An API for building Web services and clients that use remote procedure calls and XML

133. What is Java IDLA technology that provides CORBA interoperability and connectivity capabilities for the J2EE platform. Thesecapabilities enable J2EE applications to invoke operations on remote network services using the ObjectManagement Group IDL and IIOP.

134. What is Java Message Service (JMS)

An API for invoking operations on enterprise messaging systems.

135. What is Java Naming and Directory Interface (JNDI)

An API that provides naming and directory functionality.

136. What is Java Secure Socket Extension (JSSE)

A set of packages that enable secure Internet communications.

137. What is Java Transaction API (JTA)

An API that allows applications and J2EE servers to access transactions.

138. What is Java Transaction Service (JTS)

Specifies the implementation of a transaction manager that supports JTA and implements the Java mapping of the Object Management Group Object Transaction Service 1.1 specification at the level below the API.

139. What is JavaBeans component

A Java class that can be manipulated by tools and composed into applications. A JavaBeans component mustadhere to certain property and event interface conventions.

140. What is JavaMail

An API for sending and receiving email.

141. What is JavaServer Faces Technology

A framework for building server-side user interfaces for Web applications written in the Java programminglanguage.

84

Page 85: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 85/225

142. What is JavaServer Faces conversion model

A mechanism for converting between string-based markup generated by JavaServer Faces UI components andserver-side Java objects.

143. What is JavaServer Faces event and listener model

A mechanism for determining how events emitted by JavaServer Faces UI components are handled. This modelis based on the JavaBeans component event and listener model.

144. What is JavaServer Faces expression language

A simple expression language used by a JavaServer Faces UI component tag attributes to bind the associatedcomponent to a bean property or to bind the associated component's value to a method or an external datasource, such as a bean property. Unlike JSP EL expressions, JavaServer Faces EL expressions are evaluated bythe JavaServer Faces implementation rather than by the Web container

145. What is JavaServer Faces navigation model

A mechanism for defining the sequence in which pages in a JavaServer Faces application are displayed.

147. What is JavaServer Faces UI component

A user interface control that outputs data to a client or allows a user to input data to a JavaServer Facesapplication.

148. What is JavaServer Faces UI component class

A JavaServer Faces class that defines the behavior and properties of a JavaServer Faces UI component.

149. What is JavaServer Faces validation model

A mechanism for validating the data a user inputs to a JavaServer Faces UI component.

150. What is JavaServer Pages (JSP)

An extensible Web technology that uses static data, JSP elements, and server-side Java objects to generatedynamic content for a client. Typically the static data is HTML or XML elements, and in many cases the client isa Web browser.

151. What is JavaServer Pages Standard Tag Library (JSTL)

A tag library that encapsulates core functionality common to many JSP applications. JSTL has support forcommon, structural tasks such as iteration and conditionals, tags for manipulating XML documents,internationalization and locale-specific formatting tags, SQL tags, and functions.

152. What is JAXR client

A client program that uses the JAXR API to access a business registry via a JAXR provider.

153. What is JAXR provider

An implementation of the JAXR API that provides access to a specific registry provider or to a class of registryproviders that are based on a common specification.

154. What is JDBC

An JDBC for database-independent connectivity between the J2EE platform and a wide range of data sources.

155. What is JMS

Java Message Service.

156. What is JMS administered object

A preconfigured JMS object (a resource manager connection factory or a destination) created by anadministrator for the use of JMS clients and placed in a JNDI namespace

157. What is JMS application

One or more JMS clients that exchange messages.

158. What is JMS client

A Java language program that sends or receives messages.

159. What is JMS provider

A messaging system that implements the Java Message Service as well as other administrative and controlfunctionality needed in a full-featured messaging product.

85

Page 86: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 86/225

160. What is JMS session

A single-threaded context for sending and receiving JMS messages. A JMS session can be nontransacted,locally transacted, or participating in a distributed transaction.

161. What is JNDI

Abbreviate of Java Naming and Directory Interface.

162. What is JSP

Abbreviate of JavaServer Pages.

163. What is JSP action

A JSP element that can act on implicit objects and other server-side objects or can define new scriptingvariables. Actions follow the XML syntax for elements, with a start tag, a body, and an end tag; if the body isempty it can also use the empty tag syntax. The tag must use a prefix. There are standard and custom actions.

164. What is JSP container

A container that provides the same services as a servlet container and an engine that interprets and processesJSP pages into a servlet.

165. What is JSP container, distributed

A JSP container that can run a Web application that is tagged as distributable and is spread across multiple

Java virtual machines that might be running on different hosts.

167. What is JSP custom action

A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP pageby a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.

168. What is JSP custom tag

A tag that references a JSP custom action.

169. What is JSP declaration

A JSP scripting element that declares methods, variables, or both in a JSP page.

170. What is JSP directive

A JSP element that gives an instruction to the JSP container and is interpreted at translation time.

171. What is JSP document

A JSP page written in XML syntax and subject to the constraints of XML documents.

172. What is JSP element

A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or ascripting element.

173. What is JSP expression

A scripting element that contains a valid scripting language expression that is evaluated, converted to a String,and placed into the implicit out object.

174. What is JSP expression language

A language used to write expressions that access the properties of JavaBeans components. EL expressions canbe used in static text and in any standard or custom tag attribute that can accept an expression.

175. What is JSP page

A text-based document containing static text and JSP elements that describes how to process a request tocreate a response. A JSP page is translated into and handles requests as a servlet.

176. What is JSP scripting element

A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose contentis written according to the scripting language used in the JSP page. The JSP specification describes the syntaxand semantics for the case where the language page attribute is "java".

177. What is JSP scriptletA JSP scripting element containing any code fragment that is valid in the scripting language used in the JSPpage. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is"java".

86

Page 87: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 87/225

178. What is JSP standard action

An action that is defined in the JSP specification and is always available to a JSP page.

179. What is JSP tag file

A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP pageis translated into a servlet.

180. What is JSP tag handler

A Java programming language object that implements the behavior of a custom tag.

181. What is JSP tag library

A collection of custom tags described via a tag library descriptor and Java classes.

182. What is JSTL

Abbreviate of JavaServer Pages Standard Tag Library.

183. What is JTA

Abbreviate of Java Transaction API.

184. What is JTS

Abbreviate of Java Transaction Service.

185. What is keystore

A file containing the keys and certificates used for authentication

186. What is life cycle (J2EE component)

The framework events of a J2EE component's existence. Each type of component has defining events thatmark its transition into states in which it has varying availability for use. For example, a servlet is created andhas its init method called by its container before invocation of its service method by clients or other servletsthat require its functionality. After the call of its init method, it has the data and readiness for its intended use.The servlet's destroy method is called by its container before the ending of its existence so that processingassociated with winding up can be done and resources can be released. The init and destroy methods in thisexample are callback methods. Similar considerations apply to the life cycle of all J2EE component types:enterprise beans, Web components (servlets or JSP pages), applets, and application clients.

187. What is life cycle (JavaServer Faces)

A set of phases during which a request for a page is received, a UI component tree representing the page isprocessed, and a response is produced. During the phases of the life cycle: The local data of the components isupdated with the values contained in the request parameters. Events generated by the components areprocessed. Validators and converters registered on the components are processed. The components' local datais updated to back-end objects. The response is rendered to the client while the component state of theresponse is saved on the server for future requests.

188. What is local subset

That part of the DTD that is defined within the current XML file.

189. What is managed bean creation facilityA mechanism for defining the characteristics of JavaBeans components used in a JavaServer Faces application.

190. What is message

In the Java Message Service, an asynchronous request, report, or event that is created, sent, and consumedby an enterprise application and not by a human. It contains vital information needed to coordinate enterpriseapplications, in the form of precisely formatted data that describes specific business actions.

191. What is message consumer

An object created by a JMS session that is used for receiving messages sent to a destination.

192. What is message-driven bean

An enterprise bean that is an asynchronous message consumer. A message-driven bean has no state for aspecific client, but its instance variables can contain state across the handling of client messages, including anopen database connection and an object reference to an EJB object. A client accesses a message-driven beanby sending messages to the destination for which the bean is a message listener

193. What is message producer

An object created by a JMS session that is used for sending messages to a destination.

87

Page 88: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 88/225

194. What is mixed-content model

A DTD specification that defines an element as containing a mixture of text and one more other elements. Thespecification must start with #PCDATA, followed by diverse elements, and must end with the "zero-or-more"asterisk symbol (*).

195. What is method-binding expression

A JavaServer Faces EL expression that refers to a method of a backing bean. This method performs either

event handling, validation, or navigation processing for the UI component whose tag uses the method-bindingexpression.

196. What is method permission

An authorization rule that determines who is permitted to execute one or more enterprise bean methods.

197. What is mutual authentication

An authentication mechanism employed by two parties for the purpose of proving each other's identity to oneanother.

198. What is namespace

A standard that lets you specify a unique label for the set of element names defined by a DTD. A document

using that DTD can be included in any other document without having a conflict between element names. Theelements defined in your DTD are then uniquely identified so that, for example, the parser can tell when anelement should be interpreted according to your DTD rather than using the definition for an element in adifferent DTD.

199. What is naming context

A set of associations between unique, atomic, people-friendly identifiers and objects.

200. What is naming environment

A mechanism that allows a component to be customized without the need to access or change the component'ssource code. A container implements the component's naming environment and provides it to the componentas a JNDI naming context. Each component names and accesses its environment entries using the

 java:comp/env JNDI context. The environment entries are declaratively specified in the component'sdeployment descriptor.

201. What is normalizationThe process of removing redundancy by modularizing, as with subroutines, and of removing superfluousdifferences by reducing them to a common denominator. For example, line endings from different systems arenormalized by reducing them to a single new line, and multiple whitespace characters are normalized to onespace.

202. What is North American Industry Classification System (NAICS)

A system for classifying business establishments based on the processes they use to produce goods orservices.

203. What is notation

A mechanism for defining a data format for a non-XML document referenced as an unparsed entity. This is aholdover from SGML. A newer standard is to use MIME data types and namespaces to prevent namingconflicts.

204. What is OASIS

Organization for the Advancement of Structured Information Standards. A consortium that drives thedevelopment, convergence, and adoption of e-business standards.

205. What is OMG

Object Management Group. A consortium that produces and maintains computer industry specifications forinteroperable enterprise applications.

206. What is one-way messaging

A method of transmitting messages without having to block until a response is received.

207. What is ORB

Object request broker. A library that enables CORBA objects to locate and communicate with one another.

208. What is OS principal

88

Page 89: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 89/225

A principal native to the operating system on which the J2EE platform is executing.

209. What is OTS

Object Transaction Service. A definition of the interfaces that permit CORBA objects to participate intransactions.

220. What is parameter entity

An entity that consists of DTD specifications, as distinct from a general entity. A parameter entity defined inthe DTD can then be referenced at other points, thereby eliminating the need to recode the definition at eachlocation it is used.

221. What is parsed entity

A general entity that contains XML and therefore is parsed when inserted into the XML document, as opposedto an unparsed entity.

222. What is parser

A module that reads in XML data from an input source and breaks it into chunks so that your program knowswhen it is working with a tag, an attribute, or element data. A nonvalidating parser ensures that the XML datais well formed but does not verify that it is valid. See also validating parser.

223. What is passivation

The process of transferring an enterprise bean from memory to secondary storage. See activation.

224. What is persistence

The protocol for transferring the state of an entity bean between its instance variables and an underlyingdatabase.

225. What is persistent field

A virtual field of an entity bean that has container-managed persistence; it is stored in a database.

226. What is POA

Portable Object Adapter. A CORBA standard for building server-side applications that are portable acrossheterogeneous ORBs.

221. What is parsed entity

A general entity that contains XML and therefore is parsed when inserted into the XML document, as opposedto an unparsed entity.

222. What is parser

A module that reads in XML data from an input source and breaks it into chunks so that your program knowswhen it is working with a tag, an attribute, or element data. A nonvalidating parser ensures that the XML datais well formed but does not verify that it is valid. See also validating parser.

223. What is passivation

The process of transferring an enterprise bean from memory to secondary storage. See activation.

224. What is persistence

The protocol for transferring the state of an entity bean between its instance variables and an underlyingdatabase.

225. What is persistent field

A virtual field of an entity bean that has container-managed persistence; it is stored in a database.

226. What is POA

Portable Object Adapter. A CORBA standard for building server-side applications that are portable acrossheterogeneous ORBs.

227. What is point-to-point messaging system

A messaging system built on the concept of message queues. Each message is addressed to a specific queue;

clients extract messages from the queues established to hold their messages.

229. What is primary key

An object that uniquely identifies an entity bean within a home.

89

Page 90: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 90/225

230. What is principal

The identity assigned to a user as a result of authentication.

231. What is privilege

A security attribute that does not have the property of uniqueness and that can be shared by many principals.

232. What is processing instruction

Information contained in an XML structure that is intended to be interpreted by a specific application.

233. What is programmatic security

Security decisions that are made by security-aware applications. Programmatic security is useful whendeclarative security alone is not sufficient to express the security model of an application.

234. What is prolog

The part of an XML document that precedes the XML data. The prolog includes the declaration and an optionalDTD.

235. What is public key certificate

Used in client-certificate authentication to enable the server, and optionally the client, to authenticate eachother. The public key certificate is the digital equivalent of a passport. It is issued by a trusted organization,

called a certificate authority, and provides identification for the bearer.

236. What is publish/subscribe messaging system

A messaging system in which clients address messages to a specific node in a content hierarchy, called a topic.Publishers and subscribers are generally anonymous and can dynamically publish or subscribe to the contenthierarchy. The system takes care of distributing the messages arriving from a node's multiple publishers to itsmultiple subscribers.

237. What is query string

A component of an HTTP request URL that contains a set of parameters and values that affect the handling of the request.

238. What is queue

A messaging system built on the concept of message queues. Each message is addressed to a specific queue;clients extract messages from the queues established to hold their messages.

239. What is RAR

Resource Adapter Archive. A JAR archive that contains a resource adapter module.

240. What is RDF

Resource Description Framework. A standard for defining the kind of data that an XML file contains. Suchinformation can help ensure semantic integrity-for example-by helping to make sure that a date is treated as adate rather than simply as text.

241. What is RDF schema

A standard for specifying consistency rules that apply to the specifications contained in an RDF.

242. What is realm

See security policy domain. Also, a string, passed as part of an HTTP request during basic authentication, thatdefines a protection space. The protected resources on a server can be partitioned into a set of protectionspaces, each with its own authentication scheme or authorization database or both. In the J2EE serverauthentication service, a realm is a complete database of roles, users, and groups that identify valid users of aWeb application or a set of Web applications.

243. What is reentrant entity bean

An entity bean that can handle multiple simultaneous, interleaved, or nested invocations that will not interferewith each other.

244. What is reference

A reference to an entity that is substituted for the reference when the XML document is parsed. It canreference a predefined entity such as < or reference one that is defined in the DTD. In the XML data, thereference could be to an entity that is defined in the local subset of the DTD or to an external XML file (anexternal entity). The DTD can also carve out a segment of DTD specifications and give it a name so that it canbe reused (included) at multiple points in the DTD by defining a parameter entity.

90

Page 91: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 91/225

245. What is registry

An infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral thirdparty that facilitates dynamic and loosely coupled business-to-business (B2B) interactions.

246. What is registry provider

An implementation of a business registry that conforms to a specification for XML registries (for example,ebXML or UDDI).

247. What is relationship fieldA virtual field of an entity bean having container-managed persistence; it identifies a related entity bean.

248. What is remote interface

One of two interfaces for an enterprise bean. The remote interface defines the business methods callable by aclient.

249. What is remove method

Method defined in the home interface and invoked by a client to destroy an enterprise bean.

250. What is render kit

A set of renderers that render output to a particular client. The JavaServer Faces implementation provides a

standard HTML render kit, which is composed of renderers that can render HMTL markup.251. What is renderer

A Java class that can render the output for a set of JavaServer Faces UI components.

252. What is request-response messaging

A method of messaging that includes blocking until a response is received.

253. What is resource adapter

A system-level software driver that is used by an EJB container or an application client to connect to anenterprise information system. A resource adapter typically is specific to an enterprise information system. It isavailable as a library and is used within the address space of the server or client using it. A resource adapterplugs in to a container. The application components deployed on the container then use the client API (exposedby the adapter) or tool-generated high-level abstractions to access the underlying enterprise informationsystem. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.

254. What is resource adapter module

A deployable unit that contains all Java interfaces, classes, and native libraries, implementing a resourceadapter along with the resource adapter deployment descriptor.

255. What is resource manager

Provides access to a set of shared resources. A resource manager participates in transactions that areexternally controlled and coordinated by a transaction manager. A resource manager typically is in a differentaddress space or on a different machine from the clients that access it. Note: An enterprise information systemis referred to as a resource manager when it is mentioned in the context of resource and transactionmanagement.

256. What is resource manager connection

An object that represents a session with a resource manager.

257. What is resource manager connection factory

An object used for creating a resource manager connection.

258. What is RMI

Remote Method Invocation. A technology that allows an object running in one Java virtual machine to invokemethods on an object running in a different Java virtual machine.

259. What is RMI-IIOP

A version of RMI implemented to use the CORBA IIOP protocol. RMI over IIOP provides interoperability with

CORBA objects implemented in any language if all the remote interfaces are originally defined as RMIinterfaces.

260. What is role (development)

91

Page 92: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 92/225

The function performed by a party in the development and deployment phases of an application developedusing J2EE technology. The roles are application component provider, application assembler, deployer, J2EEproduct provider, EJB container provider, EJB server provider, Web container provider, Web server provider,tool provider, and system administrator.

261. What is role mapping

The process of associating the groups or principals (or both), recognized by the container with security rolesspecified in the deployment descriptor. Security roles must be mapped by the deployer before a component isinstalled in the server.

262. What is role (security)

An abstract logical grouping of users that is defined by the application assembler. When an application isdeployed, the roles are mapped to security identities, such as principals or groups, in the operationalenvironment. In the J2EE server authentication service, a role is an abstract name for permission to access aparticular set of resources. A role can be compared to a key that can open a lock. Many people might have acopy of the key; the lock doesn't care who you are, only that you have the right key.

263. What is rollback

The point in a transaction when all updates to any resources involved in the transaction are reversed.

264. What is root

The outermost element in an XML document. The element that contains all other elements.

265. What is SAX

Abbreviation of Simple API for XML.

266. What is Simple API for XML

An event-driven interface in which the parser invokes one of several methods supplied by the caller when aparsing event occurs. Events include recognizing an XML tag, finding an error, encountering a reference to anexternal entity, or processing a DTD specification.

267. What is schema

A database-inspired method for specifying constraints on XML documents using an XML-based language.Schemas address deficiencies in DTDs, such as the inability to put constraints on the kinds of data that canoccur in a particular field. Because schemas are founded on XML, they are hierarchical. Thus it is easier to

create an unambiguous specification, and it is possible to determine the scope over which a comment is meantto apply.

268. What is Secure Socket Layer (SSL)

A technology that allows Web browsers and Web servers to communicate over a secured connection.

267. What is security attributes

A set of properties associated with a principal. Security attributes can be associated with a principal by anauthentication protocol or by a J2EE product provider or both.

268. What is security constraint

A declarative way to annotate the intended protection of Web content. A security constraint consists of a Web

resource collection, an authorization constraint, and a user data constraint.269. What is security context

An object that encapsulates the shared state information regarding security between two entities.

270. What is security permission

A mechanism defined by J2SE, and used by the J2EE platform to express the programming restrictionsimposed on application component developers.

271. What is security permission set

The minimum set of security permissions that a J2EE product provider must provide for the execution of eachcomponent type.

272. What is security policy domain

A scope over which security policies are defined and enforced by a security administrator. A security policydomain has a collection of users (or principals), uses a well-defined authentication protocol or protocols forauthenticating users (or principals), and may have groups to simplify setting of security policies.

273. What is security role

92

Page 93: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 93/225

An abstract logical grouping of users that is defined by the application assembler. When an application isdeployed, the roles are mapped to security identities, such as principals or groups, in the operationalenvironment. In the J2EE server authentication service, a role is an abstract name for permission to access aparticular set of resources. A role can be compared to a key that can open a lock. Many people might have acopy of the key; the lock doesn't care who you are, only that you have the right key.

274. What is security technology domain

A scope over which the same security mechanism is used to enforce a security policy. Multiple security policydomains can exist within a single technology domain.

275. What is security view

The set of security roles defined by the application assembler.

276. What is server certificate

Used with the HTTPS protocol to authenticate Web applications. The certificate can be self-signed or approvedby a certificate authority (CA). The HTTPS service of the Sun Java System Application Server Platform Edition 8will not run unless a server certificate has been installed.

277. What is server principal

The OS principal that the server is executing as.

278. What is service element

A representation of the combination of one or more Connector components that share a single enginecomponent for processing incoming requests.

279. What is service endpoint interface

A Java interface that declares the methods that a client can invoke on a Web service.

280. What is servlet

A Java program that extends the functionality of a Web server, generating dynamic content and interactingwith Web applications using a request-response paradigm.

281. What is servlet container

A container that provides the network services over which requests and responses are sent, decodes requests,

and formats responses. All servlet containers must support HTTP as a protocol for requests and responses butcan also support additional request-response protocols, such as HTTPS.

282. What is servlet container, distributed

A servlet container that can run a Web application that is tagged as distributable and that executes acrossmultiple Java virtual machines running on the same host or on different hosts.

283. What is servlet context

An object that contains a servlet's view of the Web application within which the servlet is running. Using thecontext, a servlet can log events, obtain URL references to resources, and set and store attributes that otherservlets in the context can use.

284. What is servlet mapping

Defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

285. What is session

An object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

286. What is session bean

An enterprise bean that is created by a client and that usually exists only for the duration of a single client-server session. A session bean performs operations, such as calculations or database access, for the client.Although a session bean can be transactional, it is not recoverable should a system crash occur. Session beanobjects either can be stateless or can maintain conversational state across methods and transactions. If asession bean maintains state, then the EJB container manages this state if the object must be removed frommemory. However, the session bean object itself must manage its own persistent data.

287. What is SGML

Standard Generalized Markup Language. The parent of both HTML and XML. Although HTML shares SGML'spropensity for embedding presentation information in the markup, XML is a standard that allows informationcontent to be totally separated from the mechanisms for rendering that content.

93

Page 94: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 94/225

288. What is SOAP

Simple Object Access Protocol. A lightweight protocol intended for exchanging structured information in adecentralized, distributed environment. It defines, using XML technologies, an extensible messaging frameworkcontaining a message construct that can be exchanged over a variety of underlying protocols.

289. What is SOAP with Attachments API for Java (SAAJ)

The basic package for SOAP messaging, SAAJ contains the API for creating and populating a SOAP message.

290. What is SQLStructured Query Language. The standardized relational database language for defining database objects andmanipulating data.

291. What is SQL/J

A set of standards that includes specifications for embedding SQL statements in methods in the Javaprogramming language and specifications for calling Java static methods as SQL stored procedures and user-defined functions. An SQL checker can detect errors in static SQL statements at program development time,rather than at execution time as with a JDBC driver.

292. What is SSL

Secure Socket Layer. A security protocol that provides privacy over the Internet. The protocol allows client-server applications to communicate in a way that cannot be eavesdropped upon or tampered with. Servers are

always authenticated, and clients are optionally authenticated.

293. What is stateful session bean

A session bean with a conversational state.

294. What is stateless session bean

A session bean with no conversational state. All instances of a stateless session bean are identical.

295. What is system administrator

The person responsible for configuring and administering the enterprise's computers, networks, and softwaresystems.

296. What is tagIn XML documents, a piece of text that describes a unit of data or an element. The tag is distinguishable asmarkup, as opposed to data, because it is surrounded by angle brackets (< and >). To treat such markupsyntax as data, you use an entity reference or a CDATA section.

297. What is template

A set of formatting instructions that apply to the nodes selected by an XPath expression.

298. What is tool provider

An organization or software vendor that provides tools used for the development, packaging, and deploymentof J2EE applications.

299. What is transaction attributeA value specified in an enterprise bean's deployment descriptor that is used by the EJB container to control thetransaction scope when the enterprise bean's methods are invoked. A transaction attribute can have thefollowing values: Required, RequiresNew, Supports, NotSupported, Mandatory, or Never.

300. What is transaction

An atomic unit of work that modifies data. A transaction encloses one or more program statements, all of which either complete or roll back. Transactions enable multiple users to access the same data concurrently.

301. What is transaction isolation level

What is transaction isolation level The degree to which the intermediate state of the data being modified by atransaction is visible to other concurrent transactions and data being modified by other transactions is visibleto it.

302. What is transaction manager

Provides the services and management functions required to support transaction demarcation, transactionalresource management, synchronization, and transaction context propagation.

94

Page 95: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 95/225

303. What is Unicode

A standard defined by the Unicode Consortium that uses a 16-bit code page that maps digits to characters inlanguages around the world. Because 16 bits covers 32,768 codes, Unicode is large enough to include all theworld's languages, with the exception of ideographic languages that have a different character for everyconcept, such as Chinese. For more information, see http://www.unicode.org/.

304. What is Universal Description, Discovery and Integration (UDDI) project

An industry initiative to create a platform-independent, open framework for describing services, discovering

businesses, and integrating business services using the Internet, as well as a registry. It is being developed bya vendor consortium.

305. What is Universal Standard Products and Services Classification (UNSPSC)

A schema that classifies and identifies commodities. It is used in sell-side and buy-side catalogs and as astandardized account code in analyzing expenditure.

306. What is unparsed entity

A general entity that contains something other than XML. By its nature, an unparsed entity contains binarydata.

306. What is URI

Uniform resource identifier. A globally unique identifier for an abstract or physical resource. A URL is a kind of 

URI that specifies the retrieval protocol (http or https for Web applications) and physical location of a resource(host name and host-relative path). A URN is another type of URI.

307. What is URL

Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the WorldWide Web. A URL looks like this: protocol://host/localinfo where protocol specifies a protocol for fetching theobject (such as http or ftp), host specifies the Internet name of the targeted host, and localinfo is a string(often a file name) passed to the protocol handler on the remote host.

308. What is URL path

The part of a URL passed by an HTTP request to invoke a servlet. A URL path consists of the context path +servlet path + path info, where Context path is the path prefix associated with a servlet context of which theservlet is a part. If this context is the default context rooted at the base of the Web server's URL namespace,

the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not endwith a / character. Servlet path is the path section that directly corresponds to the mapping that activated thisrequest. This path starts with a / character. Path info is the part of the request path that is not part of thecontext path or the servlet path

309. What is URN

Uniform resource name. A unique identifier that identifies an entity but doesn't tell where it is located. Asystem can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Weblocation to change, while still allowing the entity to be found.

310. What is user data constraint

Indicates how data between a client and a Web container should be protected. The protection can be theprevention of tampering with the data or prevention of eavesdropping on the data.

305. What is Universal Standard Products and Services Classification (UNSPSC)A schema that classifies and identifies commodities. It is used in sell-side and buy-side catalogs and as astandardized account code in analyzing expenditure.

306. What is unparsed entity

A general entity that contains something other than XML. By its nature, an unparsed entity contains binarydata.

306. What is URI

Uniform resource identifier. A globally unique identifier for an abstract or physical resource. A URL is a kind of URI that specifies the retrieval protocol (http or https for Web applications) and physical location of a resource(host name and host-relative path). A URN is another type of URI.

307. What is URLUniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the WorldWide Web. A URL looks like this: protocol://host/localinfo where protocol specifies a protocol for fetching theobject (such as http or ftp), host specifies the Internet name of the targeted host, and localinfo is a string(often a file name) passed to the protocol handler on the remote host.

95

Page 96: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 96/225

308. What is URL path

The part of a URL passed by an HTTP request to invoke a servlet. A URL path consists of the context path +servlet path + path info, where Context path is the path prefix associated with a servlet context of which theservlet is a part. If this context is the default context rooted at the base of the Web server's URL namespace,the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not endwith a / character. Servlet path is the path section that directly corresponds to the mapping that activated thisrequest. This path starts with a / character. Path info is the part of the request path that is not part of thecontext path or the servlet path

309. What is URNUniform resource name. A unique identifier that identifies an entity but doesn't tell where it is located. Asystem can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Weblocation to change, while still allowing the entity to be found.

310. What is user data constraint

Indicates how data between a client and a Web container should be protected. The protection can be theprevention of tampering with the data or prevention of eavesdropping on the data.

311. What is user (security)

An individual (or application program) identity that has been authenticated. A user can have a set of rolesassociated with that identity, which entitles the user to access all resources protected by those roles.

312. What is user (security)A valid XML document, in addition to being well formed, conforms to all the constraints imposed by a DTD. Itdoes not contain any tags that are not permitted by the DTD, and the order of the tags conforms to the DTD'sspecifications.

313. What is validating parser

A parser that ensures that an XML document is valid in addition to being well formed. See also parser.

314. What is value-binding expression

A JavaServer Faces EL expression that refers to a property of a backing bean. A component tag uses thisexpression to bind the associated component's value or the component instance to the bean property. If thecomponent tag refers to the property via its value attribute, then the component's value is bound to theproperty. If the component tag refers to the property via its binding attribute then the component itself isbound to the property.

315. What is virtual host

Multiple hosts plus domain names mapped to a single IP address.

316. What is W3C

World Wide Web Consortium. The international body that governs Internet standards. Its Web site ishttp://www.w3.org/.

317. What is WAR file

Web application archive file. A JAR archive that contains a Web module.

318. What is warning

A SAX parser warning is generated when the document's DTD contains duplicate definitions and in similarsituations that are not necessarily an error but which the document author might like to know about, becausethey could be. See also fatal error, error.

319. What is Web application

An application written for the Internet, including those built with Java technologies such as JavaServer Pagesand servlets, as well as those built with non-Java technologies such as CGI and Perl.

320. What is Web application, distributable

A Web application that uses J2EE technology written so that it can be deployed in a Web container distributedacross multiple Java virtual machines running on the same host or different hosts. The deployment descriptorfor such an application uses the distributable element.

321. What is Web component

A component that provides services in response to requests; either a servlet or a JSP page.

322. What is Web container

A container that implements the Web component contract of the J2EE architecture. This contract specifies aruntime environment for Web components that includes security, concurrency, life-cycle management,

96

Page 97: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 97/225

transaction, deployment, and other services. A Web container provides the same services as a JSP container aswell as a federated view of the J2EE platform APIs. A Web container is provided by a Web or J2EE server.

323. What is Web container, distributed

A Web container that can run a Web application that is tagged as distributable and that executes acrossmultiple Java virtual machines running on the same host or on different hosts.

324. What is Web container provider

A vendor that supplies a Web container.325. What is Web module

A deployable unit that consists of one or more Web components, other resources, and a Web applicationdeployment descriptor contained in a hierarchy of directories and files in a standard Web application format.

326. What is Web resource

A static or dynamic object contained in a Web application that can be referenced by a URL.

327. What is Web resource collection

A list of URL patterns and HTTP methods that describe a set of Web resources to be protected.

328. What is Web server

Software that provides services to access the Internet, an intranet, or an extranet. A Web server hosts Websites, provides support for HTTP and other protocols, and executes server-side programs (such as CGI scriptsor servlets) that perform certain functions. In the J2EE architecture, a Web server provides services to a Webcontainer. For example, a Web container typically relies on a Web server to provide HTTP message handling.The J2EE architecture assumes that a Web container is hosted by a Web server from the same vendor, so itdoes not specify the contract between these two entities. A Web server can host one or more Web containers.

329. What is Web server provider

A vendor that supplies a Web server.

330. What is Web service

An application that exists in a distributed environment, such as the Internet. A Web service accepts a request,performs its function based on the request, and returns a response. The request and the response can be part

of the same operation, or they can occur separately, in which case the consumer does not need to wait for aresponse. Both the request and the response usually take the form of XML, a portable data-interchangeformat, and are delivered over a wire protocol, such as HTTP.

331. What is well-formed

An XML document that is syntactically correct. It does not have any angle brackets that are not part of tags, alltags have an ending tag or are themselves self-ending, and all tags are fully nested. Knowing that a documentis well formed makes it possible to process it. However, a well-formed document may not be valid. Todetermine that, you need a validating parser and a DTD.

332. What is Xalan

An interpreting version of XSLT.

333. What is XHTML

An XML look-alike for HTML defined by one of several XHTML DTDs. To use XHTML for everything would of 

course defeat the purpose of XML, because the idea of XML is to identify information content, and not just totell how to display it. You can reference it in a DTD, which allows you to say, for example, that the text in anelement can contain < em > and < b > tags rather than being limited to plain text.

334. What is XLink

The part of the XLL specification that is concerned with specifying links between documents.

335. What is XLL

The XML Link Language specification, consisting of XLink and XPointer.

336. What is XML

Extensible Markup Language. A markup language that allows you to define the tags (markup) needed toidentify the content, data, and text in XML documents. It differs from HTML, the markup language most oftenused to present information on the Internet. HTML has fixed tags that deal mainly with style or presentation.An XML document must undergo a transformation into a language with style tags under the control of a stylesheet before it can be presented by a browser or other presentation mechanism. Two types of style sheetsused with XML are CSS and XSL. Typically, XML is transformed into HTML for presentation. Although tags canbe defined as needed in the generation of an XML document, a document type definition (DTD) can be used todefine the elements allowed in a particular type of document. A document can be compared by using the rules

97

Page 98: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 98/225

in the DTD to determine its validity and to locate particular elements in the document. A Web servicesapplication's J2EE deployment descriptors are expressed in XML with schemas defining allowed elements.Programs for processing XML documents use SAX or DOM APIs.

337. What is XML registry

An infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral thirdparty that facilitates dynamic and loosely coupled business-to-business (B2B) interactions.

338. What is XML Schema

The W3C specification for defining the structure, content, and semantics of XML documents.

339. What is XPath

An addressing mechanism for identifying the parts of an XML document.

340. What is XPointer

The part of the XLL specification that is concerned with identifying sections of documents so that they can bereferenced in links or included in other documents.

341. What is XSL

Extensible Stylesheet Language. A standard that lets you do the following: Specify an addressing mechanism,so that you can identify the parts of an XML document that a transformation applies to (XPath). Specify tag

conversions, so that you can convert XML data into different formats (XSLT). Specify display characteristics,such page sizes, margins, and font heights and widths, as well as the flow objects on each page. Informationfills in one area of a page and then automatically flows to the next object when that area fills up. That allowsyou to wrap text around pictures, for example, or to continue a newsletter article on a different page (XSL-FO).

342. What is XSL-FO

A subcomponent of XSL used for describing font sizes, page layouts, and how information flows from one pageto another.

343. What is XSLT

XSL Transformations. An XML document that controls the transformation of an XML document into another XMLdocument or HTML. The target document often has presentation-related tags dictating how it will be renderedby a browser or other presentation mechanism. XSLT was formerly a part of XSL, which also included a taglanguage of style flow objects.

344. What is XSLTCA compiling version of XSLT.

345. What is binary entity

A general entity that contains something other than XML. By its nature, an unparsed entity contains binarydata.

346. What is component (JavaServer Faces technology)

A user interface control that outputs data to a client or allows a user to input data to a JavaServer Facesapplication.

EJB

1. What is EJBEJB stands for Enterprise JavaBean and is a widely-adopted server side component architecture for J2EE. Itenables rapid development of mission-critical application that are versatile, reusable and portable acrossmiddleware while protecting IT investment and preventing vendor lock-in.

2. What is session Facade?

Session Facade is a design pattern to access the Entity bean through local interface than accessing directly. Itincreases the performance over the network. In this case we call session bean which on turn call entity bean.

3. What is EJB role in J2EE?

EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side businesslogic for the J2EE platform.

4. What is the difference between EJB and Java beans?

EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.

5. What are the key features of the EJB technology?

98

Page 99: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 99/225

1. EJB components are server-side components written entirely in the Java programming language2. EJB components contain business logic only - no system-level programming & services, such astransactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB componentby the EJB server.3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.4. EJB components are fully portable across any EJB server and any OS.5. EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc.

6. What are the key benefits of the EJB technology?

1. Rapid application development2. Broad industry adoption3. Application portability4. Protection of IT investment

7. How many enterprise beans?

There are three kinds of enterprise beans:1. session beans,2. entity beans, and3. message-driven beans.

8. What is message-driven bean?

A message-driven bean combines features of a session bean and a Java Message Service (JMS) messagelistener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clientsto access the business logic in the EJB tier.

9. What is Entity Bean and Session Bean ?

Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence(CMP) and Bean-ManagedPersistence(BMP).Session Bean is used to represent a workflow on behalf of a client. There are two types: Stateless and Stateful.Stateless bean is the simplest bean. It doesn't maintain any conversational state with clients between methodinvocations. Stateful bean maintains state between invocations.

10. How EJB Invocation happens?

Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client.

Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. ReturnEJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request toBean (Enterprise Bean).

11. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in theHttpSession from inside an EJB?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.Thishas to be consider as passed-by-value, that means that it’s read-only in the EJB. If anything is altered frominside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The pass-by-reference canbe used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass anHttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-orienteddesign. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing thewhole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value

object (or structure) that holds all the data you need to pass back and forth between front-end/back-end.Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstractionwill be flexible enough to support it.

12. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client,does the container create a separate instance of the generated EJBHome and EJBObject classes?

The EJB container maintains an instance pool. The container uses these instances for the EJB Home referenceirrespective of the client request. while refering the EJB Object classes the container creates a separateinstance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it.Having said that, yes most of the container providers implement the pooling functionality to increase theperformance of the application server. The way it is implemented is, again, up to the implementer.

13. Can the primary key in the entity bean be a Java primitive type such as int?

The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For example, you canuse java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive).

14. Can you control when passivation occurs?

99

Page 100: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 100/225

The developer, according to the specification, cannot directly control when passivation occurs. Although forStateful Session Beans, the container cannot passivate an instance that is inside a transaction. So usingtransactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation,so the developer has control over what to do during this exercise and can implement the require optimizedlogic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimizepassivation calls. Taken from the WebLogic 6.0 DTD -The passivation-strategy can be either default ortransaction. With the default setting the container will attempt to keep a working set of beans in the cache.With the transaction setting, the container will passivate the bean after every transaction (or method call for anon-transactional invocation).

15. What is the advantage of using Entity bean for database operations, over directly using JDBC API to dodatabase operations? When would I use one over the other?

Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. Thereare two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean -Whenever the instance of the bean is created the container automatically retrieves the data from theDB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For thisthe developer needs to map the fields in the database to the variables in deployment descriptor files (whichvaries for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection,retrive values, assign them to the objects in the ejbLoad() which will be called by the container when itinstatiates a bean object. Similarly in the ejbStore() the container saves the object values back the thepersistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container.Apart from this, when you use Entity beans you dont need to worry about database transaction handling,database connection pooling etc. which are taken care by the ejb container.

16. What is EJB QL?

EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependentobjects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification.The EJB QL query language defines finder methods for entity beans with container managed persistenceand isportable across containers and persistence managers. EJB QL is used for queries of two types of findermethods: Finder methods that are defined in the home interface of an entity bean and which return entityobjects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to selectpersistent values that are maintained by the Persistence Manager or to select entity objects that are related tothe entity bean on which the query is defined.

17. Brief description about local interfaces?

EEJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI)mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This

design allowed for maximum flexibility in developing applications without consideration for the deploymentscenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are usingEJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback inmind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined fora bean during development, to allow streamlined calls to the bean if a caller is in the same container. This doesnot involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performanceof applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.

18. What are the special design care that must be taken when you work with local interfaces?

It is important to understand that the calling semantics of local interfaces are different from those of remoteinterfaces. For example, remote interfaces pass parameters using call-by-value semantics, while localinterfaces use call-by-reference. This means that in order to use local interfaces safely, application developersneed to carefully consider potential deployment scenarios up front, then decide which interfaces can be localand which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 localinterfaces are extremely useful in some situations, the long-term costs of these choices, especially whenchanging requirements and component reuse are taken into account, need to be factored into the designdecision.

19. What happens if remove( ) is never invoked on a session bean?

In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. Thenumber of beans in cache is managed by the container. In case of stateful session bean, the bean may be keptin cache till either the session times out, in which case the bean is removed or when there is a requirement formemory in which case the data is cached and the bean is sent to free pool.

20. What is the difference between Message Driven Beans and Stateless Session beans?

In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However,

message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significantways: Message-driven beans process multiple JMS messages asynchronously, rather than processing aserialized sequence of method calls. Message-driven beans have no home or remote interface, and thereforecannot be directly accessed by internal or external clients. Clients interact with message-driven beans onlyindirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with amessage-driven bean by creating bean instances and passing JMS messages to those instances as necessary.

100

Page 101: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 101/225

The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created orremoved as a result of client requests or other API calls.

22. How can I call one EJB from inside of another EJB?

EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, thenacquire an instance reference, and so forth.

23. What is an EJB Context?

EJBContext is an interface that is implemented by the container, and it is also a part of the bean-containercontract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass calledSessionContext. These EJBContext objects provide the bean class with information about its container, theclient using the bean and the bean itself. They also provide other functions. See the API docs and the spec formore details.

24. Is is possible for an EJB client to marshal an object of class java.lang.Class to an EJB?

Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtaininformation about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.

25. Is it legal to have static initializer blocks in EJB?

Although technically it is legal, static initializer blocks are used to execute some piece of code before executing

any constructor or method while instantiating a class. Static initializer blocks are also typically used to initializestatic fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including thecode in either the ejbCreate(), setSessionContext() or setEntityContext() methods.

26. Is it possible to stop the execution of a method before completion in a SessionBean?

Stopping the execution of a method inside a Session Bean is not possible without writing code inside theSession Bean. This is because you are not allowed to access Threads inside an EJB.

27. What is the default transaction attribute for an EJB?

There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer mustspecify a value for the transaction attribute for those methods having container managed transaction. InWebLogic, the default transaction attribute for EJB is SUPPORTS.

28. What is the difference between session and entity beans? When should I use one or the other?An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beansimplement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit,Account.withdraw)

29. Is there any default cache management system with Entity beans ?

In other words whether a cache of the data in database will be maintained in EJB ? - Caching data from adatabase inside the Application Server are what Entity EJB’s are used for.The ejbLoad() and ejbStore()methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactionsalso play an important role in this scenario. If data is removed from the database, via an external application -your Entity Bean can still be alive the EJB container. When the transaction commits, ejbStore() is called andthe row will not be found, and the transaction rolled back.

30. Why is ejbFindByPrimaryKey mandatory?

An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. TheejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to aSELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a newbean each time - which would mean creating duplications of persistent data and break the integrity of EJB.

31. Why do we have a remove method in both EJBHome and EJBObject?

With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it(you can provide a PrimaryKey object as a parameter to the remove method). The home version only works forentity beans. On the other hand, the Remote interface version works on an entity bean that you have alreadyinstantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform thecontainer of your loss of interest in this bean.

32. How can I call one EJB from inside of another EJB?

EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, thenacquire an instance reference, and so forth.

101

Page 102: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 102/225

33. What is the difference between a Server, a Container, and a Connector?

An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) forconcurrent client connections and manages system resources such as threads, processes, memory, databaseconnections, network connections, etc. An EJB container runs inside (or within) an EJB server, and providesdeployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB beanfrom the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean andits container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJBserver which supports the Connector architecture. See Sun’s J2EE Connectors for more in-depth information onConnectors.

34. How is persistence implemented in enterprise beans?

Persistence in EJB is taken care of in two ways, depending on how you implement your beans: containermanaged persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beansrun under takes care of the persistence of the fields you have declared to be persisted with the database - thisdeclaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as themethod you have executed is finished, the new data is persisted to the database by the container. For BMP,the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, forinstance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer tomake calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean.So, if the bean is being looked up, when the create() method is called on the Home interface, then thecontainer is responsible for calling the ejbCreate() method in the bean, which should have functionality insidefor going to the database and looking up the data.

35. What is an EJB Context?EJBContext is an interface that is implemented by the container, and it is also a part of the bean-containercontract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass calledSessionContext. These EJBContext objects provide the bean class with information about its container, theclient using the bean and the bean itself. They also provide other functions. See the API docs and the spec formore details.

36. Is method overloading allowed in EJB?

Yes you can overload methods Should synchronization primitives be used on bean methods? - No. The EJBspecification specifically states that the enterprise bean is not allowed to use thread primitives. The container isresponsible for managing concurrent access to beans at runtime.

37. Are we allowed to change the transaction isolation property in middle of a transaction?

No. You cannot change the transaction isolation level in the middle of transaction.

38. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the beanis passivated?

The specification infers that the container never serializes an instance of an Entity bean (unlike stateful sessionbeans). Thus passivation simply involves moving the bean from the ready to the pooled bin. So what happensto the contents of an instance variable is controlled by the programmer. Remember that when an entity bean ispassivated the instance gets logically disassociated from it’s remote object. Be careful here, as the functionalityof passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. Forentity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particularentity prior to reuse or for dereference.

39. What is a Message Driven Bean, what functions does a message driven bean have and how do they work incollaboration with JMS?

Message driven beans are the latest addition to the family of component bean types defined by the EJBspecification. The original bean types include session beans, which contain business logic and maintain a stateassociated with client sessions, and entity beans, which map objects to persistent data. Message driven beanswill provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean isassociated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlikeentity beans and session beans, message beans do not have home or remote interfaces. Instead, messagedriven beans are instantiated by the container as required. Like stateless session beans, message beansmaintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances.Clients send JMS messages to message beans in exactly the same manner as they would send messages toany other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the newspecification. To receive JMS messages, message driven beans implement the javax.jms.MessageListenerinterface, which defines a single onMessage() method. When a message arrives, the container ensures that amessage bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls itsonMessage method passing the client’s message as the single argument. The message bean’s implementationof this method contains the business logic required to process the message. Note that session beans and entitybeans are not allowed to function as message beans.

40. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in thesame way as RMI does across a JRMP connection?

Yes. The JDK 1.2 support the dynamic class loading. The EJB container implements the EJBHome andEJBObject classes. For every request from a unique client,

102

Page 103: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 103/225

41. Does the container create a separate instance of the generated EJBHome and EJBObject classes?

The EJB container maintains an instance pool. The container uses these instances for the EJB Home referenceirrespective of the client request. while refering the EJB Object classes the container creates a separateinstance for each client request. The instance pool maintainence is up to the implementation of the container.If the container provides one, it is available otherwise it is not mandatory for the provider to implement it.Having said that, yes most of the container providers implement the pooling functionality to increase theperformance of the application server. The way it is implemented is again up to the implementer.

42. What is the advantage of putting an Entity Bean instance from the Ready State to Pooled state

The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has been created,but has not been yet synchronized or assigned to an EJBObject. This mean that the instances do represententity beans, but they can be used only for serving Home methods (create or findBy), since those methods donot relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do nothave meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using anentity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore,in such cases, the container will, after some time, move the entity bean from the Ready State to the Pooledstate to save memory. Then, to save additional memory, the container may begin moving entity beans fromthe Pooled State to the Does Not Exist State, because even though the bean’s cache has been cleared, thebean still takes up some memory just being in the Pooled State.

43. Can a Session Bean be defined without ejbCreate() method?

The ejbCreate() methods is part of the bean’s lifecycle, so, the compiler will not return an error because thereis no ejbCreate() method. However, the J2EE spec is explicit: the home interface of a Stateless Session Beanmust have a single create() method with no arguments, while the session bean class must contain exactly oneejbCreate() method, also without arguments. Stateful Session Beans can have arguments (more than onecreate method) stateful beans can contain multiple ejbCreate() as long as they match with the home interfacedefinition. You need a reference to your EJBObject to startwith. For that Sun insists on putting a method forcreating that reference (create method in the home interface). The EJBObject does matter here. Not the actualbean.

44. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in theHttpSession from inside an EJB?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.Thishas to be consider as passed-by-value, that means that it’s read-only in the EJB. If anything is altered frominside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The pass-by-reference canbe used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass anHttpSession as a parameter to an EJB object, it is considered to be bad practice (1) in terms of object oriented

design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb’s api. Rather than passing thewhole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a valueobject (or structure) that holds all the data you need to pass back and forth between front-end/back-end.Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction willbe flexible enough to support it. (1) Core J2EE design patterns (2001)

45. Is there any way to read values from an entity bean without locking it for the rest of the transaction (e.g.read-only transactions)?

We have a key-value map bean which deadlocks during some concurrent reads. Isolation levels seem to affectthe database only, and we need to work within a transaction. - The only thing that comes to (my) mind is thatyou could write a ‘group accessor’ - a method that returns a single object containing all of your entity bean’sattributes (or all interesting attributes). This method could then be placed in a ‘Requires New’ transaction. Thisway, the current transaction would be suspended for the duration of the call to the entity bean and the entity

bean’s fetch/operate/commit cycle will be in a separate transaction and any locks should be releasedimmediately. Depending on the granularity of what you need to pull out of the map, the group accessor mightbe overkill.

46. What is the difference between a Coarse Grained Entity Bean and a Fine Grained Entity Bean?

A ‘fine grained’ entity bean is pretty much directly mapped to one relational table, in third normal form. A ‘coarse grained’ entity bean is larger and more complex, either because its attributes include values or listsfrom other tables, or because it ‘owns’ one or more sets of dependent objects. Note that the coarse grainedbean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with datacopied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Finegrained entities are generally considered a liability in large systems because they will tend to increase the loadon several of the EJB server’s subsystems (there will be more objects exported through the distribution layer,more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.)

47. What is EJBDoclet?EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files from customJavaDoc comments tags embedded in the EJB source file.

48. Are enterprise beans allowed to use Thread.sleep()?

103

Page 104: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 104/225

Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. Toavoid conflicts with these services, enterprise beans are restricted from performing certain operations:Managing or synchronizing threads

49. Is it possible to write two EJB's that share the same Remote and Home interfaces, and have different beanclasses? if so, what are the advantages/disadvantages?

It's certainly possible. In fact, there's an example that ships with the Inprise Application Server of an Accountinterface with separate implementations for CheckingAccount and SavingsAccount, one of which was CMP andone of which was BMP.

50. Is it possible to specify multiple JNDI names when deploying an EJB?

No. To achieve this you have to deploy your EJB multiple times each specifying a different JNDI name.

51. Is there any way to force an Entity Bean to store itself to the db? I don't wanna wait for the container toupdate the db, I want to do it NOW! Is it possible?

Specify the transaction attribute of the bean as RequiresNew. Then as per section 11.6.2.4 of the EJB v 1.1spec EJB container automatically starts a new transaction before the method call. The container also performsthe commit protocol before the method result is sent to the client.

52. I am developing a BMP Entity bean. I have noticed that whenever the create method is invoked, theejbLoad() and the ejbStore() methods are also invoked. I feel that once my database insert is done, having to

do a select and update SQL queries is major overhead. is this behavior typical of all EJB containers? Is thereany way to suppress these invocations?

This is the default behaviour for EJB. The specification states that ejbLoad() will be called before everytransaction and ejbStore() after every transaction. Each Vendor has optimizations, which are proprietary forthis scenario.

53. Can an EJB send asynchronous notifications to its clients?

Asynchronous notification is a known hole in the first versions of the EJB spec. The recommended solution tothis is to use JMS, which is becoming available in J2EE-compliant servers. The other option, of course, is to useclient-side threads and polling. This is not an ideal solution, but it's workable for many scenarios.

54. How can I access EJB from ASP?

You can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COM Bridge 1.0,currently downloadable from http://developer.java.sun.com/developer/earlyAccess/j2eecas/

55. Is there a guarantee of uniqueness for entity beans?

There is no such guarantee. The server (or servers) can instantiate as many instances of the same underlyingEntity Bean (with the same PK) as it wants. However, each instance is guaranteed to have up-to-date datavalues, and be transactionally consistent, so uniqueness is not required. This allows the server to scale thesystem to support multiple threads, multiple concurrent requests, and multiple hosts.

56. How do the six transaction attributes map to isolation levels like "dirty read"? Will an attribute like"Required" lock out other readers until I'm finished updating?

The Transaction Attributes in EJB do not map to the Transaction Isolation levels used in JDBC. This is acommon misconception. Transaction Attributes specify to the container when a Transaction should be started,suspended(paused) and committed between method invocations on Enterprise JavaBeans. For more detailsand a summary of Transaction Attributes refer to section 11.6 of the EJB 1.1 specification.

57. I have created a remote reference to an EJB in FirstServlet. Can I put the reference in a servlet session anduse that in SecondServlet?

Yes. The EJB client (in this case your servlet) acquires a remote reference to an EJB from the Home Interface;that reference is serializable and can be passed from servlet to servlet. If it is a session bean, then the EJBserver will consider your web client's servlet session to correspond to a single EJB session, which is usually(but not always) what you want.

58. Can the primary key in the entity bean be a Java primitive type such as int?

The primary key can't be a primitive type--use the primitive wrapper classes, instead. For example, you canuse java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive)

59. What's new in the EJB 2.0 specification?

Following are the main features supported in EJB 2.0 * Integration of EJB with JMS * Message Driven Beans *Implement additional Business methods in Home interface which are not specific for bean instance. * EJB QL.

60. What is the need of Remote and Home interface. Why cant it be in one?

In a few words, I would say that the main reason is because there is a clear division of roles andresponsabilities between the two interfaces.

104

Page 105: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 105/225

The home interface is your way to communicate with the container, that is who is responsable of creating,locating even removing one or more beans.The remote interface is your link to the bean, that will allow you to remotely access to all its methods andmembers. As you can see there are two distinct elements (the container and the beans) and you need twodifferent interfaces for accessing to both of them.

61. What is the difference between Java Beans and EJB?s?

Java Beans are client-side objects and EJBs are server side object, and they have completely differentdevelopment, lifecycle, purpose.

62. Question With regard to Entity Beans, what happens if both my EJB Server and Database crash, what willhappen to unsaved changes? Is there any transactional log file used?

Actually, if your EJB server crashes, you will not even be able to make a connection to the server to perform abean lookup, as the server will no longer be listening on the port for incoming JNDI lookup requests. You willlose any data that wasn't committed prior to the crash. This is where you should start looking into clusteringyour EJB server.Another AnswerHi, Any unsaved and uncommited changes are lost the moment your EJB Server crashes. If your database alsocrashes, then all the saved changes are also lost unless you have some backup or some recovery mechanismto retrieve the data. So consider database replication and EJB Clustering for such scenarios, though theoccurence of such a thing is very very rare. Thx, Uma All databse have the concept of log files(for exampeoracle have redo log files concept). So if data bases crashes then on starting up they fill look up the log files toperform all pending jobs. But is EJB crashes, It depend upon the container how frequenlty it passivates or how

frequesntly it refreshes the data with Database.

63. Question Can you control when passivation occurs?

The developer, according to the specification, cannot directly control when passivation occurs. Although forStateful Session Beans, the container cannot passivate an instance that is inside a transaction. So usingtransactions can be a a strategy to control passivation.The ejbPassivate() method is called during passivation, so the developer has control over what to do duringthis exercise and can implement the require optimized logic.Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivationcalls. Taken from the WebLogic 6.0 DTD -"The passivation-strategy can be either "default" or "transaction". With the default setting the container willattempt to keep a working set of beans in the cache. With the "transaction" setting, the container will passivatethe bean after every transaction (or method call for a non-transactional invocation)."

63. Does EJB 1.1 support mandate the support for RMI-IIOP ? What is the meaning of "the client APImust support the Java RMI-IIOP programming model for portability, but the underlying protocol can beanything" ?

EJB1.1 does mandate the support of RMI-IIOP.OK, to answer the second question:There are 2 types of implementations that an EJB Server might provide: CORBA-based EJB Servers andProprietry EJB Servers. Both support the RMI-IIOP API but how that API is implemented is a different story.(NB: By API we mean the interface provided to the client by the stub or proxy).A CORBA-based EJB Server actually implements its EJB Objects as CORBA Objects (it therefore encorporatesan ORB and this means that EJB's can be contacted by CORBA clients (as well as RMI-IIOP clients)A proprietry EJB still implements the RMI-IIOP API (in the client's stub) but the underlying protocol can beanything. Therefore your EJB's CANNOT be contacted by CORBA clients. The difference is that in both cases,your clients see the same API (hence, your client portability) BUT how the stubs communicate with the serveris different.

63. The EJB specification says that we cannot use Bean Managed Transaction in Entity Beans. Why?The short, practical answer is... because it makes your entity beans useless as a reusable component. Also,transaction management is best left to the application server - that's what they're there for. It's all aboutatomic operations on your data. If an operation updates more than one entity then you want the whole thingto succeed or the whole thing to fail, nothing in between. If you put commits in the entity beans then it's verydifficult to rollback if an error occurs at some point late in the operation.

64. Can I invoke Runtime.gc() in an EJB?

You shouldn't.What will happen depends on the implementation, but the call will most likely be ignored. You should leavesystem level management like garbage collection for the container to deal with. After all, that's part of thebenefit of using EJBs, you don't have to manage resources yourself.

65. What is clustering? What are the different algorithms used for clustering?Clustering is grouping machines together to transparantly provide enterprise services.The client does not nowthe difference between approaching one server or approaching a cluster of servers.Clusters provide twobenefits: scalability and high availability. Further information can be found in the JavaWorld article J2EEClustering.

105

Page 106: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 106/225

66. What is the advantage of using Entity bean for database operations, over directly using JDBC API to dodatabase operations? When would I use one over the other?

Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. Thereare two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean -Whenever the instance of the bean is created the container automatically retrieves the data from theDB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For thisthe developer needs to map the fields in the database to the variables in deployment descriptor files (whichvaries for each vendor).In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign

them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object.Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad andejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entitybeans you dont need to worry about database transaction handling, database connection pooling etc. which aretaken care by the ejb container. But in case of JDBC you have to explicitly do the above features. what sureshtold is exactly perfect. ofcourse, this comes under the database transations, but i want to add this. the greatthing about the entity beans of container managed, whenever the connection is failed during the transactionprocessing, the database consistancy is mantained automatically. the container writes the data stored atpersistant storage of the entity beans to the database again to provide the database consistancy. where as in

 jdbc api, we, developers has to do manually.

67. What is the role of serialization in EJB?

A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You're invokingmethods remotely from JVM space 'A' on objects which are in JVM space 'B' -- possibly running on anothermachine on the network. To make this happen, all arguments of each method call must have their currentstate plucked out of JVM 'A' memory, flattened into a byte stream which can be sent over a TCP/IP networkconnection, and then deserialized for reincarnation on the other end in JVM 'B' where the actual method calltakes place.If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that allEJB methods arguments and return values must be serializable. The easiest way to do this is to make sure allyour classes implement java.io.Serializable.

68. Is is possible for an EJB client to marshall an object of class java.lang.Class to an EJB?

Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtaininformation about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language.

69. Is there any default cache management system with Entity beans ? In other words whether a cache of thedata in database will be maintained in EJB ?

Caching data from a database inside the Application Server are what Entity EJB's are used for.The ejbLoad()and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database).Transactions also play an important role in this scenario. If data is removed from the database, via an externalapplication - your Entity Bean can still be "alive" the EJB container. When the transaction commits, ejbStore()is called and the row will not be found, and the transcation rolled back.

70. Question Are we allowed to change the transaction isolation property in middle of a transaction?

No. You cannot change the transaction isolation level in the middle of transaction.

71. Question For Entity Beans, What happens to an instance field not mapped to any persistent storage,whenthe bean is passivated?

The specification infers that the container never serializes an instance of an Entity bean (unlike stateful sessionbeans). Thus passivation simply involves moving the bean from the "ready" to the "pooled" bin. So what

happens to the contents of an instance variable is controlled by the programmer. Remember that when anentity bean is passivated the instance gets logically disassociated from it's remote object.Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entitybeans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is beingdisassociated with a particular entity prior to reuse or for dereferenc.

72. Question What is a Message Driven Bean, What functions does a message driven bean have andhow do they work in collaboration with JMS?

Message driven beans are the latest addition to the family of component bean types defined by the EJBspecification. The original bean types include session beans, which contain business logic and maintain a stateassociated with client sessions, and entity beans, which map objects to persistent data.Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers.A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients orother beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces.Instead, message driven beans are instantiated by the container as required. Like stateless session beans,message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances.Clients send JMS messages to message beans in exactly the same manner as they would send messages toany other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the newspecification.To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, whichdefines a single "onMessage()" method.

106

Page 107: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 107/225

When a message arrives, the container ensures that a message bean corresponding to the messagetopic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client's messageas the single argument. The message bean's implementation of this method contains the business logicrequired to process the message. Note that session beans and entity beans are not allowed to function asmessage beans.

73. What is the advantage of puttting an Entity Bean instance from the "Ready State" to "Pooled state"?

The idea of the "Pooled State" is to allow a container to maintain a pool of entity beans that has been created,but has not been yet "synchronized" or assigned to an EJBObject. This mean that the instances do represententity beans, but they can be used only for serving Home methods (create or findBy), since those methods donot relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do nothave meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using anentity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore,in such cases, the container will, after some time, move the entity bean from the "Ready State" to the "Pooledstate" to save memory. Then, to save additional memory, the container may begin moving entity beans fromthe "Pooled State" to the "Does Not Exist State", because even though the bean's cache has been cleared, thebean still takes up some memory just being in the "Pooled State".

74. What is the difference between a "Coarse Grained" Entity Bean and a "Fine Grained" Entity Bean?

A 'fine grained' entity bean is pretty much directly mapped to one relational table, in third normal form. A'coarse grained' entity bean is larger and more complex, either because its attributes include values or listsfrom other tables, or because it 'owns' one or more sets of dependent objects. Note that the coarse grainedbean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data

copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc.Fine grained entities are generally considered a liability in large systems because they will tend to increase theload on several of the EJB server's subsystems (there will be more objects exported through the distributionlayer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory,etc.) The other side of the coin is that the 1.1 spec doesn't mandate CMP Error! No index entries found.supportfor dependent objects (or even indicate how they should be supported), which makes it more difficult to docoarse grained objects with CMP. The EJB 2.0 specification improves this in a huge way.

EJB Interview Questions only

1. When we can do transaction management and persistence management using JSP, servlets using JDBC whydo we require EJB?

2. Since we don't implement the remote interface in our EJB bean, what happens if we dont implement any of the methods from the interface?

3. How can we force the EJB bean to implement all the methods of the remote interface at compile time itself?

4. Explain the packaging structure of an EJB application?

5. What are the different containers available in a typical J2EE application server?

6. What are POJOs(Plain Old Java Objects)? Where do we use them

7. Given a scenario where we need to write the application from UI(JSPs to EJBs including Entity beans), give adetailed Work flow as to how will you design the application?

8. Give some parameters to choose between a Stateless session bean EJB to a Stateful Session Bean EJB?

9. Give some parameters to choose between session beansand Entity Bean?

10. Give some parameters to choose between a BMP bean to a CMP Bean?

STRUTS

1. What is Struts?

Struts is a web page development framework and an open source software that helps developers build webapplications quickly and easily. Struts combines Java Servlets, Java Server Pages, custom tags, and messageresources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams,independent developers, and everyone between.

2. How is the MVC design pattern used in Struts framework?

In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegatesrequests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapterbetween the request and the Model. The Model represents, or encapsulates, an application's business logic orstate. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding

can be determined by consulting a set of mappings, usually loaded from a database or configuration file. Thisprovides a loose coupling between the View and Model, which can make an application significantly easier tocreate and maintain.Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a JSPpage and presentation components; Model --- System state and a business logic JavaBeans.

107

Page 108: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 108/225

3. Who makes the Struts?

Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project, like Tomcat, Ant andVelocity.

4. Why it called Struts?

Because the designers want to remind us of the invisible underpinnings that hold up our houses, buildings,bridges, and ourselves when we are on stilts. This excellent description of Struts reflect the role the Strutsplays in developing web applications.

5. Do we need to pay the Struts if being used in commercial purpose?

No. Struts is available for commercial use at no charge under the Apache Software License. You can alsointegrate the Struts components into your own framework just as if they were writtern in house without anyred tape, fees, or other hassles.

6. What are the core classes of Struts?

Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.

7. What is the design role played by Struts?

The role played by Structs is controller in Model/View/Controller(MVC) style. The View is played by JSP andModel is played by JDBC or generic data source classes. The Struts controller is a set of programmablecomponents that allow developers to define exactly how the application interacts with the user.

8. How Struts control data flow?

Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keepcontrol-flow decisions out of presentation layer.

9. What configuration files are used in Struts?

ApplicationResources.propertiesstruts-config.xmlThese two files are used to bridge the gap between the Controller and the Model.

10. What helpers in the form of JSP pages are provided in Struts framework?

--struts-html.tld

--struts-bean.tld--struts-logic.tld

11. Is Struts efficient?

• The Struts is not only thread-safe but thread-dependent(instantiates each Action once and allowsother requests to be threaded through the original object.

• ActionForm beans minimize subclass code and shorten subclass hierarchies

• The Struts tag libraries provide general-purpose functionality

• The Struts components are reusable by the application

• The Struts localization strategies reduce the need for redundant JSPs

• The Struts is designed with an open architecture--subclass available

• The Struts is lightweight (5 core packages, 5 tag libraries)

• The Struts is open source and well documented (code to be examined easily)• The Struts is model neutral

12. How you will enable front-end validation based on the xml in validation.xml?

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

13. What is ActionServlet?

The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta StrutsFramework this class plays the role of controller. All the requests to the server goes through the controller.Controller is responsible for handling all the requests.

14. How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Message Resources Definitions file are simple .properties files and these files contains the messages that canbe used in the struts project. Message Resources Definitions files can be added to the struts-config.xml filethrough < message-resources / > tag. Example: < message-resources parameter= MessageResources / >

108

Page 109: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 109/225

15. What is Action Class?

The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class isto translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwritethe execute() method. In the Action Class all the database/business processing are done. It is advisable toperform all the database related stuffs in the Action Class. The ActionServlet (commad) passes theparameterized class to Action Form using the execute() method. The return type of the execute method isActionForward which is used by the Struts Framework to

forward the request to the file as per the value of the returned ActionForward object.

16. Write code of any Action Class?

Here is the code of Action Class that returns the ActionForward object.import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;

public class TestAction extends Action{

public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception

{return mapping.findForward(\"testAction\");

}}

17. What is ActionForm?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains thesession state for web application and the ActionForm object is automatically populated on the server side withdata entered from a form on the client side.

18. What is Struts Validator Framework?Struts Framework provides the functionality to validate the form data. It can be use to validate the data on theusers browser as well as on the server side. Struts Framework emits the java scripts and it can be usedvalidate the form data on the client browser. Server side validation of form can be accomplished by subclassing your From Bean with DynaValidatorForm class. The Validator framework was developed by DavidWinterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons projectand it can be used with or without Struts. The Validator framework comes integrated with the StrutsFramework and can be used without doing any extra settings.

19. Give the Details of XML files used in Validator Framework?

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. Thevalidator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. todefine the form specific validations. The validation.xml defines the validations applied to a form bean. How youwill display validation fail errors on jsp page? - The following tag displays all the errors: < html:errors/ >

20. Why do we need Struts?

Java technologies give developers a serious boost when creating and maintaining applications to meet thedemands of today's public Web sites and enterprise intranets. Struts combines Java Servlets, JavaServerPages, custom tags, and message resources into a unified framework. The end result is a cooperative,synergistic platform, suitable for development teams, independent developers, and everyone in between.

21. How does Struts work?

Java Servlets are designed to handle requests made by Web browsers. Java ServerPages are designed tocreate dynamic Web pages that can turn billboard sites into live applications. Struts uses a special Servlet as aswitchboard to route requests from Web browsers to the appropriate ServerPage. This makes Web applicationsmuch easier to design, create, and maintain.

22. Is Struts compatible with other Java technologies?Yes. Struts is committed to supporting industry standards. Struts acts as an integrator of Java technologies sothat they can be used in the "real world".

23. Who wrote Struts?

109

Page 110: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 110/225

There are several active committers to the Struts project, working cooperatively from around the globe.Dozens of individual developers and committers contributed to the Struts 1.x codebase. All interested Javadevelopers are invited to contribute to the project. Struts is a Apache Software Foundation project, with themission to "provide secure, enterprise-grade server solutions based on the Java Platform that are developed inan open and cooperative fashion".Struts was created by Craig R. McClanahan and donated to The Apache Software Foundation in May 2000.Craig was the primary developer of both Struts 1.x and Tomcat 4. Tomcat 4 was the basis for the officialreference implementation for a servlet 2.3 and JSP 1.2 container.Craig's current focus is as architect of the Sun Java Studio Creator (formerly Project Rave). Craig also servesas the Specification Lead for JavaServer Faces (JSR-127), and is the Web Layer Architect for the Java2Enterprise Edition (J2EE) platform as a whole.

24. Why is it called Struts?

It's a reference to struts in the architectural sense, a reminder of the nearly invisible pieces that hold upbuildings, houses, and bridges.

25. Do I have to credit Struts on my own website?

You need to credit Struts if you redistribute your own framework based on Struts for other people to use. (Seethe Apache License for details.) But you do not need to credit Struts just because your web application utilizesthe framework. It's the same situation as using the Apache HTTPD server or Tomcat. Not required if its justrunning your web site.

26. Where can I get a copy of Struts?The best place to download Struts is at struts.apache.org. The nightly builds are very stable, andrecommended as the best place to start today.

27. How do I install Struts?

To develop applications with Struts, you can usually just add the Struts JAR file to your Java developmentenvironment. You can then start using the Struts classes as part of your own application. A blank Strutsapplication (in the webapps directory, open struts-blank.war) is provided, which you can just copy to get aquick-start on your own brainchild.Since the full source code for Struts is available, we also provide complete instructions for compiling your ownStruts JAR from scratch. (This is actually easier than it looks!)Your Struts application can usually be deployed using a standard WAR file. In most cases, you simply depositthe WAR file on your application server, and it is installed automatically. If not, step-by-step installationinstructions for various servlet containers are available.

28. When do I need "struts.jar" on my classpath?

When you are compiling an application that uses the Struts classes, you must have the "struts.jar" on theclasspath your compiler sees -- it does not have to be on your CLASSPATH environment variable.Why is that an important distinction? Because if you are using a servlet container on your developmentmachine to test your application, the "struts.jar" must not be on your CLASSPATH environment variable whenrunning the container. (This is because each Web application must also have their own copy of the Strutsclasses, and the container will become confused if it is on the environment path as well.)There are several general approaches to this issue:* Use ANT for building your projects -- it can easily assemble classpaths for the compiler. (This is how Strutsitself is built, along with Tomcat and most other Java-based projects).* Use an IDE where you can configure the "class path" used for compilation independent of the CLASSPATHenvironment variable.* Use a shell script that temporarily adds struts.jar to the classpath just for compilation, for example javac

-classpath /path/to/struts.jar:$CLASSPATH $@

29. Does Struts include its own unit tests?

Struts currently has two testing environments, to reflect the fact that some things can be tested statically, andsome really need to be done in the environment of a running servlet container.For static unit tests, we use the JUnit framework. The sources for these tests are in the "src/test" hierarchy inthe source repository, and are executed via the "test.junit" target in the top-level build.xml file. Such tests arefocused on the low-level functionality of individual methods, are particularly suitable for the static methods inthe org.apache.struts.util utility classes. In the test hierarchy, there are also some "mock object" classes (inthe org.apache.struts.mock package) so that you can package up things that look like servlet API and StrutsAPI objects to pass in as arguments to such tests.Another valuable tool is Struts TestCase which provides a useful harness for Action classes that can be usedwith JUnit or Cactus.

30. If the framework doesn't do what I want, can I request that a feature be added?

First, it's important to remember that Struts is an all-volunteer project. We don't charge anyone anything touse Struts. Committers and other developers work on Struts because they need to use it with their ownapplications. If others can use it too, that's "icing on the cake". If you submit a patch for a feature that aCommitter finds useful, then that Committer may choose to volunteer his or her time to apply the patch. If you

110

Page 111: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 111/225

 just submit an idea without a patch, it is much less likely to be added (since first someone else has tovolunteer their time to write the patch).We are grateful for any patches, and we welcome new ideas, but the best way to see that something getsadded to the framework is to do as much of the work as you can, rather than rely on the "kindness of strangers". Worst case, you can apply the patch to your copy of Struts and still use the feature in your ownapplication. (Which is what open source is ~really~ all about.)

31. Where can I get help with Struts?

The Struts package comes complete with a Users Guide to introduce people to the framework and itsunderlying technologies. Various components also have their own in-depth Developers Guide, to cover moreadvanced topics. Comprehensive Javadocs are included along with the full source code. For your convenience,these are bundled together as a self-installing application. The struts-documentation.war is the same bundlethat is deployed as the Struts Web site.The Strut's mailing list is also very active, and welcomes posts from new users. Before posting a new question,be sure to consult the MAILING LIST ARCHIVE and the very excellent How To Ask Questions The Smart Way byEric Raymond. Please do be sure to turn off HTML in your email client before posting.

32. What's the difference between Struts and Turbine? What's the difference between Struts and Expresso?

If you are starting from scratch, packages like Turbine and Expresso can be very helpful since they try toprovide all of the basic services that your team is likely to need. Such services include things like datapersistence and logging.If you are not starting from scratch, and need to hook up your web application to an existing infrastructure,then "plain vanilla" Struts can be a better choice. The core Struts framework does not presuppose that you are

using a given set of data persistence, presentation, or logging tools. Anything goes =:0)Compared to other offerings, Struts endeavors to be a minimalist framework. We try leverage existingtechnologies whenever we can and provide only the missing pieces you need to combine disparate technologiesinto a coherent application. This is great when you want to select your own tools to use with Struts. But, if youprefer a more integrated infrastructure, then packages like Turbine or Expresso (which uses Struts) areperfectly good ways to go.See also* < http://www.mail-archive.com/[email protected]/msg03206.html >* < http://www.mail-archive.com/[email protected]/msg00495.html >* < http://jakarta.apache.org/velocity/ymtd/ymtd.html >

33. Why aren't the Struts tags maintained as part of the Jakarta Taglibs project?

Development of both products began about the same time. Leading up to the release of 1.0, it was thoughtbetter to continue to develop the taglibs alongside the controller. Now that 1.0 is out, the JavaServer Pages

Standard Taglib is in active development. Once work on JSTL stabilizes, the Struts taglibs will be revisited.Tags which are not linked directly to the framework may be hosted at Jakarta Taglibs instead.

34. Are the Struts tags XHTML compliant?

If you use an <html:html xhtml="true> or <html:xhtml/> element on your page, the tags will render asXHTML (since Struts 1.1).

35. Will the Struts tags support other markup languages such as WML

Struts itself is markup neutral. The original Struts taglibs are only one example of how presentation layercomponents can access the framework. The framework objects are exposed through the standard application,session, and request contexts, where any Java component in the application can make use of them.Markup extensions that use Struts are available for Velocity and XLST, among others. A new Struts tag libraryfor Java Server Faces is also in development.

For more about using WAP/WML with Struts see the article WAP up your EAserver.

36. What about JSTL and JavaServer Faces?

JSTL, the JavaServer Standard Tag Library, is a set of JSP tags that are designed to make it easier to developWeb applications. JavaServer Faces (JSF) is a specification for a new technology that promises to make iteasier to write MVC applications, both for the Web and for the desktop.The inventor of Struts, Craig McClanahan, is the specification co-lead for JavaServer Faces (JSR 127), andarchitect of the reference implemenation as well as Java Studio Creator. Both JSTL and JSF are complementaryto Struts.The mainstay of the Struts framework is the controller components, which can be used with any Javapresentation technology. As new technologies become available, it is certain that new "glue" components willalso appear to help these technologies work as well with Struts.Struts originally came bundled with a set of custom JSP tags. Today, several extensions are available to helpyou use Struts with other popular presentation technologies, like XSLT and Velocity. Likewise, extensions forJSTL and JSF are now available as well.The JSTL reference implementation is available through the Jakarta Taglibs site. A JSTL taglibs for Struts,Struts-El , is available and distributed with Struts beginning with the 1.1 release.The JSF specification and reference implementation is available through Sun's The JSF specification andreference implementation is available through Sun's Java ServerFaces page. An early-release JavaServer Facestaglib for Struts, Struts-Faces, is also in early release and available through the nightly build. The Struts Facestaglib is expected to work with any compliant JSF implementation, including MyFaces.

111

Page 112: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 112/225

37. Is there a particularly good IDE to use with Struts

Struts should work well with any development environment that you would like to use, as well as with anyprogrammers editor. The members of the Struts development team each use their own tools such as Emacs,IDEA, Eclipse, and NetBeans.

38. Why was reload removed from Struts (since 1.1)?

The problem with ReloadAction was that Struts was trying to act like a container, but it couldn't do a proper

 job of it. For example, you can't reload classes that have been modified, or (portably) add new classes to arunning web application (even if the container supported it).Meanwhile, as Struts 1.1 was being developed, work progressed on things like Tomcat's reload command viathe Manager webapp. This feature allows you to quickly reload-on-demand, complete with saving and restoringyour session). It started to make even less sense for Struts to half-implement a feature that containers areimplementing fully.A more minor point is that freezing the configuration information at application startup time allows Struts tosafely access the mapping information without bothering with synchronization. The "startup-only" strategycreates a modest but real improvement in performance for all users.So, ReloadAction is not supported since Struts 1.1 for two reasons:* It never did let you reload everything that you would really want to -- particularly changed classes -- somany people ended up having to reload the webapp anyway.* Containers are starting to offer reload-on-demand features which does the same thing as the StrutsReloadAction, only better.* Not supporting ReloadAction lets Struts avoid doing synchronization locks around all the lookups (like figuring

out which action to use, or the destination of an ActionForward) so applications can run a little faster.Of course, if someone came up with an implementation that solved these problems without creating anyothers, we would not be opposed to including a new ReloadAction.

39. What is a modular application? What does module-relative mean?

Since Struts 1.1, the framework supports multiple application modules. All applications have at least one root,or default, module. Like the root directory in a file system, the default application has no name. (Or is namedwith an empty string, depending your viewpoint.) Developing an application with only a default module is nodifferent from how applications were developed under Struts 1.0. Since Struts 1.1, you can add additionalmodules to your application, each of which can have their own configuration files, messages resources, and soforth. Each module is developed in the same way as the default module. Applications that were developed as asingle module can added to a multiple module application, and modules can promoted to a standaloneapplication without change. For more about configuring your application to support multiple modules, seeConfiguring Applications in the User Guide.But to answer the question =:0), a modular application is a Struts application that uses more than one module.Module-relative means that the URI starts at the module level, rather than at the context level, or theabsolute-URL level.* Absolute URL: http://localhost/myApplication/myModule/myAction.do* context-relative: /myModule/myAction.do* module-relative: /myAction.doThe Struts Examples application is a modular application that was assembled from several applications thatwere created independently.

40. Why are some of the class and element names counter-intuitive?

The framework grew in the telling and, as it evolved, some of the names drifted.The good thing about a nightly build, is that everything becomes available to the community as soon as it iswritten. The bad thing about a nightly build is that things like class names get locked down early and thenbecome difficult to change.

41. Why is ActionForm a base class rather than an interface?

The MVC design pattern is very simple to understand but much more difficult to live with. You just need thislittle bit of Business Logic in the View logic or you need just that little bit of View logic in the Business tier andpretty soon you have a real mess.Making ActionForm a class takes advantage of the single inheritance restriction of Java to it makes it moredifficult for people to do things that they should not do.ActionForms implemented as interfaces encourage making the property types match the underlying businesstier instead of Strings, which violates one of the primary purposes for ActionForms in the first place (the abilityto reproduce invalid input, which is a fundamental user expectation). ActionForms as an interface would alsoencourage using existing DAO objects as ActionForms by adding ‘implements ActionForm’ to the class.This violates the MVC design pattern goal of separation of the view and business logic.Since the goal of struts is to enforce this separation, it just makes more sense for Struts to own theActionForm.DynaActionForms relieve developers of maintaining simple ActionForms. For near zero maintenance, try Niall

Pemberton's LazyActionForm

42. Do ActionForms have to be true JavaBeans?

The utilities that Struts uses (Commons-BeanUtils since 1.1) require that ActionForm properties follow theJavaBean patterns for mutators and accessors (get*,set*,is*). Since Struts uses the Introspection API with the

112

Page 113: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 113/225

ActionForms, some containers may require that all the JavaBean patterns be followed, including declaring"implements Serializable" for each subclass. The safest thing is to review the JavaBean specification and followall the prescribed patterns.Since Struts 1.1, you can also use DynaActionForms and mapped-backed forms, which are not true JavaBeans.For more see ActionForm classes in the User Guide and Using Hashmaps with ActionForms in this FAQ.

43. Can I use multiple HTML form elements with the same name?

Yes. Define the element as an array and Struts will autopopulate it like any other.private String[] id= {};public String[] getId() { return this.id; }public void setItem(String id[]) {this.id = id;}And so forth

44. Can I use multiple HTML form elements with the same name?

Yes. The issue is that only one action class can be associated with a single form. So the real issue is how do Idecode multiple submit types to a single Action class. There is more than one way to achieve this functionality.

The way that is suggested by struts is right out of the javadoc for LookupDispatchAction . Basically,LookupDispatchAction is using the keys from ApplicationProperties.resources as keys to a map of actionsavailable to your Action class. It uses reflection to decode the request and invoke the proper action. It alsotakes advantage of the struts <html:submit> tags and is straight forward to implement.

You can roll your own with JavaScript events and javascript:void (document.forms["myform"].submit) on anyhtml element. This gives you control of how you want your page to look. Again you will have to decode theexpected action in the execute method of your action form if you choose this route.

45. Why doesn't the focus feature on the <html:form> tag work in every circumstance?

Unfortunately, there is some disagreement between the various browsers, and different versions of the samebrowser, as to how the focus can be set. The <html:form> tag provides a quick and easy JavaScript that willset the focus on a form for most versions of most browsers. If this feature doesn't work for you, then youshould set the focus using your own JavaScript. The focus feature is a convenient "value-add" -- not a corerequirement of the tag. If you do come up with a JavaScript that provides the final solution to this project,please post your patch to this Bugzilla ticket.

46. Why are my checkboxes not being set from ON to OFF?

A problem with a checkbox is that the browser will only include it in the request when it is checked. If it is notchecked, the HTML specification suggests that it not be sent (i.e. omitted from the request). If the value of thecheckbox is being persisted, either in a session bean or in the model, a checked box can never unchecked by aHTML form -- because the form can never send a signal to uncheck the box. The application must somehowascertain that since the element was not sent that the corresponding value is unchecked.The recommended approach for Struts applications is to use the reset method in the ActionForm to set allproperties represented by checkboxes to null or false. The checked boxes submitted by the form will then setthose properties to true. The omitted properties will remain false. Another solution is to use radio buttonsinstead, which always submit a value.It is important to note that the HTML specification recommends this same behavior whenever a control is not"successful". Any blank element in a HTML form is not guaranteed to submitted. It is therefor very important toset the default values for an ActionForm correctly, and to implement the reset method when the ActionFormmight kept in session scope.

47. Can I use JavaScript to submit a form?

You can submit a form with a link as below. BTW, the examples below assume you are in an block and'myForm' is picked up from the struts-config.xml name field of the action.<a href='javascript:void(document.forms["myForm"].submit()>My Link</a>Now the trick in the action is to decode what action you intend to perform. Since you are using JavaScript, youcould set a field value and look for it in the request or in the form.... html/javascript part ...<input type='hidden' value='myAction' /><input type='button' value='Save Meeeee'onclick='document.forms["myForm"].myAction.value="save";document.forms["myForm"].submit();' /><input type='button' value='Delete Meeeee'onclick='document.forms["myForm"].myAction.value="delete";document.forms["myForm"].submit();' />... the java part ...class MyAction extends ActionForm implements Serializable {

public ActionForward execute (ActionMapping map, ActionForm form,HttpServletRequest req, HttpServletResponse) {

String myAction = req.getParameter("myAction");

113

Page 114: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 114/225

if (myAction.equals("save") { // ... save action ...} else if (myAction.equals("delete") {

 // ... delete action ...}}}}This is just one of many ways to achieve submitting a form and decoding the intended action. Once you getused to the framework you will find other ways that make more sense for your coding style and requirements.Just remember this example is completely non-functional without JavaScript.Here is a link which utilizes the LookupDispatch action to submit forms with multiple actions without javascript:http://husted.com/struts/tips/003.html

48. How do I use JavaScript to ...

Struts is mainly a server-side technology. We bundled in some JSP tags to expose the framework componentsto your presentation page, but past that, the usual development process applies.Interactive pages require the use of JavaScript. (That's why it was invented.) If you want things popping up ordoing this when they click that, you are outside the scope of Struts and back into the web developmentmainstream.You use JavaScript with Struts the same way you use with any presentation page. Since JavaScript is a client-side technology, you can use simple relative references to your scripts. If you need to fire a JavaScript from aHTML control, the Struts HTML tags have properties for the JavaScript events.A very good JavaScript resource is Matt Kruse's site at http://www.mattkruse.com/javascript/ Do I need to

implement reset and set all my form properties to their initial values?No. You need to set checkbox properties to false if the ActionForm is being retained in session scope. This isbecause an unchecked box does not submit an attribute. Only checked boxes submit attributes. If the form isin session scope, and the checkbox was checked, there is no way to turn it back off without the reset method.Resetting the properties for other controls, or for a request scope form, is pointless. If the form is in requestscope, everything already just started at the initial value.

49. Can't I just create some of my JavaBeans in the JSP using a scriptlet?

Struts is designed to encourage a Model 2/MVC architecture. But there is nothing that prevents you from usingModel 1 techniques in your JavaServer Pages, so the answer to the question is "Yes, you can".Though, using Model 1 techniques in a Struts application does go against the grain. The approachrecommended by most Struts developers is to create and populate whatever objects the view may need in theAction, and then forward these through the request. Some objects may also be created and stored in thesession or context, depending on how they are used.

Likewise, there is nothing to prevent you from using scriptlets along with JSP tags in your pages. Though,many Struts developers report writing very complex scriplet-free applications and recommend the JSP tagapproach to others.For help with Model 1 techniques and scriptlets, you might consider joining the Javasoft JSP-interest mailinglist, where there are more people still using these approaches.

50. Can I use other beans or hashmaps with ActionForms?

Yes. There are several ways that you can use other beans or hashmaps with ActionForms.* ActionForms can have other beansor hashmaps as properties* "Value Beans" or "Data Transfer Objects" (DTOs) can be used independently of ActionForms to transfer datato the view* ActionForms can use Maps to support "dynamic" properties (since Struts 1.1)ActionForms (a.k.a. "form beans") are really just Java beans (with a few special methods) that Struts createsand puts into session or request scope for you. There is nothing preventing you from using other beans, or

including them in your form beans. Here are some examples:Collections as properties Suppose that you need to display a pulldown list of available colors on an input formin your application. You can include a string-valued colorSelected property in your ActionForm to represent theuser's selection and a colorOptions property implemented as a Collection (of strings) to store the availablecolor choices. Assuming that you have defined the getters and setters for the colorSelected and colorOptionsproperties in your orderEntryForm form bean, you can render the pulldown list using:<html:select property="colorSelected"><html:options property="colorOptions" name="orderEntryForm"/></html:select>The list will be populated using the strings in the colorOptions collection of the orderEntryForm and the valuethat the user selects will go into the colorSelected property that gets posted to the subsequent Action. Notethat we are assuming here that the colorOptions property of the orderEntryForm has already been set.See How can I prepopulate a form? for instructions on how to set form bean properties before rendering editforms that expect properties to be pre-set.Independent DTO An Action that retrieves a list of open orders (as an ArrayList of Order objects) can use a

DTO independently of any form bean to transfer search results to the view. First, the Action's execute methodperforms the search and puts the DTO into the request:ArrayList results = businessObject.executeSearch(searchParameters);request.setAttribute("searchResults",results);Then the view can iterate through the results using the "searchResults" request key to reference the DTO:` <logic:iterate id="order" name="searchResults" type="com.foo.bar.Order"><tr><td><bean:write name="order" property="orderNumber"/><td>

114

Page 115: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 115/225

<td>..other properties...</td></tr></logic:iterate>

51. Why do the Struts tags provide for so little formatting?

The Struts tags seem to provide only the most rudimentary functionality. Why is there not better support fordate formatting and advanced string handling?Three reasons:First, work started on the JSTL and we didn't want to duplicate the effort.

Second, work started on Java Server Faces, and we didn't want to duplicate that effort either.Third, in a Model 2 application, most of the formatting can be handled in the ActionForms (or in the businesstier), so all the tag has to do is spit out a string. This leads to better reuse since the same "how to format"code does not need to be repeated in every instance. You can "say it once" in a JavaBean and be done with it.Why don't the Struts taglibs offer more layout options?Since the Struts tags are open source, you can extend them to provide whatever additional formatting youmay need. If you are interested in a pre-written taglib that offers more layout options, see the struts-layouttaglib.In the same arena, there is a well regarded contributor taglib that can help you create Menus for your Strutsapplications.

52. Why does the <html:link> tag URL-encode javascript and mailto links?

The <html:link> tag is not intended for use with client-side references like those used to launch Javascripts oremail clients. The purpose of link tag is to interject the context (or module) path into the URI so that yourserver-side links are not dependent on your context (or module) name. It also encodes the link, as needed, tomaintain the client's session on the server. Neither feature applies to client-side links, so there is no reason touse the <html:link> tag. Simply markup the client-side links using the standard tag.

53. How can I scroll through list of pages like the search results in google?

Many Struts developers use the Pager from the JSPTags site.http://jsptags.com/tags/navigation/pager/

54. Why does the option tag render selected=selected instead of just selected?

Attribute minimization (that is, specifying an attribute with no value) is a place where HTML violates standardXML syntax rules. This matters a lot for people writing to browsers that support XHTML, where doing so makesthe page invalid.It's much better for Struts to use the expanded syntax, which works the same on existingbrowsers interpreting HTML, and newer browsers that expect XHTML-compliant syntax. Struts is following thebehavior recommended by the XHTML specification

55. Do I have to use JSPs with my application?

The short answer to this question is: No, you are not limited to JavaServer Pages.The longer answer is that you can use any type of presentation technology which can be returned by a webserver or Java container. The list includes but is not limited to:* JavaServer Pages,* HTML pages,* WML files,* Java servlets,* Velocity templates, and* XML/XLSTSome people even mix and match apparently unrelated technologies, like PHP, into the same web application.

56. Do ActionForms have to be true JavaBeans?

ActionForms are added to a servlet scope (session or request) as beans. What this means is that, for certainfunctionality to be available, your ActionForms will have to follow a few simple rules.First, your ActionForm bean must have a zero-arguments constructor. This is required because Struts must beable to dynamically create new instances of your form bean class, while knowing only the class name. This isnot an onerous restriction, however, because Struts will also populate your form bean's properties (from therequest parameters) for you.Second, the fields of your form bean are made available to the framework by supplying public getter and settermethods that follow the naming design patterns described in the JavaBeans Specification. For most users, thatmeans using the following idiom for each of your form bean's properties:private {type} fieldName;public {type} getFieldName() {return (this.fieldName);}

public void setFieldName({type} fieldName) {this.fieldName = fieldName;}NOTE - you MUST obey the capitalization conventions shown above for your ActionForm properties to berecognized. The property name in this example is "fieldName", and that must also be the name of the inputfield that corresponds to this property. A bean property may have a "getter" method and a "setter" method (ina form bean, it is typical to have both) whose name starts with "get" or "set", followed by the property name

115

Page 116: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 116/225

with the first character capitalized. (For boolean properties, it is also legal to use "is" instead of "get" as theprefix for the getter method.)Advanced JavaBeans users will know that you can tell the system you want to use different names for thegetter and setter methods, by using a java.beans.BeanInfo class associated with your form bean. Normally,however, it is much more convenient to follow the standard conventions.WARNING - developers might be tempted to use one of the following techniques, but any of them will causeyour property not to be recognized by the JavaBeans introspection facilities, and therefore cause yourapplications to misbehave:* Using getter and setter method names that do not match - if you have a getFoo() method for your getter,but a setBar() method for your setter, Java will not recognize these methods as referring to the same property.Instead, the language will think you have a read-only property named "foo" and a write-only property named"bar".* Using more than one setter method with the same name - The Java language lets you "overload" methods,as long as the argument types are different. For example, you could have a setStartDate(java.util.Date date)method and a setStartDate(String date) method in the same class, and the compiled code would know whichmethod to call based on the parameter type being passed. However, doing this for form bean properties willprevent Java from recognizing that you have a "startDate" property at all.There are other rules to follow if you want other features of your form beans to be exposed. These includeindexed attributes and mapped attributes. They are covered in detail in other areas of the Strutsdocumentation, in particular: indexedprops.htmlFor a complete explanation of what a JavaBean is, and everything it can do, see the JavaBeans Specification(version 1.01) at:http://java.sun.com/products/javabeans/docs/beans.101.pdf 

57. Do I have to have a separate ActionForm bean for every HTML form?This is an interesting question. As a newbie, it is a good practice to create a new ActionForm for each actionsequence. You can use DynaActionForms to help reduce the effort required, or use the code generationfacilities of your IDE.Some issues to keep in mind regarding reuse of form beans are as follows:* Validation - You might need to use different validation rules depending upon the action that is currently beingexecuted.* Persistence - Be careful that a form populated in one action is not unexpectedly reused in a different action.Multiple entries in struts-config.xml for the same ActionForm subclass can help (especially if you store yourform beans in session scope). Alternatively, storing form beans in request scope can avoid unexpectedinteractions (as well as reduce the memory footprint of your application, because no server-side objects willneed to be saved in between requests.* Checkboxes - If you do as recommended and reset your boolean properties (for fields presented ascheckboxes), and the page you are currently displaying does not have a checkbox for every boolean propertyon the form bean, the undisplayed boolean properties will always appear to have a false value.

* Workflow - The most common need for form bean reuse is workflow. Out of the box, Struts has limitedsupport for workflow, but a common pattern is to use a single form bean with all of the properties for all of thepages of a workflow. You will need a good understanding of the environment (ActionForms, Actions, etc.) priorto being able to put together a smooth workflow environment using a single form bean.As you get more comfortable, there are a few shortcuts you can take in order to reuse your ActionForm beans.Most of these shortcuts depend on how you have chosen to implement your Action / ActionForm combinations.

58. How can I prepopulate a form?The simplest way to prepopulate a form is to have an Action whose sole purpose is to populate an ActionFormand forward to the servlet or JSP to render that form back to the client. A separate Action would then be use toprocess the submitted form fields, by declaring an instance of the same form bean name.The struts-example example application that is shipped with Struts illustrates this design pattern nicely. Notethe following definitions from the struts-config.xml file:

...

<form-beans>...<-- Registration form bean --><form-bean name="registrationForm"

type="org.apache.struts.webapp.example.RegistrationForm"/>...

</form-beans>...<action-mappings>

...<-- Edit user registration --><action path="/editRegistration"

type="org.apache.struts.webapp.example.EditRegistrationAction"name="registrationForm"

scope="request"validate="false"/>

...<-- Save user registration --><action path="/saveRegistration"

type="org.apache.struts.webapp.example.SaveRegistrationAction"name="registrationForm"

input="registration"

116

Page 117: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 117/225

scope="request"/>...

</action-mappings> 

Note the following features of this approach:* Both the /editRegistration and /saveRegistration actions use the same form bean.* When the /editRegistration action is entered, Struts will have pre-created an empty form bean instance, andpassed it to the execute() method. The setup action is free to preconfigure the values that will be displayedwhen the form is rendered, simply by setting the corresponding form bean properties.

* When the setup action completes configuring the properties of the form bean, it should return an ActionFormthat points at the page which will display this form. If you are using the Struts JSP tag library, the actionattribute on your <html:form> tag will be set to /saveRegistration in order for the form to be submitted to theprocessing action.* Note that the setup action (/editRegistration) turns off validation on the form that is being set up. You willnormally want to include this attribute in the configuration of your setup actions, because you are not planningto actually process the results -- you simply want to take advantage of the fact that Struts will precreate aform bean instance of the correct class for you.* The processing action (/saveRegistration), on the other hand, leaves out the validate attribute, whichdefaults to true. This tells Struts to perform the validations associated with this form bean before invoking theprocessing action at all. If any validation errors have occurred, Struts will forward back to your input page(technically, it forwards back to an ActionForward named "registration" in this case, because the examplewebapp uses the inputForward attribute in the element -- see the documentation describing struts-config.xmlfor more information) instead of calling your processing action.

59. Can I have an Action without a form?

Yes. If your Action does not need any data and it doesnot need to make any data available to the view orcontroller component that it forwards to, it doesn't needa form. A good example of an Action with no ActionForm isthe LogoffAction in the struts example application:

<action path="/logoff"type="org.apache.struts.webapp.example.LogoffAction">

<forward name="success" path="/index.jsp"/></action>

This action needs no data other than the user's session, which

it can get from the Request, and it doesn't need to prepare anyview elements for display, so it does not need a form.

However, you cannot use the <html:form> tag withoutan ActionForm. Even if you want to use the <html:form>tag with a simple Action that does not require input,the tag will expect you to use some type of ActionForm,even if it is an empty subclass without any properties.

60. Can you give me a simple example of using the requiredif Validator rule?

First off, there's an even newer Validator rule calledvalidwhen, which is almost certainly what you want to use,since it is much easier and more powerful.It will be available in the first release after 1.1 ships.

The example shown below could be coded with validwhen as:

<form name="medicalStatusForm">

<fieldproperty="pregnancyTest" depends="validwhen">

<arg0 key="medicalStatusForm.pregnancyTest.label"/><var><var-name>test</var-name><var-value>((((sex == 'm') OR (sex == 'M'))AND (*this* == null)) OR (*this* != null))</test>

</var></field>

Let's assume you have a medical information form

with three fields,sex, pregnancyTest, and testResult. If sex is 'f' or 'F',pregnancyTest is required. If pregnancyTest is not blank,testResult is required. The entry in your validation.xmlfile would look like this:

<form name="medicalStatusForm">

117

Page 118: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 118/225

<fieldproperty="pregnancyTest" depends="requiredif">

<arg0 key="medicalStatusForm.pregnancyTest.label"/><var><var-name>field[0]</var-name><var-value>sex</var-value>

</var><var><var-name>fieldTest[0]</var-name><var-value>EQUAL</var-value>

</var><var><var-name>fieldValue[0]</var-name><var-value>F</var-value>

</var><var><var-name>field[1]</var-name><var-value>sex</var-value>

</var><var><var-name>fieldTest[1]</var-name><var-value>EQUAL</var-value>

</var><var>

<var-name>fieldValue[1]</var-name><var-value>f</var-value>

</var><var><var-name>fieldJoin</var-name><var-value>OR</var-value>

</var></field>

<fieldproperty="testResult" depends="requiredif">

<arg0 key="medicalStatusForm.testResult.label"/><var><var-name>field[0]</var-name><var-value>pregnancyTest</var-value>

</var><var><var-name>fieldTest[0]</var-name><var-value>NOTNULL</var-value>

</var></field></form>

61. When is the best time to validate input?

This is an excellent question. Let's step back a second and think about a typical mid to large size application. If we start from the back end and work toward the view we have:1) Database: Most modern databases are going to validate for required fields, duplicate records, securityconstraints, etc.2) Business Logic: Here you are going to check for valid data relationships and things that make sense for theparticular problem you are triing to solve.... This is where struts comes into the picture, by now the system should be pretty well bulletproof. What weare going to do is make validation friendlier and informative. Rember it is OK to have duplicate validations...3) ActionErrors validate(ActionMapping map, HttpServletRequest req) is where you can do your validation andfeed back to the view, information required to correct any errors. validate is run after the form has been resetand after the ActionForm properties have been set from corresponding view based input. Also remember youcan turn validation off with validate="false" in the action mapping in the struts-config.xml. This is done byreturning an ActionErrors collection with messages from your ApplicationResources.properties file.Here you have access to the request so you can see what kinds of action is being requested to fine tune yourvalidations. The <html:error> tag allows you to dump all errors on your page or a particular error associatedwith a particular property. The input attribute of the struts-config.xml action allows you to send validationerrors to a particular jsp / html / tile page.4) You can have the system perform low level validations and client side feedback using a ValidatorForm or itsderivatives. This will generate javascript and give instant feedback to the user for simple data entry errors. Youcode your validations in the validator-rules.xml file. A working knowledge of regular expressions is necessaryto use this feature effectively.

61. How can I avoid validating a form before data is entered?The simplest way is to have two actions. The first one has the job of setting the form data, i.e. a blankregistration screen. The second action in our writes the registration data to the database. Struts would takecare of invoking the validation and returning the user to the correct screen if validation was not complete.The EditRegistration action in the struts example application illustrates this:< action path="/editRegistration">

118

Page 119: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 119/225

type="org.apache.struts.webapp.example.EditRegistrationAction"attribute="registrationForm"scope="request"validate="false"><forward name="success path="/registration.jsp"/></action>When the /editRegistration action is invoked, a registrationForm is created and added to the request, but itsvalidate method is not called. The default value of the validate attribute is true, so if you do not want an actionto trigger form validation, you need to remember to add this attribute and set it to false.

62. How can I create a wizard workflow?The basic idea is a series of actions with next, back, cancel and finish actions with a common bean. Using aLookupDispatchAction is reccomended as it fits the design pattern well and can be internationalized easily.Since the bean is shared, each choice made will add data to the wizards base of information. A sample of struts-config.xml follows:

< form-beans><form-bean name="MyWizard"

type="forms.MyWizard" /></form-beans>

<!-- the first screen of the wizard (next action only available) --><!-- no validation, since the finish action is not available -->

<actions><action path="/mywizard1"

type="actions.MyWizard"name="MyWizard"validate="false"input="/WEB-INF/jsp/mywizard1.jsp">

<forward name="next"path="/WEB-INF/jsp/mywizard2.jsp" />

<forward name="cancel"path="/WEB-INF/jsp/mywizardcancel.jsp" />

</action>

<!-- the second screen of the wizard (back, next and finish) --><!-- since finish action is available, bean should validated, note

validation should not necessarily validate if back action requested, youmight delay validation or do conditional validation -->

<action path="/mywizard2"

type="actions.MyWizard"name="MyWizard"validate="true"input="/WEB-INF/jsp/mywizard2.jsp">

<forward name="back"path="/WEB-INF/jsp/mywizard1.jsp" />

<forward name="next"path="/WEB-INF/jsp/mywizard3.jsp" />

<forward name="finish"path="/WEB-INF/jsp/mywizarddone.jsp" />

<forward name="cancel"path="/WEB-INF/jsp/mywizardcancel.jsp" />

</action>

<!-- the last screen of the wizard (back, finish and cancel only) -->

<action path="/mywizard3"type="actions.MyWizard"name="MyWizard"validate="true"input="/WEB-INF/jsp/mywizard3.jsp">

<forward name="back"path="/WEB-INF/jsp/mywizard2.jsp" />

<forward name="finish"path="/WEB-INF/jsp/mywizarddone.jsp" />

<forward name="cancel"path="/WEB-INF/jsp/mywizardcancel.jsp" />

</action> 

The pieces of the wizard are as follows:forms.MyWizard.java - the form bean holding the information required

actions.MyWizard.java - the actions of the wizard, note the use of LookupDispatchAction allows for one actionclass with several methods. All the real work will be done in the 'finish' method.mywizard[x].jsp - the data collection jsp'smywizarddone.jsp - the 'success' pagemywizardcancel.jsp - the 'cancel' page

119

Page 120: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 120/225

62. How can I 'chain' Actions?

Chaining actions can be done by simply using theproper mapping in your forward entries in the struts-config.xml file.Assume you had the following two classes:

/* com/AAction.java */...

public class AAction extends Action{

public ActionForwardexecute(ActionMapping mapping,

ActionForm form,HttpServletRequest request,HttpServletResponse response) throws

Exception{

// Do something

return mapping.findForward("success");}

 /* com/BAction.java */...

public class BAction extends Action{

public ActionForwardexecute(ActionMapping mapping,

ActionForm form,HttpServletRequest request,HttpServletResponse response) throws

Exception{

// Do something else

return mapping.findForward("success");}

Then you can chain together these two actions withthe Struts configuration as shown in the following excerpt:

...<action-mappings type="org.apache.struts.action.ActionMapping">

<action path="/A"type="com.AAction"validate="false">

<forward name="success" path="/B.do" /></action><action path="/B"

type="com.BAction"scope="session"validate="false">

<forward name="success" path="/result.jsp" /></action>

</action-mappings>...

 

Here we are assuming you are using a suffix-based (.do) servlet mapping, which is recommended sincemodule support requires it. When you send your browser to the web application and name the action A.do (i.e.http://localhost:8080/app/A.do) it will execute AAction.execute(), which will then forward to the "success"mapping.This causes the execution of BAction.execute() since the entry for "success" in the configuration file uses the.do suffix.Of course it is also possible to chain actions programmatically, but the power and ease of being able to"reroute" your web application's structure using the XML configuration file is much easier to maintain.As a rule, chaining Actions is not recommended. If your business classes are properly factored, you should beable to call whatever methods you need from any Action, without splicing them together into a cybernetic RubeGoldberg device.

120

Page 121: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 121/225

If you must chain Actions, be aware of the following: calling the second Action from the first Action has thesame effect as calling the second Action from scratch. If both of your Actions change the properties of aformbean, the changes made by the first Action will be lost because Struts calls the reset() method on theformbean when the second Action is called.

63. struts GenericDataSource Just a general question - I'm building an application that will run stand-alone, not in an application server. I need to manage some database connections. Is the strutsGenericDataSource a good candidate to do this for me? I basicly just need a connection pool from where I canget connections and then return them to optimize performance.If this struts class is not a good candidate, can someone recommend a similar pool-manager that is lean andmean and easy to use?

Answer 1The Struts 1.0 GenericDataSource is not a good candidate for a production server. In Struts 1.1, the CommonsDBCP is used istead, which is a good candidate for a production server. (You can also use the DBCP in Struts1.0 by specifying the type and including the Commons JARs.)Another popular choice is Poolman. It's not under active development, but I believe you can still download itfrom SourceForge. Poolman is also very easy to use outside of Struts.Many containers also offer support for connection pools. The one that ships with Resin is quite good. The laterversions of Tomcat bundle the Commons DBCP.Regardless of what pool you use, a good practice is to hide it behind some type of adaptor class of your own(often a singleton), to make it easy to change later. So your classes call your adaptor, and your adaptor callswhichever pool you are using.A neat and often-overlooked aspect of the Struts DataSource manager is that it supports loading multipleconnection pools and giving each a name. So you might have one pool for internal use and another for publicuse. This way, the public connections can't swap your administrative access to the application. Each pool couldalso have its own login, and therefore different rights to the underlying database.

Answer 2

int i=1;

with Struts 1.0 and jdbc i'am use GenericDataSourcenot in struts-xml, but in Client.properties

my Client.propertiesinstanceBd=oraIDuserPasswd=xxx/yyyymaxCount=20

minCount=19port=1521driver=oracle.jdbc.driver.OracleDriverurl=jdbc:oracle:thin:@serverName:port:instanceBd

then, on my code i have init (struts 1.0 or struts 1.1):

GenericDataSource ng = new GenericDataSource ();

ng.setUser (mprop.getUserBd());ng.setPassword (mprop.getPasswdBd());ng.setUrl (mprop.getUrl());ng.setDriverClass(mprop.getDriverClass());

ng.setMaxCount(mprop.getMaxCount());ng.setMinCount (mprop.getMinCount());

ng.setDescription("jdbc OracleDriver");ng.setAutoCommit(true);try { ng.open(); } catch (java.sql.SQLException e) {

}

in business logic (or pool) :Connect cn = ng.getConnection();

it's work.

with struts 1.1 , struts-legacy.jar is necessy for this codes.

it's work. 

64. Dynamic pages using strutsIs it possible to create the elements of a page(jsp) dynamically based on the results of a data base query,when using struts framework?

If you are talking about rendering a report, then sure. The Action iteracts with the business layer/data accessobjects to acquire the data, and then passes it to the presentation page bundled up as a JavaBean or acollection of JavaBeans. The JSP tags (and other systems) all use reflection, so you can use whatever JavaBean

121

Page 122: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 122/225

you like.If you are talking about creating a dynamic data-entry form, then "not so much".Struts 1.1 supports map-backed ActionForms, but the page still needs to know what input fields are going tobe needed. For a truly dynamic input form, I guess the key would be some type of tag that took a map andthen generated a column of input fields. (Wouldn't work for everyone, since a lot of forms must be designed

 just so.) For extra credit, the entry names could (optionally) be resource keys that were used to find the labeltext.Text fields would be easy. Others would need some type of JavaBean with properties to tell the tag what tooutput. A bit of work, but obviously doable.Of course, you'd probably want to validate the form before passing it back to the database. I imagine it'spossible to use the validator in a non-declarative way, but I don't know anyone whose doing that. If you can doa db query to get the information about the form, I imagine you could also do a query to get the informationabout validations for the form. It would probably be easier to write your own engine than adopt the validator.(It's not really that complicated to do.)People often ask about "dynamic input forms", but most of us just can't get our head around the use case. It'shard to understand what you do with the dynamic data when it comes back. Most application don't allow you toinput or update an arbitrary (e.g. dynamic) set of fields.

65. What's the best way to deal with migrating a large application from Struts to JSF? Is there any tool supportthat can help?

Answer: This is a complicated task depending on your Struts application. Because the two frameworks havedifferent goals, there are some challenges. Migrate your response pages first. Keep the Struts controller andplace and forward to JSF pages. Then you can configure Struts forwards to go through the Faces servlet.Consider looking at the Struts-Faces framework from Apache. See the framework chapter in JSF in Action.

66. Declarative Exception Handling

If you have developed web applications long enough, you will realize a recurring pattern emerges: when thebackend (e.g. the EJB tier) throws you an exception, you nearly always need to display an error pagecorresponding to the type of that exception. Sooner or later, you will come up with a mechanism to use alookup table (e.g. an HashMap) to lookup an error page from the exception class.Struts 1.1 now provides a similar but more powerful mechanism to declare exception handling. In Struts 1.1,you can declare in the struts-config.xml the associations between an exception class and an exception handler.Using the default exception handler included in Struts, you can also specify the path of the error pages. Withthis information, Struts will automatically forward to the specified pages when an uncaught exception is thrownfrom an Action.Like other facilities in Struts, the exception handlers are pluggable. You can write and define your own handlerclasses if needed.

67. This is a very basic question. Can you compare the advantages and disadvantages of JSF vs. Struts.Both now, and from what you may know of futures, how and if JSF will evolve into a superior technology vs.Struts? Include how WSAD plays into the comparison if it will help differentiate the two.

This is a very popular question these days. In general, JSF is still fairly new and will take time to fully mature.However, I see JSF being able to accomplish everything Struts can, plus more. Struts evolved out of necessity.It was created by developers who were tired of coding the same logic again and again. JSF emerged both fromnecessity and competition.Struts has several benefits:* Struts is a mature and proven framework. It has been around for a few years and deployed successfully onmany projects. The WebSphere Application Server admin console is a Struts application.* Struts uses the Front Controller and Command patterns and can handle sophisticated controller logic.* In addition to the core controller function, it has many add-on benefits such as layouts with Tiles, declarativeexception handling, and internationalization.

There are disadvantages:

* Struts is very JSP-centric and takes other frameworks to adapt to other view technologies.* Although Struts has a rich tag library, it is still geared towards helping the controller aspect of developmentand does not give a sense that you are dealing with components on a page. Therefore, it is not as toolablefrom a view perspective.* Struts requires knowledge of Java™. Its goal was to aid Java developers, but not to hide Java. It does nothide details of the Java language to Web developers that well.* ActionForms are linked programmatically to the Struts framework. Therefore, to decouple the model, youneed to write transfer code or use utilities to move data from Action Forms to the Model on input.

JSF is an evolution of a few frameworks, including Struts. The creator of Struts, Craig McClanahan, is one of the JSF specification leads. Therefore, it is not by accident to see some overlap between Struts and JSF.However, one of JSF's major goals is to help J2EE Web applications to be easily developed using RAD tools. Assuch, it introduces a rich component model. JSF has several advantages:

* JSF is a specification from Sun® and will be included in future versions of the J2EE specification. All majorvendors are pledging strong support for JSF.* JSF uses the Page Controller Pattern and therefore aids in Page rich applications. Components can respond toevent from components on a page.* JSF has a well-defined request lifecycle allowing for plugability at different levels.* One powerful example of plugability is building your own render toolkit. The ability to separate the renderingportion from the controller portion of the framework allows for wonderful opportunities of extensibility.

122

Page 123: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 123/225

Component providers can write their own toolkits to render different markup languages, such as XML or WML.In addition, the render toolkit is not tied to JSP.* Because JSF has a rich component model, it favors a RAD style of development. I can now build my Webpages using drag and drop technology. In addition, JSF gives me a way to link visual components to backmodel components without breaking the layering.JSF has disadvantages:* JSF is still quite new and evolving. It will take some time to see successful deployments and wide usage. Inaddition, as vendors write components, they may not do everything you want them to.* JSF by hand is not easier than Struts. Its goal was more oriented to RAD. Those who prefer to do things byhand (for example, the vi type guy who does not like IDEs) may find Struts easier to develop.* Struts navigation may be a bit more flexible and adhere to more complex controller logic.

68. Both JSF and Struts will continue to exist for a while. The Struts community is aware of JSF and ispositioning itself to have strong support for JSF. See What about JSTL and JavaServer faces?

From a tools perspective, if you look at the support for JSF versus Struts in WebSphere Studio, the Struts toolsare focused around the controller aspects. The Web Diagram editor helps build your Struts configuration andthe wizards/editors build Struts artifacts. The JSF tools are geared towards building pages, and in essence,hide the JSF framework from you. Expect WebSphere Studio to support both frameworks for a while. As JSFmatures, expect to see some of the controller aspects in JSF to become toolable

69. Multiple Sub-applications

One of the shortcomings in Struts 1.0 is manageability of the configuration file (commonly known as struts-config.xml) when the development of the application involves a sizable team. This problem arises because a

Struts-based application must run under one controller servlet, the ActionServlet, and the ActionServlet canuse only one struts-config.xml. It is not an issue when the project is relatively small and the team consists of acouple of developers; however, when the project size becomes significant and the project involves a largenumber of developers, maintaining all the mapping information in a single file becomes increasinglyproblematic.Struts 1.1 solves this problem nicely by introducing multiple sub-applications. In Struts 1.1, each sub-application has its own struts-config.xml file. A large Struts-based application can thus be easily partitionedinto largely independent modules, i.e. sub-applications, and each sub-team can maintain their struts-config.xml independently.The sub-application scheme is a natural extension of the servlet context mapping scheme of the URI pathsused by servlet containers. According to the Servlet standard, when the servlet container receives a requestwith a URL, the servlet container will try to match the prefix of the URI path to a deployed web-application inthe container. What Struts 1.1 does is it maps the second prefix of the path to a sub-application. In effect, thisprefix mapping scheme creates another level of namespace for each sub-application. For example, for the URI,http://some-host.com/myApp/module2/editSubscription.do

 /myApp is the context path for a web-application called "myApp" and /module2 is the sub-app prefix for aStruts sub-application called "module2".

70. DynaBean and BeanUtils

Another major complaint usually heard amongst Struts 1.0 users is the extensive effort involved in writing theFormBean (a.k.a. ActionForm) classes.Struts provides two-way automatic population between HTML forms and Java objects, the FormBeans. To takeadvantage of this however, you have to write one FormBean per HTML form. (In some use cases, a FormBeancan actually be shared between multiple HTML forms. But those are specific cases.) Struts' FormBean standardfollows faithfully the verbose JavaBean standard to define and access properties. Besides, to encourage amaintainable architecture, Struts enforces a pattern such that it is very difficult to 'reuse' a model-layer object(e.g. a ValueObject from the EJB tier) as a FormBean. Combining all these factors, a developer has to spend asignificant amount of time to write tedious getters/setters for all the FormBean classes.Struts 1.1 offers an alternative, Dynamic ActionForms, which are based on DynaBeans. Simply put, DynaBeansare type-safe name-value pairs (think HashMaps) but behave like normal JavaBeans with the help of theBeanUtils library. (Both the DynaBeans and the BeanUtils library were found to be useful and generic enoughthat they have been 'promoted' into Jakarta's Commons project.) With Dynamic ActionForms, instead of codingthe tedious setters/getters, developers can declare the required properties in the struts-config.xml files. Strutswill instantiate and initialize Dynamic ActionForm objects with the appropriate metadata. From then onwards,The Dynamic ActionForm instance is treated as if it is an ordinary JavaBean by Struts and the BeanUtils library.

71. Validator

The Validator is not exactly a new feature. The Validator has been in the contrib package in the distributionsince Struts 1.0.1. Since then, part of it has now been refactored and moved into the Jakarta-Commonssubproject and renamed the Commons-Validator and the Struts specific portion is now called the Struts-Validator. However, since it is in the contrib package, people may overlook it and it is worthwhile to mention ithere.The Validator provides an extensible framework to define validation rules to validate user inputs in forms. Whatis appealing in the Validator is that it generates both the server-side validation code and the client-side

validation code (i.e. Javascript) from the same set of validation rules defined in an XML configuration file. TheValidator performs the validation based on regular-expression pattern matching. While a handful of commonlyused validators are shipped with the framework (e.g. date validator, range validator), you can always defineyour own ones to suit your need.

72. Default Sub-application

123

Page 124: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 124/225

To maintain backward compatibility, Struts 1.1 allows one default sub-application per application. The URI of the resources (i.e. JSPs, HTMLs, etc) in the default sub-application will have an empty sub-app prefix. Thismeans when an existing 1.0 application is "dropped" into Struts 1.1, theoretically, it will automatically becomethe default sub-application.

73. Direct Requests to JSPs

To take the full advantage of sub-application support, Struts 1.1 stipulates the requirement that all requestsmust flow through the controller servlet, i.e. the ActionServlet. Effectively, this means all JSPs must be frontedby Actions. Instead of allowing direct requests to any of the JSPs, all requests must go through an Action andlet the Action forward to the appropriate JSP.This is perhaps the biggest impact of migration to Struts 1.1 if you have not followed this idiom in yourapplications. This restriction is required because without going through the ActionServlet, Struts navigationtaglibs (e.g. <html:form> and <html:link>) used in the JSPs will not have the correct sub-app context to workwith

74. ActionServlet Configurations

With the introduction of sub-applications, a more flexible way is introduced to configure each sub-applicationindependently. Many of the configuration entries (e.g. resource bundle location, maximum upload file size, etc)that used to be defined in web.xml have now been moved to struts-config.xml. The original entries in web.xmlare deprecated but will still be effective.

75. Action.execute() and Action.getResources()

In Struts 1.0, request handling logic is coded in Action.perform(); however, Action.perform() throws onlyIOException and SevletException. To facilitate the new declarative exception handling , the request handlingmethod needs to throw Exception, the superclass of all the checked exceptions. Therefore, to both maintainbackward compatibility and facilitate declarative exception handling, Action.perform() is now deprecated infavour of Action.execute().You also have to be careful if you use DispatchAction in your existing applications. At the time of writing, theDispatchAction in Struts 1.1 beta has not yet been updated to use execute(). (A bug report has been filed inStruts' bug database.) Therefore, without modifying the DispatchAction class yourself, declarative exceptionhandling will not work with DispatchAction subclasses.In addition, Action.getResources() is now deprecated. Instead, you should callAction.getResources(HttpServletRequest) instead. This allows Struts to return to you the sub-applicationspecific message resources. Otherwise, the message resources for the default sub-app will be used.

76. Library Dependency

Struts 1.1 now depends on a handful of libraries from other Jakarta subprojects (e.g. Commons-Logging,Commons-Collections, etc.). Some of these libraries may cause classloading conflicts in some servletcontainers. So far, people have reported in the mailing list the classloading problem of commons-digester/jaxp1.1, and commons-logging causing deployment difficulties in Struts 1.1 applications running onWeblogic 6.0. (The problems have been corrected in Weblogic 6.1 and 7.0.)

77. Resources under WEB-INF

According to the Servlet specification, resources (e.g. JSP files) stored under WEB-INF are protected andcannot be accessed directly by the browsers. One design idiom for Struts 1.0 is to put all the JSP files underWEB-INF and front them by Actions so that clients cannot illegally access the JSPs. With the introduction of sub-application prefixes in Struts 1.1, mapping resources under WEB-INF gets complicated. Extra configurationsteps utilizing the pagePattern and forwardPattern attributes of the element in struts-config.xml is required toinform Struts to construct the paths correctly. More specifically, you need to set these attributes to the pattern"/WEB-INF/$A$P".

78. What is the Jakarta Struts Framework?

Jakarta Struts is an open source implementation of MVC(Model-View-Controller) pattern for the development of web based applications.Jakarta Struts is a robust architecture and can be used for the development of applications of any size.The “Struts framework” makes it easier to design scalable, reliable Web applications.

79. What is an ActionServlet?

The class org.apache.struts.action.ActionServlet is called the ActionServlet.In the Jakarta Struts Framework this class plays the role of controller.All the requests to the server go through the “Controller”.The “Controller” is responsible for handling all the requests.

80. How can one make any “Message Resources” definitions file available to the “Struts Framework” environment?

Answer: “Message Resources” definitions file are simple .properties files andthese files contain the messages that can be used in the struts project.

 “Message Resources” definition files can be added to the struts-config.xml filethrough <message-resources /> tag. Example:<message-resources parameter="MessageResources" />

124

Page 125: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 125/225

81. What is an “Action Class”?

The “Action Class” is part of the “Model” and is a wrapper around the business logic.The purpose of the “Action Class” is to translate the HttpServletRequest to the business logic.To use the “Action”, we need to subclass and overwrite the execute() method.All the database and business processing is done in the “Action” class.It is advisable to perform all the database related work in the “Action” class.The ActionServlet (command) passes the parameterized class to ActionForm using the execute() method.The return type of the execute method is ActionForward which is used by the Struts Framework to forward the

request to the file according to the value of the returned ActionForward object.

82. Write code of any Action Class?

Here is the code of Action Class that returns the ActionForward object.package j2eeonline.jdj.com;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;public class TestAction extends Action{

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,

HttpServletResponse response) throws Exception{return mapping.findForward("testAction");}}

83. What is an “ActionForm”?

An “ActionForm” is a JavaBean that extends org.apache.struts.action.ActionForm.ActionForm maintains the session state for web application and the “ActionForm” object is automaticallypopulated on the server side with data entered from a form on the client side.

84. What is Struts Validator Framework?

The “Struts Framework” provides the functionality to validate the form data.It can be used to validate the data in the user’s browser as well as on the server side.Struts Framework checks the JavaScript code and it can be used to validate the form data on the clientbrowser.Server side validation of form data can be accomplished by subclassing your “form” Bean withDynaValidatorForm class.The “Validator” framework was developed by David Winterfeldt as a third-party “add-on” to Struts.Now the Validator framework is part of the “Jakarta Commons” project and it can be used with or withoutStruts.The Validator framework comes integrated with the Struts Framework andcan be used without any making any additional settings.

85. Describe the details of XML files used in the “Validator Framework”?

The Validator Framework uses two XML configuration files1) validator-rules.xml and2) validation.xml.The validator-rules.xml defines the standard validation routines.

These are reusable and used in validation.xml to define the form specific validations.The validation.xml defines the validations applied to a form bean.

86. How would you display “validation fail” errors on a JSP page?

Following tag displays all the errors: <html:errors/>

87. How can one enable front-end validation based on the xml in validation.xml?

The <html:javascript> tag allows front-end validation based on the xml in validation.xml.For example the code:

generates the client side JavaScript for the form "logonForm" as defined in the validation.xml file.The <html:javascript> when added in the JSP file generates the client side validation script.

ORACLE1. What are the components of physical database structure of Oracle database?

Oracle database is comprised of three types of files. One or more datafiles, two are more redo log files, andone or more control files.

125

Page 126: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 126/225

2. What are the components of logical database structure of Oracle database?

There are tablespaces and database's schema objects.

3. What is a tablespace?

A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped relatedlogical structures together.

4. What is SYSTEM tablespace and when is it created?

Every Oracle database contains a tablespace named SYSTEM, which is automatically created when thedatabase is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database.

5. Explain the relationship among database, tablespace and data file.

Each databases logically divided into one or more tablespaces one or more data files are explicitly created foreach tablespace.

6. What is schema?

A schema is collection of database objects of a user.

7. What are Schema Objects?

Schema objects are the logical structures that directly refer to the database's data. Schema objects include

tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages anddatabase links.

8. Can objects of the same schema reside in different tablespaces?

Yes.

9. Can a tablespace hold objects from different schemes?

Yes.

10. What is Oracle table?

A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the useraccessible data. Table data is stored in rows and columns.

11. What is an Oracle view?

A view is a virtual table. Every view has a query attached to it. (The query is a SELECT statement thatidentifies the columns and rows of the table(s) the view uses.)

11. What is Partial Backup ?

A Partial Backup is any operating system backup short of a full backup, taken while the database is open orshut down.

12. What is Mirrored on-line Redo Log ?

A mirrored on-line redo log consists of copies of on-line redo log files physically located on separate disks,changes made to one member of the group are made to all members.

13. What is Full Backup ?

A full backup is an operating system backup of all data files, on-line redo log files and control file thatconstitute ORACLE database and the parameter.

14. Can a View based on another View ?

Yes.

15. Can a Tablespace hold objects from different Schemes ?

Yes.

16. Can objects of the same Schema reside in different tablespaces.?

Yes.

17. What is the use of Control File ?When an instance of an ORACLE database is started, its control file is used to identify the database and redolog files that must be opened for database operation to proceed. It is also used in database recovery.

18. Do View contain Data ?

Views do not contain or store data.

126

Page 127: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 127/225

19. What are the Referential actions supported by FOREIGN KEY integrity constraint ?

UPDATE and DELETE Restrict - A referential integrity rule that disallows the update or deletion of referenceddata. DELETE Cascade - When a referenced row is deleted all associated dependent rows are deleted.

20. What are the type of Synonyms?

There are two types of Synonyms Private and Public.

21. What is a Redo Log ?

The set of Redo Log files YSDATE,UID,USER or USERENV SQL functions, or the pseudo columns LEVEL orROWNUM.

22. What is an Index Segment ?

Each Index has an Index segment that stores all of its data.

23. Explain the relationship among Database, Tablespace and Data file.?

Each databases logically divided into one or more tablespaces one or more data files are explicitly created foreach tablespace

24. What are the different type of Segments ?

Data Segment, Index Segment, Rollback Segment and Temporary Segment.

25. What are Clusters ?

Clusters are groups of one or more tables physically stores together to share common columns and are oftenused together.

26. What is an Integrity Constrains ?

An integrity constraint is a declarative way to define a business rule for a column of a table.

27. What is an Index ?

An Index is an optional structure associated with a table to have direct access to rows, which can be created toincrease the performance of data retrieval. Index can be created on one or more columns of a table.

28. What is an Extent ?An Extent is a specific number of contiguous data blocks, obtained in a single allocation, and used to store aspecific type of information.

29. What is a View ?

A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECT statement thatidentifies the columns and rows of the table(s) the view uses.)

30. What is Table ?

A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the useraccessible data. Table data is stored in rows and columns

31. Can a view based on another view?

Yes.

32. What are the advantages of views?

- Provide an additional level of table security, by restricting access to a predetermined set of rows and columnsof a table.- Hide data complexity.- Simplify commands for the user.- Present the data in a different perspective from that of the base table.- Store complex queries.

33. What is an Oracle sequence?

A sequence generates a serial list of unique numbers for numerical columns of a database's tables.

34. What is a synonym?A synonym is an alias for a table, view, sequence or program unit.

35. What are the types of synonyms?

There are two types of synonyms private and public.

127

Page 128: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 128/225

36. What is a private synonym?

Only its owner can access a private synonym.

37. What is a public synonym?

Any database user can access a public synonym.

38. What are synonyms used for?- Mask the real name and owner of an object.- Provide public access to an object- Provide location transparency for tables, views or program units of a remote database.- Simplify the SQL statements for database users.

39. What is an Oracle index?

An index is an optional structure associated with a table to have direct access to rows, which can be created toincrease the performance of data retrieval. Index can be created on one or more columns of a table.

40. How are the index updates?

Indexes are automatically maintained and used by Oracle. Changes to table data are automaticallyincorporated into all relevant indexes.

41. What is a Tablespace?

A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped relatedlogical structures together

42. What is Rollback Segment ?

A Database contains one or more Rollback Segments to temporarily store "undo" information.

43. What are the Characteristics of Data Files ?

A data file can be associated with only one database. Once created a data file can't change size. One or moredata files form a logical unit of database storage called a tablespace.

44. How to define Data Block size ?A data block size is specified for each ORACLE database when the database is created. A database users andallocated free database space in ORACLE datablocks. Block size is specified in INIT.ORA file and can’t bechanged latter.

45. What does a Control file Contain ?

A Control file records the physical structure of the database. It contains the following information.Database NameNames and locations of a database's files and redolog files.Time stamp of database creation.

46.What is difference between UNIQUE constraint and PRIMARY KEY constraint ?

A column defined as UNIQUE can contain Nulls while a column defined as PRIMARY KEY can't contain Nulls.

47.What is Index Cluster ?

A Cluster with an index on the Cluster Key

48.When does a Transaction end ?

When it is committed or Rollbacked.

49. What is the effect of setting the value "ALL_ROWS" for OPTIMIZER_GOAL parameter of the ALTERSESSION command ? What are the factors that affect OPTIMIZER in choosing an Optimization approach ?

Answer The OPTIMIZER_MODE initialization parameter Statistics in the Data Dictionary the OPTIMIZER_GOALparameter of the ALTER SESSION command hints in the statement.

50. What is the effect of setting the value "CHOOSE" for OPTIMIZER_GOAL, parameter of the ALTER SESSIONCommand ?

The Optimizer chooses Cost_based approach and optimizes with the goal of best throughput if statistics foratleast one of the tables accessed by the SQL statement exist in the data dictionary. Otherwise the OPTIMIZERchooses RULE_based approach.

51. What is the function of Optimizer ?

128

Page 129: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 129/225

The goal of the optimizer is to choose the most efficient way to execute a SQL statement.

52. What is Execution Plan ?

The combinations of the steps the optimizer chooses to execute a statement is called an execution plan.

53. What are the different approaches used by Optimizer in choosing an execution plan ?

Rule-based and Cost-based.

54. What does ROLLBACK do ?

ROLLBACK retracts any of the changes resulting from the SQL statements in the transaction.

55. What is SAVE POINT ?

For long transactions that contain many SQL statements, intermediate markers or savepoints can be declaredwhich can be used to divide a transaction into smaller parts. This allows the option of later rolling back all workperformed from the current point in the transaction to a declared savepoint within the transaction.

56. What are the values that can be specified for OPTIMIZER MODE Parameter ?

COST and RULE.

57. What is COST-based approach to optimization ?

Considering available access paths and determining the most efficient execution plan based on statistics in thedata dictionary for the tables accessed by the statement and their associated clusters and indexes.

58. What does COMMIT do ?

COMMIT makes permanent the changes resulting from all SQL statements in the transaction. The changesmade by the SQL statements of a transaction become visible to other user sessions transactions that start onlyafter transaction is committed.

59. What is RULE-based approach to optimization ?

Choosing an executing planbased on the access paths available and the ranks of these access paths.

60. What are the values that can be specified for OPTIMIZER_GOAL parameter of the ALTER SESSION

Command ?CHOOSE,ALL_ROWS,FIRST_ROWS and RULE.

61. Define Transaction ?

A Transaction is a logical unit of work that comprises one or more SQL statements executed by a single user.

62. What is Read-Only Transaction ?

A Read-Only transaction ensures that the results of each query executed in the transaction are consistant withrespect to the same point in time.

63. What is a deadlock ? Explain .

Two processes wating to update the rows of a table which are locked by the other process then deadlockarises. In a database environment this will often happen because of not issuing proper row lock commands.

Poor design of front-end application may cause this situation and the performance of server will reducedrastically.These locks will be released automatically when a commit/rollback operation performed or any one of thisprocesses being killed externally.

64. What is a Schema ?

The set of objects owned by user account is called the schema.

65. What is a cluster Key ?

The related columns of the tables are called the cluster key. The cluster key is indexed using a cluster indexand its value is stored only once for multiple tables in the cluster.

66. What is Parallel Server ?

Multiple instances accessing the same database (Only In Multi-CPU environments)

67. What are the basic element of Base configuration of an oracle Database ?

It consists of one or more data files.

129

Page 130: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 130/225

one or more control files.two or more redo log files.The Database containsmultiple users/schemasone or more rollback segmentsone or more tablespacesData dictionary tablesUser objects (table,indexes,views etc.,)The server that access the database consists of SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)SMON (System MONito)PMON (Process MONitor)LGWR (LoG Write)DBWR (Data Base Write)ARCH (ARCHiver)CKPT (Check Point)RECODispatcherUser Process with associated PGS

68. What is clusters ?

Group of tables physically stored together because they share common columns and are often used together iscalled Cluster.

69. What is an Index ? How it is implemented in Oracle Database ?

An index is a database structure used by the server to have direct access of a row in a table. An index isautomatically created when a unique of primary key constraint clause is specified in create table comman (Ver7.0)

70. What is a Database instance ? Explain

A database instance (Server) is a set of memory structure and background processes that access a set of database files.The process can be shared by all users. The memory structure that are used to store most queried data fromdatabase. This helps up to improve database performance by decreasing the amount of I/O performed againstdata file.

71. WWhat is the use of ANALYZE command ?To perform one of these function on an index,table, or cluster:- To collect statistics about object used by the optimizer and store them in the data dictionary.- To delete statistics about the object used by object from the data dictionary.- To validate the structure of the object.- To identify migrated and chained rows of the table or cluster.

72. What is default tablespace ?

The Tablespace to contain schema objects created without specifying a tablespace name.

73. What are the system resources that can be controlled through Profile ?

The number of concurrent sessions the user can establish the CPU processing time available to the user'ssession the CPU processing time available to a single call to ORACLE made by a SQL statement the amount of 

logical I/O available to the user's session the amout of logical I/O available to a single call to ORACLE made bya SQL statement the allowed amount of idle time for the user's session the allowed amount of connect time forthe user's session.

74. What is Tablespace Quota ?

The collective amount of disk space available to the objects in a schema on a particular tablespace.

76. What are the different Levels of Auditing ?

Statement Auditing, Privilege Auditing and Object Auditing.

77. What is Statement Auditing ?

Statement auditing is the auditing of the powerful system privileges without regard to specifically namedobjects.

78. What are the database administrators utilities avaliable ?

SQL * DBA - This allows DBA to monitor and control an ORACLE database. SQL * Loader - It loads data fromstandard operating system files (Flat files) into ORACLE database tables. Export (EXP) and Import (imp)utilities allow you to move existing data in ORACLE format to and from ORACLE database.

130

Page 131: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 131/225

79. How can you enable automatic archiving ?

Shut the databaseBackup the databaseModify/Include LOG_ARCHIVE_START_TRUE in init.ora file.Start up the database.

80. What are roles? How can we implement roles ?

Roles are the easiest way to grant and manage common privileges needed by different groups of databaseusers. Creating roles and assigning provides to roles. Assign each role to group of users. This will simplify the job of assigning privileges to individual users.

81. What are Roles ?

Roles are named groups of related privileges that are granted to users or other roles.

82. What are the use of Roles ?

REDUCED GRANTING OF PRIVILEGES - Rather than explicitly granting the same set of privileges to many usersa database administrator can grant the privileges for a group of related users granted to a role and then grantonly the role to each member of the group.DYNAMIC PRIVILEGE MANAGEMENT - When the privileges of a group must change, only the privileges of therole need to be modified. The security domains of all users granted the group's role automatically reflect the

changes made to the role.SELECTIVE AVAILABILITY OF PRIVILEGES - The roles granted to a user can be selectively enable (available foruse) or disabled (not available for use). This allows specific control of a user's privileges in any given situation.APPLICATION AWARENESS - A database application can be designed to automatically enable and disableselective roles when a user attempts to use the application.

83. What is Privilege Auditing ?

Privilege auditing is the auditing of the use of powerful system privileges without regard to specifically namedobjects.

84. What is Object Auditing ?

Object auditing is the auditing of accesses to specific schema objects without regard to user.

85. What is Auditing ?Monitoring of user access to aid in the investigation of database use

86. What are the responsibilities of a Database Administrator ?

Installing and upgrading the Oracle Server and application tools. Allocating system storage and planning futurestorage requirements for the database system. Managing primary database structures (tablespaces) Managingprimary objects (table,views,indexes) Enrolling users and maintaining system security. Ensuring compliancewith Oralce license agreement Controlling and monitoring user access to the database. Monitoring andoptimizing the performance of the database. Planning for backup and recovery of database information.Maintain archived data on tape Backing up and restoring the database. Contacting Oracle Corporation fortechnical support.

87. What is a trace file and how is it created ?

Each server and background process can write an associated trace file. When an internal error is detected by aprocess or user process, it dumps information about the error to its trace. This can be used for tuning thedatabase.

88. What is a profile ?

Each database user is assigned a Profile that specifies limitations on various system resources available to theuser.

89. How will you enforce security using stored procedures?

Don't grant user access directly to tables within the application. Instead grant the ability to access theprocedures that access the tables. When procedure executed it will execute the privilege of procedures owner.Users cannot access tables except via the procedure.

90. What are the dictionary tables used to monitor a database spaces ?

DBA_FREE_SPACEDBA_SEGMENTSDBA_DATA_FILES.

91. What are the roles and user accounts created automatically with the database?

131

Page 132: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 132/225

DBA - role Contains all database system privileges.SYS user account - The DBA role will be assigned to this account. All of the base tables and views for thedatabase's dictionary are store in this schema and are manipulated only by ORACLE. SYSTEM user account - Ithas all the system privileges for the database and additional tables and views that display administrativeinformation and internal tables and views used by oracle tools are created using this username.

92. What are the minimum parameters should exist in the parameter file (init.ora) ?

DB NAME - Must set to a text string of no more than 8 characters and it will be stored inside the datafiles, redolog files and control files and control file while database creation.DB_DOMAIN - It is string that specifies the network domain where the database is created. The globaldatabase name is identified by setting these parameters(DB_NAME & DB_DOMAIN) CONTORL FILES - List of control filenames of the database. If name is notmentioned then default name will be used.DB_BLOCK_BUFFERS - To determine the no of buffers in the buffer cache in SGA.PROCESSES - To determine number of operating system processes that can be connected to ORACLEconcurrently. The value should be 5 (background process) and additional 1 for each user.ROLLBACK_SEGMENTS - List of rollback segments an ORACLE instance acquires at database startup. Alsooptionally LICENSE_MAX_SESSIONS,LICENSE_SESSION_WARNING and LICENSE_MAX_USERS.

93. How can we specify the Archived log file name format and destination?

By setting the following values in init.ora file. LOG_ARCHIVE_FORMAT = arch %S/s/T/tarc (%S - Log sequencenumber and is zero left paded, %s - Log sequence number not padded. %T - Thread number lef-zero-padedand %t - Thread number not padded). The file name created is arch 0001 are if %S is used.LOG_ARCHIVE_DEST = path.

94. What is user Account in Oracle database?

An user account is not a physical structure in Database but it is having important relationship to the objects inthe database and will be having certain privileges.

95. When will the data in the snapshot log be used?

We must be able to create a after row trigger on table (i.e., it should be not be already available) After givingtable privileges. We cannot specify snapshot log name because oracle uses the name of the master table in thename of the database objects that support its snapshot log. The master table name should be less than orequal to 23 characters. (The table name created will be MLOGS_tablename, and trigger name will be TLOGSname).

96. What dynamic data replication?

Updating or Inserting records in remote database through database triggers. It may fail if remote database ishaving any problem.

97. What is Two-Phase Commit ?

Two-phase commit is mechanism that guarantees a distributed transaction either commits on all involvednodes or rolls back on all involved nodes to maintain data consistency across the global distributed database. Ithas two phase, a Prepare Phase and a Commit Phase.

98. How can you Enforce Referential Integrity in snapshots ?

Time the references to occur when master tables are not in use. Peform the reference the manually immdiatelylocking the master tables. We can join tables in snopshots by creating a complex snapshots that will based onthe master tables.

99. What is a SQL * NET?

SQL *NET is ORACLE's mechanism for interfacing with the communication protocols used by the networks thatfacilitate distributed processing and distributed databases. It is used in Clint-Server and Server-Servercommunications.

100. What is a SNAPSHOT ?

Snapshots are read-only copies of a master table located on a remote node which is periodically refreshed toreflect changes made to the master table.

101. What is the mechanism provided by ORACLE for table replication ?

Snapshots and SNAPSHOT LOGs

102. What is snapshots?Snapshot is an object used to dynamically replicate data between distribute database at specified timeintervals. In ver 7.0 they are read only.

103. What are the various type of snapshots?

132

Page 133: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 133/225

Simple and Complex.

104. Describe two phases of Two-phase commit ?

Prepare phase - The global coordinator (initiating node) ask a participants to prepare (to promise to commit orrollback the transaction, even if there is a failure) Commit - Phase - If all participants respond to thecoordinator that they are prepared, the coordinator asks all nodes to commit the transaction, if all participantscannot prepare, the coordinator asks all nodes to roll back the transaction.

105. What is snapshot log ?

It is a table that maintains a record of modifications to the master table in a snapshot. It is stored in the samedatabase as master table and is only available for simple snapshots. It should be created before creatingsnapshots.

106. What are the benefits of distributed options in databases?

Database on other servers can be updated and those transactions can be grouped together with others in alogical unit.Database uses a two phase commit.

107. What are the options available to refresh snapshots ?

COMPLETE - Tables are completely regenerated using the snapshots query and the master tables every timethe snapshot referenced.FAST - If simple snapshot used then a snapshot log can be used to send the changes to the snapshot tables.

FORCE - Default value. If possible it performs a FAST refresh; Otherwise it will perform a complete refresh.

108. What is a SNAPSHOT LOG ?

A snapshot log is a table in the master database that is associated with the master table. ORACLE uses asnapshot log to track the rows that have been updated in the master table. Snapshot logs are used in updatingthe snapshots based on the master table.

109. What is Distributed database ?

A distributed database is a network of databases managed by multiple database servers that appears to a useras single logical database. The data of all databases in the distributed database can be simultaneouslyaccessed and modified.

110. How can we reduce the network traffic?

- Replication of data in distributed environment.- Using snapshots to replicate data.- Using remote procedure calls.

111. Differentiate simple and complex, snapshots ?

- A simple snapshot is based on a query that does not contains GROUP BY clauses, CONNECT BY clauses,JOINs, sub-query or snashot of operations.- A complex snapshots contain atleast any one of the above.

112. What are the Built-ins used for sending Parameters to forms?

You can pass parameter values to a form when an application executes the call_form, New_form, Open_formor Run_product.

113. Can you have more than one content canvas view attached with a window?

Yes. Each window you create must have atleast one content canvas view assigned to it. You can also create awindow that has manipulated content canvas view. At run time only one of the content canvas views assign toa window is displayed at a time.

114. Is the After report trigger fired if the report execution fails?

Yes.

115. Does a Before form trigger fire when the parameter form is suppressed?

Yes.

116. What is SGA?

The System Global Area in an Oracle database is the area in memory to facilitate the transfer of informationbetween users. It holds the most recently requested structural information between users. It holds the mostrecently requested structural information about the database. The structure is database buffers, dictionarycache, redo log buffer and shared pool area.

117. What is a shared pool?

133

Page 134: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 134/225

The data dictionary cache is stored in an area in SGA called the shared pool. This will allow sharing of parsedSQL statements among concurrent users.

118. What is mean by Program Global Area (PGA)?

It is area in memory that is used by a single Oracle user process.

119. What is a data segment?

Data segment are the physical areas within a database block in which the data associated with tables andclusters are stored.

120. What are the factors causing the reparsing of SQL statements in SGA?

Due to insufficient shared pool size.Monitor the ratio of the reloads takes place while executing SQL statements. If the ratio is greater than 1 thenincrease the SHARED_POOL_SIZE.

121. What are clusters?

Clusters are groups of one or more tables physically stores together to share common columns and are oftenused together.

122. What is cluster key?

The related columns of the tables in a cluster are called the cluster key.

123. Do a view contain data?

Views do not contain or store data.

124. What is user Account in Oracle database?

A user account is not a physical structure in database but it is having important relationship to the objects inthe database and will be having certain privileges.

125. How will you enforce security using stored procedures?

Don't grant user access directly to tables within the application. Instead grant the ability to access theprocedures that access the tables. When procedure executed it will execute the privilege of procedures owner.Users cannot access tables except via the procedure.

126. What are the dictionary tables used to monitor a database space?

DBA_FREE_SPACEDBA_SEGMENTSDBA_DATA_FILES.

127. Can a property clause itself be based on a property clause?

Yes

128. If a parameter is used in a query without being previously defined, what diff. exist betw. report 2.0 and2.5 when the query is applied?

While both reports 2.0 and 2.5 create the parameter, report 2.5 gives a message that a bind parameter hasbeen created.

129. What are the sql clauses supported in the link property sheet?Where start with having.

130. What is trigger associated with the timer?

When-timer-expired.

131. What are the trigger associated with image items?

When-image-activated fires when the operators double clicks on an image itemwhen-image-pressed fires whenan operator clicks or double clicks on an image item

132. What are the different windows events activated at runtimes?

When_window_activated

When_window_closedWhen_window_deactivatedWhen_window_resizedWithin this triggers, you can examine the built in system variable system. event_window to determine thename of the window for which the trigger fired.

134

Page 135: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 135/225

133. When do you use data parameter type?

When the value of a data parameter being passed to a called product is always the name of the record groupdefined in the current form. Data parameters are used to pass data to produts invoked with the run_productbuilt-in subprogram.

134. What is difference between open_form and call_form?

when one form invokes another form by executing open_form the first form remains displayed, and operatorscan navigate between the forms as desired. when one form invokes another form by executing call_form, the

called form is modal with respect to the calling form. That is, any windows that belong to the calling form aredisabled, and operators cannot navigate to them until they first exit the called form.

135. What is new_form built-in?

When one form invokes another form by executing new_form oracle form exits the first form and releases itsmemory before loading the new form calling new form completely replace the first with the second. If there arechanges pending in the first form, the operator will be prompted to save them before the new form is loaded.

136. What is the "LOV of Validation" Property of an item? What is the use of it?

When LOV for Validation is set to True, Oracle Forms compares the current value of the text item to the valuesin the first column displayed in the LOV. Whenever the validation event occurs. If the value in the text itemmatches one of the values in the first column of the LOV, validation succeeds, the LOV is not displayed, andprocessing continues normally. If the value in the text item does not match one of the values in the firstcolumn of the LOV, Oracle Forms displays the LOV and uses the text item value as the search criteria toautomatically reduce the list.137. What is the diff. when Flex mode is mode on and when it is off?

When flex mode is on, reports automatically resizes the parent when the child is resized.

138. What is the diff. when confine mode is on and when it is off?

When confine mode is on, an object cannot be moved outside its parent in the layout.

139. What are visual attributes?

Visual attributes are the font, color, pattern proprieties that you set for form and menu objects that appear inyour application interface.

140. Which of the two views should objects according to possession?

view by structure.

141. What are the two types of views available in the object navigator(specific to report 2.5)?

View by structure and view by type .

142. What are the vbx controls?

Vbx control provide a simple method of building and enhancing user interfaces. The controls can use to obtainuser inputs and display program outputs.vbx control where originally develop as extensions for the ms visualbasic environments and include such items as sliders, rides and knobs.

143. What is the use of transactional triggers?

Using transactional triggers we can control or modify the default functionality of the oracle forms.

144. How do you create a new session while open a new form?

Using open_form built-in setting the session option Ex. Open_form('Stocks ',active,session). when invoke themulitiple forms with open form and call_form in the same application, state whether the following aretrue/False

145. What are the ways to monitor the performance of the report?

Use reports profile executable statement. Use SQL trace facility.

146. If two groups are not linked in the data model editor, What is the hierarchy between them?

Two group that is above are the left most rank higher than the group that is to right or below it.

147. An open form can not be execute the call_form procedure if you chain of called forms has been

initiated by another open form?True

148. Explain about horizontal, Vertical tool bar canvas views?

135

Page 136: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 136/225

Tool bar canvas views are used to create tool bars for individual windows. Horizontal tool bars are display atthe top of a window, just under its menu bar. Vertical Tool bars are displayed along the left side of a window

149. What is the purpose of the product order option in the column property sheet?

To specify the order of individual group evaluation in a cross products.

150. What is the use of image_zoom built-in?

To manipulate images in image items.

151. How do you reference a parameter indirectly?

To indirectly reference a parameter use the NAME IN, COPY 'built-ins to indirectly set and reference theparameters value' Example name_in ('capital parameter my param'), Copy ('SURESH','Parameter my_param')

152. What is a timer?

Timer is an "internal time clock" that you can programmatically create to perform an action each time thetimes.

153. What are the two phases of block coordination?

There are two phases of block coordination: the clear phase and the population phase. During, the clear phase,Oracle Forms navigates internally to the detail block and flushes the obsolete detail records. During the

population phase, Oracle Forms issues a SELECT statement to repopulate the detail block with detail recordsassociated with the new master record. These operations are accomplished through the execution of triggers.

154. What are Most Common types of Complex master-detail relationships?

There are three most common types of complex master-detail relationships:master with dependent detailsmaster with independent detailsdetail with two masters

155. What is a text list?

The text list style list item appears as a rectangular box which displays the fixed number of values. When thetext list contains values that can not be displayed, a vertical scroll bar appears, allowing the operator to viewand select undisplayed values.

156. What is term?

The term is terminal definition file that describes the terminal form which you are using r20run.

157. What is use of term?

The term file which key is correspond to which oracle report functions.

158. What is pop list?

The pop list style list item appears initially as a single field (similar to a text item field). When the operatorselects the list icon, a list of available choices appears.

159. What is the maximum no of chars the parameter can store?

The maximum no of chars the parameter can store is only valid for char parameters, which can be upto 64K.

No parameters default to 23Bytes and Date parameter default to 7Bytes.

160. What are the default extensions of the files created by library module?

The default file extensions indicate the library module type and storage format .pll - pl/sql library modulebinary

161. What are the Coordination Properties in a Master-Detail relationship?

The coordination properties areDeferredAuto-QueryThese Properties determine when the population phase of blockcoordination should occur.

162. How do you display console on a window ?The console includes the status line and message line, and is displayed at the bottom of the window to which itis assigned.To specify that the console should be displayed, set the console window form property to the nameof any window in the form. To include the console, set console window to Null.

163. What are the different Parameter types?

136

Page 137: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 137/225

Text ParametersData Parameters

164. State any three mouse events system variables?

System.mouse_button_pressedSystem.mouse_button_shift

165. What are the types of calculated columns available?

Summary, Formula, Placeholder column.

166. Explain about stacked canvas views?

Stacked canvas view is displayed in a window on top of, or "stacked" on the content canvas view assigned tothat same window. Stacked canvas views obscure some part of the underlying content canvas view, and oroften shown and hidden programmatically.

167. What are the built_ins used the display the LOV?

Show_lovList_values

168. What is the difference between SHOW_EDITOR and EDIT_TEXTITEM?

Show editor is the generic built-in which accepts any editor name and takes some input string and returnsmodified output string. Whereas the edit_textitem built-in needs the input focus to be in the text item beforethe built-in is executed.

169. What are the built-ins that are used to Attach an LOV programmatically to an item?

set_item_propertyget_item_property(by setting the LOV_NAME property)

170. How do you call other Oracle Products from Oracle Forms?

Run_product is a built-in, Used to invoke one of the supported oracle tools products and specifies the name of the document or module to be run. If the called product is unavailable at the time of the call, Oracle Formsreturns a message to the operator.

171. What is the main diff. bet. Reports 2.0 & Reports 2.5?

Report 2.5 is object oriented.

172. What are the different file extensions that are created by oracle reports?

Rep file and Rdf file.

173. What is strip sources generate options?

Removes the source code from the library file and generates a library files that contains only pcode. Theresulting file can be used for final deployment, but can not be subsequently edited in the designer.ex. f45genmodule=old_lib.pll userid=scott/tiger strip_source YES output_file

176. What is the basic data structure that is required for creating an LOV?

Record Group.

177. What is the Maximum allowed length of Record group Column?Record group column names cannot exceed 30 characters.

178. Which parameter can be used to set read level consistency across multiple queries?

Read only

179. What are the different types of Record Groups?

Query Record GroupsNonQuery Record GroupsState Record Groups

180. From which designation is it preferred to send the output to the printed?

Previewer

181. what are difference between post database commit and post-form commit?

Post-form commit fires once during the post and commit transactions process, after the database commitoccurs. The post-form-commit trigger fires after inserts, updates and deletes have been posted to the database

137

Page 138: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 138/225

but before the transactions have been finalized in the issuing the command. The post-database-commit triggerfires after oracle forms issues the commit to finalized transactions.

182. What are the different display styles of list items?

Pop_listText_listCombo box

183. Which of the above methods is the faster method?

performing the calculation in the query is faster.

184. With which function of summary item is the compute at options required?

percentage of total functions.

185. What are parameters?

Parameters provide a simple mechanism for defining and setting the valuesof inputs that are required by aform at startup. Form parameters are variables of type char,number,date that you define at design time.

186. What are the three types of user exits available ?

Oracle Precompiler exits, Oracle call interface, NonOracle user exits.

187. How many windows in a form can have console?

Only one window in a form can display the console, and you cannot change the console assignment at runtime.

188.If the maximum record retrieved property of the query is set to 10 then a summary value will becalculated?

Only for 10 records.

189.What are the two repeating frame always associated with matrix object?

One down repeating frame below one across repeating frame.

190. What are the master-detail triggers?\ 

On-Check_delete_masterOn_clear_detailsOn_populate_details

191. What are the different objects that you cannot copy or reference in object groups?Objects of different modulesAnother object groupsIndividual block dependent itemsProgram units.

192. What is an OLE?

Object Linking & Embedding provides you with the capability to integrate objects from many Ms-Windowsapplications into a single compound document creating integrated applications enables you to use the featuresform .

193. Is it possible to modify an external query in a report which contains it?

No.

194. Does a grouping done for objects in the layout editor affect the grouping done in the data model editor?

No.

195. Can a repeating frame be created without a data group as a base?

No

196. If a break order is set on a column would it affect columns which are under the column?

No

197. Is it possible to set a filter condition in a cross product group in matrix reports?

No

198. Do user parameters appear in the data modal editor in 2.5?

No

199. Can you pass data parameters to forms?

No

138

Page 139: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 139/225

200. Is it possible to link two groups inside a cross products after the cross products group has been created?

no

201. What are the different modals of windows?

Modalless windowsModal windows

202. What are modal windows?

Modal windows are usually used as dialogs, and have restricted functionality compared to modelless windows.On some platforms for example operators cannot resize, scroll or iconify a modal window.

203. What are the different default triggers created when Master Deletes Property is set to Non-isolated?

Master Deletes Property Resulting Triggers----------------------------------------------------Non-Isolated(the default) On-Check-Delete-MasterOn-Clear-DetailsOn-Populate-Details

204. What are the different default triggers created when Master Deletes Property is set to isolated?

Master Deletes Property Resulting Triggers---------------------------------------------------Isolated On-Clear-DetailsOn-Populate-Details

205. What are the different default triggers created when Master Deletes Property is set to Cascade?

Master Deletes Property Resulting Triggers---------------------------------------------------Cascading On-Clear-DetailsOn-Populate-DetailsPre-delete

206. What is the diff. bet. setting up of parameters in reports 2.0 reports2.5?

LOVs can be attached to parameters in the reports 2.5 parameter form.

207. What are the difference between lov & list item?

Lov is a property where as list item is an item. A list item can have only one column, lov can have one or morecolumns.

208. What is the advantage of the library?

Libraries provide a convenient means of storing client-side program units and sharing them among multipleapplications. Once you create a library, you can attach it to any other form, menu, or library modules. Whenyou can call library program units from triggers menu items commands and user named routine, you write inthe modules to which you have attach the library. When a library attaches another library, program units in thefirst library can reference program units in the attached library. Library support dynamic loading-that is libraryprogram units are loaded into an application only when needed. This can significantly reduce the run-timememory requirements of applications.

209. What is lexical reference? How can it be created?Lexical reference is place_holder for text that can be embedded in a sql statements. A lexical reference can becreated using & before the column or parameter name.

210. What is system.coordination_operation?

It represents the coordination causing event that occur on the master block in master-detail relation.

211. What is synchronize?

It is a terminal screen with the internal state of the form. It updates the screen display to reflect theinformation that oracle forms has in its internal representation of the screen.

212. What use of command line parameter cmd file?

It is a command line argument that allows you to specify a file that contain a set of arguments for r20run.

213. What is a Text_io Package?

It allows you to read and write information to a file in the file system.

139

Page 140: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 140/225

214. What is forms_DDL?

Issues dynamic Sql statements at run time, including server side pl/SQl and DDL

215. How is link tool operation different bet. reports 2 & 2.5?

In Reports 2.0 the link tool has to be selected and then two fields to be linked are selected and the link isautomatically created. In 2.5 the first field is selected and the link tool is then used to link the first field to thesecond field.

216. What are the different styles of activation of ole Objects?In place activationExternal activation

217. How do you reference a Parameter?

In Pl/Sql, You can reference and set the values of form parameters using bind variables syntax. Ex.PARAMETER name = '' or :block.item = PARAMETER Parameter name

218. What is the difference between object embedding & linking in Oracle forms?

In Oracle forms, Embedded objects become part of the form module, and linked objects are references from aform module to a linked source file.

219. Name of the functions used to get/set canvas properties?

Get_view_property, Set_view_property

220. What are the built-ins that are used for setting the LOV properties at runtime?

get_lov_propertyset_lov_property

221. What are the built-ins used for processing rows?

Get_group_row_count(function)Get_group_selection_count(function)Get_group_selection(function)Reset_group_selection(procedure)Set_group_selection(procedure)Unset_group_selection(procedure)

222. What are built-ins used for Processing rows?GET_GROUP_ROW_COUNT(function)GET_GROUP_SELECTION_COUNT(function)GET_GROUP_SELECTION(function)RESET_GROUP_SELECTION(procedure)SET_GROUP_SELECTION(procedure)UNSET_GROUP_SELECTION(procedure)

223. What are the built-in used for getting cell values?

Get_group_char_cell(function)Get_groupcell(function)Get_group_number_cell(function)

224. What are the built-ins used for Getting cell values?GET_GROUP_CHAR_CELL (function)GET_GROUPCELL(function)GET_GROUP_NUMBET_CELL(function)

225. Atleast how many set of data must a data model have before a data model can be base on it?

Four

226. To execute row from being displayed that still use column in the row which property can be used?

Format trigger.

227. What are different types of modules available in oracle form?

Form module - a collection of objects and code routines Menu modules - a collection of menus and menu item

commands that together make up an application menu library module - a collection of user named procedures,functions and packages that can be called from other modules in the application

228. What is the remove on exit property?

For a modelless window, it determines whether oracle forms hides the window automatically when theoperators navigates to an item in the another window.

140

Page 141: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 141/225

229. What is WHEN-Database-record trigger?

Fires when oracle forms first marks a record as an insert or an update. The trigger fires as soon as oracleforms determines through validation that the record should be processed by the next post or commit as aninsert or update. c generally occurs only when the operators modifies the first item in the record, and after theoperator attempts to navigate out of the item.

230. What is a difference between pre-select and pre-query?

Fires during the execute query and count query processing after oracle forms constructs the select statementto be issued, but before the statement is actually issued. The pre-query trigger fires just before oracle formsissues the select statement to the database after the operator as define the example records by entering thequery criteria in enter query mode.Pre-query trigger fires before pre-select trigger.

231. What are built-ins associated with timers?

find_timercreate_timerdelete_timer

232. What are the built-ins used for finding object ID functions?

Find_group(function)Find_column(function)

233. What are the built-ins used for finding Object ID function?

FIND_GROUP(function)FIND_COLUMN(function)

234. Any attempt to navigate programmatically to disabled form in a call_form stack is allowed?

False

235. Use the Add_group_row procedure to add a row to a static record group 1. true or false?

False

236. Use the add_group_column function to add a column to record group that was created at a designtime?

False

237. What are the various sub events a mouse double click event involves? What are the various sub events amouse double click event involves?

Double clicking the mouse consists of the mouse down, mouse up, mouse click, mouse down & mouse upevents.

238. How can a break order be created on a column in an existing group? What are the various sub events amouse double click event involves?

By dragging the column outside the group.

239. What is the use of place holder column? What are the various sub events a mouse double click eventinvolves?

A placeholder column is used to hold calculated values at a specified place rather than allowing is to appear in

the actual row where it has to appear.

240. What is the use of hidden column? What are the various sub events a mouse double click event involves?

A hidden column is used to when a column has to embed into boilerplate text.

241. What is the use of break group? What are the various sub events a mouse double click event involves?

A break group is used to display one record for one group ones. While multiple related records in other groupcan be displayed.

242. What is an anchoring object & what is its use? What are the various sub events a mouse double clickevent involves?

An anchoring object is a print condition object which used to explicitly or implicitly anchor other objects toitself.

243. What are the various sub events a mouse double click event involves? What are the various sub events amouse double click event involves?

Double clicking the mouse consists of the mouse down, mouse up, mouse click, mouse down & mouse upevents.

141

Page 142: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 142/225

245. What are the default parameter that appear at run time in the parameter screen? What are the varioussub events a mouse double click event involves?

Destype and Desname.

246. What are the built-ins used for Creating and deleting groups?

CREATE-GROUP (function)CREATE_GROUP_FROM_QUERY(function)DELETE_GROUP(procedure)

247. What are different types of canvas views?

Content canvas viewsStacked canvas viewsHorizontal toolbarvertical toolbar.

248. What are the different types of Delete details we can establish in Master-Details?

CascadeIsolateNon-isolate

249. What is relation between the window and canvas views?

Canvas views are the back ground objects on which you place the interface items (Text items), check boxes,radio groups etc.,) and boilerplate objects (boxes, lines, images etc.,) that operators interact with us they runyour form . Each canvas views displayed in a window.

250. What is a User_exit?

Calls the user exit named in the user_exit_string. Invokes a 3Gl program by name which has been properlylinked into your current oracle forms executable.

251. How is it possible to select generate a select set for the query in the query property sheet?

By using the tables/columns button and then specifying the table and the column names.

252. How can values be passed bet. precompiler exits & Oracle call interface?

By using the statement EXECIAFGET & EXECIAFPUT.

253. How can a square be drawn in the layout editor of the report writer?

By using the rectangle tool while pressing the (Constraint) key.

254. How can a text file be attached to a report while creating in the report writer?

By using the link file property in the layout boiler plate property sheet.

255. How can I message to passed to the user from reports?

By using SRW.MESSAGE function.

256. How is possible to restrict the user to a list of values while entering values for parameters?

By setting the Restrict To List property to true in the parameter property sheet.

257. How can a button be used in a report to give a drill down facility?

By setting the action associated with button to Execute pl/sql option and using the SRW.Run_report function.

258. How can a cross product be created?

By selecting the cross products tool and drawing a new group surrounding the base group of the crossproducts.

259. What are different types of images?

Boiler plate imagesImage Items

260. What is the difference between boiler plat images and image items?

Boiler plate Images are static images (Either vector or bit map) that you import from the file system ordatabase to use a graphical elements in your form, such as company logos and maps. Image items are specialtypes of interface controls that store and display either vector or bitmap images. Like other items that storevalues, image items can be either base table items(items that relate directly to database columns) or controlitems. The definition of an image item is stored as part of the form module FMB and FMX files, but no imagefile is actually associated with an image item until the item is populate at run time.

142

Page 143: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 143/225

261. What is bind reference and how can it be created?

Bind reference are used to replace the single value in sql, pl/sql statements a bind reference can be createdusing a (:) before a column or a parameter name.

262. What are the triggers available in the reports?

Before report, Before form, After form , Between page, After report.

263. Give the sequence of execution of the various report triggers?

Before form , After form , Before report, Between page, After report.

264. Why is a Where clause faster than a group filter or a format trigger?

Because, in a where clause the condition is applied during data retrievalthan after retrieving the data.

265. Why is it preferable to create a fewer no. of queries in the data model?

Because for each query, report has to open a separate cursor and has to rebind, execute and fetch data.

266. Where is the external query executed at the client or the server?

At the server.

267. Where is a procedure return in an external pl/sql library executed at the client or at the server?At the client.

268. What is coordination Event?

Any event that makes a different record in the master block the current record is a coordination causing event.

269. What is the difference between OLE Server & Ole Container?

An Ole server application creates ole Objects that are embedded or linked in ole Containers ex. Ole servers arems_word & ms_excel. OLE containers provide a place to store, display and manipulate objects that are createdby ole server applications. Ex. oracle forms is an example of an ole Container.

270. What is an object group?

An object group is a container for a group of objects; you define an object group when you want to packagerelated objects, so that you copy or reference them in other modules.

271. What is an LOV?

An LOV is a scrollable popup window that provides the operator with either a single or multi column selectionlist.

272. At what point of report execution is the before Report trigger fired?

After the query is executed but before the report is executed and the records are displayed.

273. What are the built -ins used for Modifying a groups structure?

ADD-GROUP_COLUMN (function)ADD_GROUP_ROW (procedure)DELETE_GROUP_ROW(procedure)

274. What is an user exit used for?

A way in which to pass control (and possibly arguments ) form Oracle report to another Oracle products of 3GL and then return control ( and ) back to Oracle reports.

275. What is the User-Named Editor?

A user named editor has the same text editing functionality as the default editor, but, because it is a namedobject, you can specify editor attributes such as windows display size, position, and title.

276. What are the Built-ins to display the user-named editor?

A user named editor can be displayed programmatically with the built in procedure SHOW-EDITOR,EDIT_TETITEM independent of any particular text item.

277. What is a Static Record Group?

A static record group is not associated with a query, rather, you define its structure and row values at designtime, and they remain fixed at runtime.

143

Page 144: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 144/225

278. What is a record group?

A record group is an internal Oracle Forms that structure that has a column/row framework similar to adatabase table. However, unlike database tables, record groups are separate objects that belong to the formmodule which they are defined.

279. How many number of columns a record group can have?

A record group can have an unlimited number of columns of type CHAR, LONG, NUMBER, or DATE providedthat the total number of column does not exceed 64K.

280. What is a Query Record Group?

A query record group is a record group that has an associated SELECT statement. The columns in a queryrecord group derive their default names, data types, had lengths from the database columns referenced in theSELECT statement. The records in query record group are the rows retrieved by the query associated with thatrecord group. What is a Non Query Record Group?

281. What is a property clause?

A property clause is a named object that contains a list of properties and their settings. Once you create aproperty clause you can base other object on it. An object based on a property can inherit the setting of anyproperty in the clause that makes sense for that object.

282. What is a physical page ? & What is a logical page ?

A physical page is a size of a page. That is output by the printer. The logical page is the size of one page of theactual report as seen in the Previewer.

283. What does the term panel refer to with regard to pages?

A panel is the no. of physical pages needed to print one logical page.

284. What is a master detail relationship?

A master detail relationship is an association between two base table blocks- a master block and a detail block.The relationship between the blocks reflects a primary key to foreign key relationship between the tables onwhich the blocks are based.

285.What is a library?

A library is a collection of subprograms including user named procedures, functions and packages.286. How can a group in a cross products be visually distinguished from a group that does not form a

cross product?

A group that forms part of a cross product will have a thicker border.

287. What is the frame & repeating frame?

A frame is a holder for a group of fields. A repeating frame is used to display a set of records when the no. of records that are to displayed is not known before.

288. What is a combo box?

A combo box style list item combines the features found in list and text item. Unlike the pop list or the text liststyle list items, the combo box style list item will both display fixed values and accept one operator enteredvalue.

289. What are three panes that appear in the run time pl/sql interpreter?

1. Source pane.2. interpreter pane.3. Navigator pane.

290. What are the two panes that Appear in the design time pl/sql interpreter?

1. Source pane.2. Interpreter pane

291. What are the two ways by which data can be generated for a parameters list of values?

1. Using static values.

2. Writing select statement.

292. What are the various methods of performing a calculation in a report ?

1. Perform the calculation in the SQL statements itself.2. Use a calculated / summary column in the data model.

144

Page 145: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 145/225

293. What are the default extensions of the files created by menu module?

.mmb,

.mmx

294. What are the default extensions of the files created by forms modules?

.fmb - form module binary

.fmx - form module executable

295. To display the page no. for each page on a report what would be the source & logical page no. or & of physical page no.?

& physical page no.

296. It is possible to use raw devices as data files and what is the advantages over file. system files ?

Yes. The advantages over file system files. I/O will be improved because Oracle is bye-passing the kernnelwhich writing into disk. Disk Corruption will be very less.

297. What are disadvantages of having raw devices ?

We should depend on export/import utility for backup/recovery (fully reliable) The tar command cannot beused for physical file backup, instead we can use dd command which is less flexible and has limited recoveries.

298. What is the significance of having storage clause ?We can plan the storage for a table as how much initial extents are required, how much can be extended next,how much % should leave free for managing row updations etc.,

299. What is the use of INCTYPE option in EXP command ?

Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL. List the sequence of events when alarge transaction that exceeds beyond its optimal value when an entry wraps and causes the rollback segmenttoexpand into anotion Completes. e. will be written.

300. What is the use of FILE option in IMP command ?

The name of the file from which import should be performed.

301. What is a Shared SQL pool?The data dictionary cache is stored in an area in SGA called the Shared SQL Pool. This will allow sharing of parsed SQL statements among concurrent users.

302. What is hot backup and how it can be taken?

Taking backup of archive log files when database is open. For this the ARCHIVELOG mode should be enabled.The following files need to be backed up. All data files. All Archive log, redo log files. All control files.

303. List the Optional Flexible Architecture (OFA) of Oracle database? or How can we organize the tablespacesin Oracle database to have maximum performance ?

SYSTEM - Data dictionary tables.DATA - Standard operational tables.DATA2- Static tables used for standard operations

INDEXES - Indexes for Standard operational tables.INDEXES1 - Indexes of static tables used for standard operations.TOOLS - Tools table.TOOLS1 - Indexes for tools table.RBS - Standard Operations Rollback Segments,RBS1,RBS2 - Additional/Special Rollback segments.TEMP - Temporary purpose tablespaceTEMP_USER - Temporary tablespace for users.USERS - User tablespace.

304. How to implement the multiple control files for an existing database ?

Shutdown the database Copy one of the existing control file to new location Edit Config ora file by adding newcontrol file. name Restart the database.

305. What is advantage of having disk shadowing/ Mirroring ?

Shadow set of disks save as a backup in the event of disk failure. In most Operating System if any disk failureoccurs it automatically switchover to place of failed disk. Improved performance because most OS supportvolume shadowing can direct file I/O request to use the shadow set of files instead of the main set of files. Thisreduces I/O load on the main set of disks.

306. How will you force database to use particular rollback segment ?

145

Page 146: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 146/225

SET TRANSACTION USE ROLLBACK SEGMENT rbs_name.

307. Why query fails sometimes ?

Rollback segment dynamically extent to handle larger transactions entry loads. A single transaction maywipeout all available free space in the Rollback Segment Tablespace. This prevents other user using Rollbacksegments.

308. What is the use of RECORD LENGTH option in EXP command ?

Record length in bytes.

309. How will you monitor rollback segment status ?

Querying the DBA_ROLLBACK_SEGS viewIN USE - Rollback Segment is on-line.AVAILABLE - Rollback Segment available but not on-line.OFF-LINE - Rollback Segment off-lineINVALID - Rollback Segment Dropped.NEEDS RECOVERY - Contains data but need recovery or corupted.PARTLY AVAILABLE - Contains data from an unresolved transaction involving a distributed database.

310. What is meant by Redo Log file mirroring ? How it can be achieved?

Process of having a copy of redo log files is called mirroring. This can be achieved by creating group of log files

together, so that LGWR will automatically writes them to all the members of the current on-line redo log group.If any one group fails then database automatically switch over to next group. It degrades performance.

311. Which parameter in Storage clause will reduce no. of rows per block?

PCTFREE parameterRow size also reduces no of rows per block.

312. What is meant by recursive hints ?

Number of times processes repeatedly query the dictionary table is called recursive hints. It is due to the datadictionary cache is too small. By increasing the SHARED_POOL_SIZE parameter we can optimize the size of Data Dictionary Cache.

313. What is the use of PARFILE option in EXP command ?

Name of the parameter file to be passed for export.314. What is the use of PARFILE option in EXP command ?

Name of the parameter file to be passed for export.

315. What is a logical backup?

Logical backup involves reading a set of database records and writing them into a file. Export utility is used fortaking backup and Import utility is used to recover from backup.

316. What is the use of TABLES option in EXP command ?

List of tables should be exported.ze)

317. What is the OPTIMAL parameter?

It is used to set the optimal length of a rollback segment.

318. What is a Rollback segment entry ?

It is the set of before image data blocks that contain rows that are modified by a transaction. Each RollbackSegment entry must be completed within one rollback segment. A single rollback segment can have multiplerollback segment entries.

319. What is mean by Program Global Area (PGA) ?

It is area in memory that is used by a Single Oracle User Process.

320. What is hit ratio ?

It is a measure of well the data cache buffer is handling requests for data. Hit Ratio = (Logical Reads - Physical

Reads - Hits Misses)/ Logical Reads.

321. What are the different kind of export backups?

146

Page 147: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 147/225

Full back - Complete databaseIncremental - Only affected tables from last incremental date/full backup date.Cumulative backup - Only affected table from the last cumulative date/full backup date.

322. How free extents are managed in Ver 6.0 and Ver 7.0 ?

Free extents cannot be merged together in Ver 6.0.Free extents are periodically coalesces with the neighboring free extent in Ver 7.0

323. What is the use of RECORD option in EXP command?For Incremental exports, the flag indirects whether a record will be stores data dictionary tables recording theexport.

324. What is the use of ROWS option in EXP command ?

Flag to indicate whether table rows should be exported. If 'N' only DDL statements for the database objects willbe created.

325. What is the use of COMPRESS option in EXP command ?

Flag to indicate whether export should compress fragmented segments into single extents.

326. How will you swap objects into a different table space for an existing database ?

Export the user

Perform import using the command imp system/manager file=export.dmp indexfile=newrite.sql.This will create all definitions into newfile.sql. Drop necessary objects.Run the script newfile.sql after altering the tablespaces.Import from the backup for the necessary objects.

327. How does Space allocation table place within a block ?

Each block contains entries as followsFixed block headerVariable block headerRow Header,row date (multiple rows may exists)PCTEREE (% of free space for row updation in future)

328. What are the factors causing the reparsing of SQL statements in SGA?

Due to insufficient Shared SQL pool size. Monitor the ratio of the reloads takes place while executing SQLstatements. If the ratio is greater than 1 then increase the SHARED_POOL_SIZE. LOGICAL & PHYSICALARCHITECTURE OF DATABASE.

329. What is dictionary cache ?

Dictionary cache is information about the databse objects stored in a data dictionary table.

330. What is a Control file ?

Database overall physical architecture is maintained in a file called control file. It will be used to maintaininternal consistency and guide recovery operations. Multiple copies of control files are advisable.

331. What is Database Buffers ?

Database buffers are cache in the SGA used to hold the data blocks that are read from the data segments in

the database such as tables, indexes and clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides thesize.

332. How will you create multiple rollback segments in a database ?

Create a database which implicitly creates a SYSTEM Rollback Segment in a SYSTEM tablespace. Create aSecond Rollback Segment name R0 in the SYSTEM tablespace. Make new rollback segment available (Aftershutdown, modify init.ora file and Start database) Create other tablespaces (RBS) for rollback segments.Deactivate Rollback Segment R0 and activate the newly created rollback segments.

333. What is cold backup? What are the elements of it?

Cold backup is taking backup of all physical files after normal shutdown of database. We need to take.- All Data files.- All Control files.- All on-line redo log files.- The init.ora file (Optional)

334. What is meant by redo log buffer ?

Changes made to entries are written to the on-line redo log files. So that they can be used in roll forwardoperations during database recoveries. Before writing them into the redo log files, they will first brought toredo log buffers in SGA and LGWR will write into files frequently. LOG_BUFFER parameter will decide the size.

147

Page 148: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 148/225

335. How will you estimate the space required by a non-clustered tables?

Calculate the total header sizeCalculate the available dataspace per data blockCalculate the combined column lengths of the average rowCalculate the total average row size.Calculate the average number rows that can fit in a blockCalculate the number of blocks and bytes required for the table.After arriving the calculation, add 10 % additional space to calculate the initial extent size for a working table.

336. How will you monitor the space allocation ?

By querying DBA_SEGMENT table/view.

337. What is meant by free extent ?

A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents arereallocated and are marked as free.

338. What is the use of IGNORE option in IMP command ?

A flag to indicate whether the import should ignore errors encounter when issuing CREATE commands.

339. What is the use of ANALYSE ( Ver 7) option in EXP command ?

A flag to indicate whether statistical information about the exported objects should be written to export dumpfile.

340. What is the use of ROWS option in IMP command ?

A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for database objects willbe executed.

341. What is the use of INDEXES option in EXP command ?

A flag to indicate whether indexes on tables will be exported.

333. What is cold backup? What are the elements of it?

Cold backup is taking backup of all physical files after normal shutdown of database. We need to take.- All Data files.

- All Control files.- All on-line redo log files.- The init.ora file (Optional)

334. What is meant by redo log buffer ?

Changes made to entries are written to the on-line redo log files. So that they can be used in roll forwardoperations during database recoveries. Before writing them into the redo log files, they will first brought toredo log buffers in SGA and LGWR will write into files frequently. LOG_BUFFER parameter will decide the size.

335. How will you estimate the space required by a non-clustered tables?

Calculate the total header sizeCalculate the available dataspace per data blockCalculate the combined column lengths of the average row

Calculate the total average row size.Calculate the average number rows that can fit in a blockCalculate the number of blocks and bytes required for the table.After arriving the calculation, add 10 % additional space to calculate the initial extent size for a working table.

336. How will you monitor the space allocation ?

By querying DBA_SEGMENT table/view.

337. What is meant by free extent ?

A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents arereallocated and are marked as free.

338. What is the use of IGNORE option in IMP command ?

A flag to indicate whether the import should ignore errors encounter when issuing CREATE commands.

339. What is the use of ANALYSE ( Ver 7) option in EXP command ?

A flag to indicate whether statistical information about the exported objects should be written to export dumpfile.

148

Page 149: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 149/225

340. What is the use of ROWS option in IMP command ?

A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for database objects willbe executed.

341. What is the use of INDEXES option in EXP command ?

A flag to indicate whether indexes on tables will be exported.

342. What is the use of INDEXES option in IMP command ?

A flag to indicate whether import should import index on tables or not.

343. What is the use of GRANT option in EXP command?

A flag to indicate whether grants on databse objects will be exported or not. Value is 'Y' or 'N'.

344. What is the use of GRANT option in IMP command ?

A flag to indicate whether grants on database objects will be imported.

345. What is the use of FULL option in EXP command ?

A flag to indicate whether full databse export should be performed.

346. What is the use of SHOW option in IMP command ?A flag to indicate whether file content should be displayed or not.

347. What is the use of CONSTRAINTS option in EXP command ?

A flag to indicate whether constraints on table need to be exported.

348. What is the use of CONSISTENT (Ver 7) option in EXP command ?

A flag to indicate whether a read consistent version of all the exported objects should be maintained.

349. What are the different methods of backing up oracle database ?

- Logical Backups- Cold Backups

- Hot Backups (Archive log)

350. What is the difference between ON-VALIDATE-FIELD trigger and a POST-CHANGE trigger ?

When you changes the Existing value to null, the On-validate field trigger will fire post change trigger will notfire. At the time of execute-query post-change trigger will fire, on-validate field trigger will not fire.

351. When is PRE-QUERY trigger executed ?

When Execute-query or count-query Package procedures are invoked.

342. What is the use of INDEXES option in IMP command ?

A flag to indicate whether import should import index on tables or not.

343. What is the use of GRANT option in EXP command?

A flag to indicate whether grants on databse objects will be exported or not. Value is 'Y' or 'N'.

344. What is the use of GRANT option in IMP command ?

A flag to indicate whether grants on database objects will be imported.

345. What is the use of FULL option in EXP command ?

A flag to indicate whether full databse export should be performed.

346. What is the use of SHOW option in IMP command ?

A flag to indicate whether file content should be displayed or not.

347. What is the use of CONSTRAINTS option in EXP command ?

A flag to indicate whether constraints on table need to be exported.

348. What is the use of CONSISTENT (Ver 7) option in EXP command ?

A flag to indicate whether a read consistent version of all the exported objects should be maintained.

149

Page 150: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 150/225

349. What are the different methods of backing up oracle database ?

- Logical Backups- Cold Backups- Hot Backups (Archive log)

350. What is the difference between ON-VALIDATE-FIELD trigger and a POST-CHANGE trigger ?

When you changes the Existing value to null, the On-validate field trigger will fire post change trigger will notfire. At the time of execute-query post-change trigger will fire, on-validate field trigger will not fire.

351. When is PRE-QUERY trigger executed ?

When Execute-query or count-query Package procedures are invoked.

342. What is the use of INDEXES option in IMP command ?

A flag to indicate whether import should import index on tables or not.

343. What is the use of GRANT option in EXP command?

A flag to indicate whether grants on databse objects will be exported or not. Value is 'Y' or 'N'.

344. What is the use of GRANT option in IMP command ?

A flag to indicate whether grants on database objects will be imported.

345. What is the use of FULL option in EXP command ?

A flag to indicate whether full databse export should be performed.

346. What is the use of SHOW option in IMP command ?

A flag to indicate whether file content should be displayed or not.

347. What is the use of CONSTRAINTS option in EXP command ?

A flag to indicate whether constraints on table need to be exported.

348. What is the use of CONSISTENT (Ver 7) option in EXP command ?

A flag to indicate whether a read consistent version of all the exported objects should be maintained.

349. What are the different methods of backing up oracle database ?

- Logical Backups- Cold Backups- Hot Backups (Archive log)

350. What is the difference between ON-VALIDATE-FIELD trigger and a POST-CHANGE trigger ?

When you changes the Existing value to null, the On-validate field trigger will fire post change trigger will notfire. At the time of execute-query post-change trigger will fire, on-validate field trigger will not fire.

351. When is PRE-QUERY trigger executed ?

When Execute-query or count-query Package procedures are invoked.

352. How do you trap the error in forms 3.0 ?

using On-Message or On-Error triggers.

353. How many pages you can in a single form ?

Unlimited

354. While specifying master/detail relationship between two blocks specifying the join condition is a must ?True or False. ?

True

355. EXIT_FORM is a restricted package procedure ?a. True b. False

True

356. What is the usage of an ON-INSERT,ON-DELETE and ON-UPDATE TRIGGERS ?

These triggers are executes when inserting, deleting and updating operations are performed and can be usedto change the default function of insert, delete or update respectively. For Eg, instead of inserting a row in atable an existing row can be updated in the same table.

150

Page 151: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 151/225

357. What are the types of Pop-up window ?

the pop-up field editorpop-up list of valuespop-up pages.Alert :

358. What is an SQL *FORMS ?

SQL *forms is 4GL tool for developing and executing; Oracle based interactive application.

359. How do you control the constraints in forms ?

Select the use constraint property is ON Block definition screen.BLOCK

360. What is the difference between restricted and unrestricted package procedure ?

Restricted package procedure that affects the basic functions of SQL * Forms. It cannot used in all triggersexcept key triggers. Unrestricted package procedure that does not interfere with the basic functions of SQL *Forms it can be used in any triggers.

361. A query fetched 10 records How many times does a PRE-QUERY Trigger and POST-QUERY Triggerwill get executed ?

PRE-QUERY fires once.POST-QUERY fires 10 times.

362. Give the sequence in which triggers fired during insert operations, when the following 3 triggers aredefined at the same block level ?

a. ON-INSERT b. POST-INSERT c. PRE-INSERT

363. State the order in which these triggers are executed ?

POST-FIELD,ON-VALIDATE-FIELD,POST-CHANGE and KEY-NEXTFLD. KEY-NEXTFLD,POST-CHANGE, ON-VALIDATE-FIELD, POST-FIELD. g.

364. What the PAUSE package procedure does ?

Pause suspends processing until the operator presses a function key

365. What do you mean by a page ?Pages are collection of display information, such as constant text and graphics

366. What are the type of User Exits ?

ORACLE Precompliers user exitsOCI (ORACLE Call Interface)Non-ORACEL user exits.Page :

367. What is the difference between an ON-VALIDATE-FIELD trigger and a trigger ?

On-validate-field trigger fires, when the field Validation status New or changed. Post-field-trigger whenever thecontrol leaving form the field, it will fire.

368. Can we use a restricted package procedure in ON-VALIDATE-FIELD Trigger ?

No

369. Is a Key startup trigger fires as result of a operator pressing a key explicitly ?

No

370. Can we use GO-BLOCK package in a pre-field trigger ?

No

371. Can we create two blocks with the same name in form 3.0 ?

No

372. What is Post-Block is a. ???a. Navigational Trigger.b. Key triggerc. Transaction Trigger.

151

Page 152: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 152/225

373. What does an on-clear-block Trigger fire?

It fires just before SQL * forms the current block.

374. Name the two files that are created when you generate the form give the filex extension ?

INP (Source File)FRM (Executable File)

375. What package procedure used for invoke sql *plus from sql *forms ?

Host (E.g. Host (sqlplus))

376. What is the significance of PAGE 0 in forms 3.0 ?

Hide the fields for internal calculation.

377. What are the different types of key triggers ?

Function KeyKey-functionKey-othersKey-startup

378. What is the difference between a Function Key Trigger and Key Function Trigger ?

Function key triggers are associated with individual SQL*FORMS function keys You can attach Key functiontriggers to 10 keys or key sequences that normally do not perform any SQL * FORMS operations. These keysreferred as key F0 through key F9.

379. Committed block sometimes refer to a BASE TABLE ?

False

380. Error_Code is a package proecdure ?

a. True b. falseFalse

381. How can you execute the user defined triggers in forms 3.0 ?

Execute Trigger (trigger-name)

382. What ERASE package procedure does ?

Erase removes an indicated global variable.

383. What Enter package procedure does ?

Enter Validate-data in the current validation unit.

384. What is the difference between NAME_IN and COPY ?

Copy is package procedure and writes values into a field.Name in is a package function and returns the contents of the variable to which you apply.

385. What package procedure is used for calling another form ?

Call (E.g. Call(formname)

386. When the form is running in DEBUG mode, If you want to examine the values of global variables andother form variables, What package procedure command you would use in your trigger text ?

Break.SYSTEM VARIABLES

387. The value recorded in system.last_record variable is of typea. Numberb. Booleanc. Character. ?

b. Boolean.

388. What are the unrestricted procedures used to change the popup screen position during run time ?Anchor-viewResize -ViewMove-View.

152

Page 153: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 153/225

389. What is an Alert ?

An alert is window that appears in the middle of the screen overlaying a portion of the current display.

390. Deleting a page removes information about all the fields in that page ? a. True. b. False?

a. True.

391. Two popup pages can appear on the screen at a time ?Two popup pages can appear on thescreen at a time ? a. True. b. False?

a. True.

392. Classify the restricted and unrestricted procedure from the following.a. Callb. User-Exitc. Call-Queryd. Upe. Execute-Queryf. Messageg. Exit-Fromh. Posti. Break?

a. Call - unrestrictedb. User Exit - Unrestrictedc. Call_query - Unrestrictedd. Up - Restrictede. Execute Query - Restrictedf. Message - Restrictedg. Exit_form - Restrictedh. Post - Restrictedi. Break - Unrestricted.

393. What is an User Exits ?

A user exit is a subroutine which are written in programming languages using pro*C pro *Cobol , etc., that linkinto the SQL * forms executable.

394. What is a Trigger ?

A piece of logic that is executed at or triggered by a SQL *forms event.

395. What is a Package Procedure ?

A Package procedure is built in PL/SQL procedure.

398. What is the maximum size of a form ?

255 character width and 255 characters Length.

399. What is the difference between system.current_field and system.cursor_field ?

1. System.current_field gives name of the field.2. System.cursor_field gives name of the field with block name.

400. List the system variables related in Block and Field?

1. System.block_status2. System.current_block3. System.current_field4. System.current_value5. System.cursor_block6. System.cursor_field7. System.field_status.

401. What are the different types of Package Procedure ?

1. Restricted package procedure.2. Unrestricted package procedure.

402. What are the types of TRIGGERS ?

1. Navigational Triggers.

2. Transaction Triggers.

403. Identify package function from the following ? 1. Error-Code2. Break3. Call4. Error-text

153

Page 154: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 154/225

5. Form-failure6. Form-fatal7. Execute-query8. Anchor View9. Message_code?

1. Error_Code2. Error_Text3. Form_Failure4. Form_Fatal

5. Message_Code

403. Can you attach an lov to a field at run-time? if yes, give the build-in name.?

Yes. Set_item_proprety

404. Is it possible to attach same library to more than one form?

Yes

405. Can you attach an lov to a field at design time?

Yes

406. List the windows event triggers available in Forms 4.0?

When-window-activated,when-window-closed,when-window-deactivated,when-window-resized

407. What are the triggers associated with the image item?

When-Image-activated(Fires when the operator double clicks on an image Items)When-image-pressed(fires when the operator selects or deselects the image item)

408. What is a visual attribute?

Visual Attributes are the font, color and pattern characteristics of objects that operators see and intract with inour application.

409. How many maximum number of radio buttons can you assign to a radio group?Unlimited no of radio buttons can be assigned to a radio group

410. How do you pass the parameters from one form to another form?

To pass one or more parameters to a called form, the calling form must perform the following steps in a triggeror user named routine execute the create_parameter_list built-in function to programmatically. Create aparameter list to execute the add parameter built-in procedure to add one or more parameters list. Executethe call_form, New_form or run_product built_in procedure and include the name or id of the parameter list tobe passed to the called form.

411. What is a Layout Editor?

The Layout Editor is a graphical design facility for creating and arranging items and boilerplate text andgraphics objects in your application's interface.

412. List the Types of Items?

Text item.Chart item.Check box.Display item.Image item.List item.Radio Group.User Area item.

413. List system variables available in forms 4.0, and not available in forms 3.0?

System.cordination_operationSystem Date_threshold

System.effective_DateSystem.event_windowSystem.suppress_working

414. What are the display styles of an alert?

Stop, Caution, note

154

Page 155: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 155/225

415. What built-in is used for showing the alert during run-time?

Show_alert.

416. What built-in is used for changing the properties of the window dynamically?

Set_window_propertyCanvas-View

417. What are the different types of windows?

Root window, secondary window.

418. What is a predefined exception available in forms 4.0?

Raise form_trigger_failure

419. What is a radio Group?

Radio groups display a fixed no of options that are mutually Exclusive. User can select one out of n number of options.

419. What are the different type of a record group?

Query record groupStatic record groupNon query record group

420. What are the menu items that oracle forms 4.0 supports?

Plain, Check,Radio, Separator, Magic

421. Give the equivalent term in forms 4.0 for the following. Page, Page 0?

Page - Canvas-ViewPage 0 - Canvas-view null.

422. What triggers are associated with the radio group?

Only when-radio-changed trigger associated with radio groupVisual Attributes.

423. What are the triggers associated with a check box?

Only When-checkbox-activated Trigger associated with a Check box.

424.Can you attach an alert to a field?

No

425. Can a root window be made modal?

No

426. What is a list item?

It is a list of text elements.

427. List some built-in routines used to manipulate images in image_item?

Image_addImage_andImage_subtractImage_xorImage_zoom

428. Can you change the alert messages at run-time?

If yes, give the name of the built-in to change the alert messages at run-time. Yes. Set_alert_property.

429. What is the built-in used to get and set lov properties during run-time?

Get_lov_property

Set_lov_propertyRecord Group

430. What is the built-in routine used to count the no of rows in a group?

Get_group _row_countSystem Variables

155

Page 156: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 156/225

431. Give the Types of modules in a form?

FormMenuLibrary

432. Write the Abbreviation for the following File Extension 1. FMB 2. MMB 3. PLL?

FMB ----- Form Module Binary.

MMB ----- Menu Module Binary.PLL ------ PL/SQL Library Module Binary.

433. List the built-in routine for controlling window during run-time?

Find_window,get_window_property,hide_window,move_window,resize_window,set_window_property,show_View

434. List the built-in routine for controlling window during run-time?

Find_canvasGet-Canvas_propertyGet_view_propertyHide_ViewReplace_content_viewScroll_viewSet_canvas_propertySet_view_propertyShow_viewAlert

435. What is the built-in function used for finding the alert?

Find_alertEditors

436. List the editors availables in forms 4.0?

Default editorUser_defined editorssystem editors.

437. What buil-in routines are used to display editor dynamicaly?

Edit_text itemshow_editor

438. What is an Lov?

A list of values is a single or multi column selection list displayed in a pop-up window

439. What is a record Group?

A record group is an internal oracle forms data structure that has a similar column/row frame work to adatabase table

440. Give built-in routine related to a record groups?

Create_group (Function)Create_group_from_query(Function)Delete_group(Procedure)Add_group_column(Function)Add_group_row(Procedure)Delete_group_row(Procedure)Populate_group(Function)Populate_group_with_query(Function)Set_group_Char_cell(procedure)

441. List the built-in routines for the controlling canvas views during run-time?

Find_canvasGet-Canvas_propertyGet_view_propertyHide_View

156

Page 157: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 157/225

Replace_content_viewScroll_viewSet_canvas_propertySet_view_propertyShow_viewAlert

442. System.effective_date system variable is read only True/False?

False

443. What are the built_in used to trapping errors in forms 4?

Error_type return characterError_code return numberError_text return charDbms_error_code return no.Dbms_error_text return char

444. what is a display item?

Display items are similar to text items but store only fetched or assigned values. Operators cannot navigate toa display item or edit the value it contains.

445. What are the design facilities available in forms 4.0?

Default Block facility.Layout Editor.Menu Editor.Object Lists.Property Sheets.PL/SQL Editor.Tables Columns Browser.Built-ins Browser.

446. What are the types of visual attribute settings?

Custom Visual attributes Default visual attributes Named Visual attributes. Window

447. What are the types of canvas-views?

Content View, Stacked View.

448. What are the two ways to incorporate images into a oracle forms application?

Boilerplate ImagesImage_items

449. What do you mean by a block in forms4.0?

Block is a single mechanism for grouping related items into a functional unit for storing, displaying andmanipulating records.

450. Explain types of Block in forms4.0?

Base table Blocks.Control Blocks.

1. A base table block is one that is associated with a specific database table or view.2. A control block is a block that is not associated with a database table. ITEMS

451. What is an Alert?

An alert is a modal window that displays a message notifies the operator of some application condition

455. What are the built-in routines is available in forms 4.0 to create and manipulate a parameter list?

Add_parameterCreate_Parameter_listDelete_parameterDestroy_parameter_listGet_parameter_attrGet_parameter_listset_parameter_attr

456 .What is a record Group?

A record group is an internal oracle forms data structure that has a similar column/row frame work to adatabase table

457 What is a Navigable item?

157

Page 158: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 158/225

A navigable item is one that operators can navigate to with the keyboard during default navigation, or thatOracle forms can navigate to by executing a navigational built-in procedure.

458. What is a library in Forms 4.0?

A library is a collection of Pl/SQL program units, including user named procedures, functions & packages

460. How image_items can be populate to field in forms 4.0?

A fetch from a long raw database column PL/Sql assignment to executing the read_image_file built_inprocedure to get an image from the file system.

461. What is the content view and stacked view?

A content view is the "Base" view that occupies the entire content pane of the window in which it is displayed.A stacked view differs from a content canvas view in that it is not the base view for the window to which it isassigned

462. What is a Check Box?

A Check Box is a two state control that indicates whether a certain condition or value is on or off, true or false.The display state of a check box is always either "checked" or "unchecked".

463. What is a canvas-view?

A canvas-view is the background object on which you layout the interface items (text-items, check boxes,

radio groups, and so on.) and boilerplate objects that operators see and interact with as they run your form. Atrun-time, operators can see only those items that have been assigned to a specific canvas. Each canvas, interm, must be displayed in a specific window.

464. Explain the following file extension related to library?

.pll,.lib,.pldThe library pll files is a portable design file comparable to an fmb form fileThe library lib file is a plat form specific, generated library file comparable to a fmx form fileThe pld file is Txt format file and can be used for source controlling your library files Parameter

465. Explain the usage of WHERE CURRENT OF clause in cursors ?

WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row fetched from a cursor.Database Triggers

466. Name the tables where characteristics of Package, procedure and functions are stored ?

User_objects, User_Source and User_error.

467. Explain the two type of Cursors ?

There are two types of cursors, Implicit Cursor and Explicit Cursor. PL/SQL uses Implicit Cursors for queries.User defined cursors are called Explicit Cursors. They can be declared and used.

468. What are two parts of package ?

The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package Specification containsdeclarations that are global to the packages and local to the schema. Package Body contains actual proceduresand local declaration of the procedures and cursor declarations.

469. What are two virtual tables available during database trigger execution ?

The table columns are referred as OLD.column_name and NEW.column_name.For triggers related to INSERT only NEW.column_name values only available.For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.For triggers related to DELETE only OLD.column_name values only available.

470. What is Overloading of procedures ?

The Same procedure name is repeated with parameters of different datatypes and parameters in differentpositions, varying number of parameters is called overloading of procedures. e.g. DBMS_OUTPUT put_line

471. What is a package ? What are the advantages of packages ? What is Pragma EXECPTION_INIT ? Explainthe usage ?

The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To get an errormessage of a specific oracle error. e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)

472. What are the return values of functions SQLCODE and SQLERRM ? What is Pragma EXECPTION_INIT ?Explain the usage ?

SQLCODE returns the latest code of the error that has occurred.SQLERRM returns the relevant error message of the SQLCODE.

158

Page 159: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 159/225

473. What are the datatypes a available in PL/SQL ?

Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN. Some composite datatypes such as RECORD & TABLE.

474. What is Raise_application_error ?

Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an user_definederror messages from stored sub-program or database trigger.

475. What are the two parts of a procedure ?

Procedure Specification and Procedure Body.

476. Give the structure of the procedure ?

PROCEDURE name (parameter list.....)islocal variable declarationsBEGINExecutable statements.Exception.exception handlersend;

477. What is the basic structure of PL/SQL ?

PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in PL/SQL.

478. Question What is PL/SQL ?

PL/SQL is a procedural language that has both interactive SQL and procedural programming languageconstructs such as iteration, conditional branching.

479. What is PL/SQL table ?

Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as) database tables,PL/SQL tables use a primary PL/SQL tables can have one column and a primary key. Cursors

480. What happens if a procedure that updates a column of table X is called in a database trigger of 

the same table ?Mutation of table occurs.

481. Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ?Why ?

It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a trigger, it affectslogical transaction processing.

482. How many types of database triggers can be specified on a table ? What are they ?

Insert Update DeleteBefore Row o.k. o.k. o.k.After Row o.k. o.k. o.k.Before Statement o.k. o.k. o.k.

After Statement o.k. o.k. o.k.If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.If WHEN clause is specified, the trigger fires according to the returned Boolean value.

483. What are the modes of parameters that can be passed to a procedure ?

IN,OUT,IN-OUT parameters.

484. Where the Pre_defined_exceptions are stored ?

In the standard package.Procedures, Functions & Packages ;

485. Write the order of precedence for validation of a column in a table ?I. done using Database triggers.

ii. done using Integarity Constraints.?I & ii.

486. Give the structure of the function ?

159

Page 160: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 160/225

FUNCTION name (argument list .....) Return datatype islocal variable declarationsBeginexecutable statementsExceptionexecution handlersEnd;

487. Explain how procedures and functions are called in a PL/SQL block ?

Function is called as part of an expression.sal := calculate_sal ('a822');procedure is called as a PL/SQL statementcalculate_bonus ('A822');

488. What are advantages fo Stored Procedures?

Extensibility,Modularity, Reusability, Maintainability and one time compilation.

489. What is an Exception ? What are types of Exception ?

Exception is the error handling part of PL/SQL block. The types are Predefined and user defined. Some of Predefined exceptions are.CURSOR_ALREADY_OPENDUP_VAL_ON_INDEX

NO_DATA_FOUNDTOO_MANY_ROWSINVALID_CURSORINVALID_NUMBERLOGON_DENIEDNOT_LOGGED_ONPROGRAM-ERRORSTORAGE_ERRORTIMEOUT_ON_RESOURCEVALUE_ERRORZERO_DIVIDEOTHERS.

490. What are the PL/SQL Statements used in cursor processing ?

DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor

name.

491. What are the components of a PL/SQL Block ?

Declarative part, Executable part and Exception part.Datatypes PL/SQL

492. What is a database trigger ? Name some usages of database trigger ?

Database trigger is stored PL/SQL program unit associated with a specific database table. Usages are Auditdata modifications, Log events transparently, Enforce complex business rules Derive column valuesautomatically, Implement complex security authorizations. Maintain replicate tables.

493. What is a cursor ? Why Cursor is required ?

Cursor is a named private SQL area from where information can be accessed. Cursors are required to process

rows individually for queries returning multiple rows.

494. What is a cursor for loop ?

Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values from activeset into fields in the record and closes when all the records have been processed.eg. FOR emp_rec IN C1 LOOPsalary_total := salary_total +emp_rec sal;END LOOP;

495. What will happen after commit statement ?

Cursor C1 isSelect empno,ename from emp;

Beginopen C1; loopFetch C1 intoeno.ename;Exit WhenC1 %notfound;-----commit;

160

Page 161: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 161/225

end loop;end;The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLBACK.The cursor having query as SELECT.... does not get closed even after COMMIT/ROLLBACK.

496. How packaged procedures and functions are called from the following?a. Stored procedure or anonymous blockb. an application program such a PRC *C, PRO* COBOLc. SQL *PLUS??

a. PACKAGE NAME.PROCEDURE NAME (parameters);variable := PACKAGE NAME.FUNCTION NAME (arguments);EXEC SQL EXECUTEb.BEGINPACKAGE NAME.PROCEDURE NAME (parameters)variable := PACKAGE NAME.FUNCTION NAME (arguments);END;END EXEC;c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out parameters. Afunction can not be called.

497. What is a stored procedure ?

A stored procedure is a sequence of statements that perform specific function.

498. What are the components of a PL/SQL block ?

A set of related declarations and procedural statements is called block.

499. What is difference between a PROCEDURE & FUNCTION ?

A FUNCTION is always returns a value using the return statement.A PROCEDURE may return one or more values through parameters or may not return at all.

500. What is difference between a Cursor declared in a procedure and Cursor declared in a packagespecification ?

A cursor declared in a package specification is global and can be accessed by other procedures or procedures ina package.A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures.

501. What are the cursor attributes used in PL/SQL ?%ISOPEN - to check whether cursor is open or not% ROWCOUNT - number of rows fetched/updated/deleted.% FOUND - to check whether cursor has fetched any row. True if rows are fetched.% NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched.These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit Cursors.

502. What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?

% TYPE provides the data type of a variable or a database column to that variable.% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in thecursor.The advantages are :I. Need not know about variable's data typeii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.

503. What is difference between % ROWTYPE and TYPE RECORD ?

% ROWTYPE is to be used whenever query returns a entire row of a table or view.TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables.E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type );e_rec emp% ROWTYPEcursor c1 is select empno,deptno from emp;e_rec c1 %ROWTYPE.

504. What are the different types of PL/SQL program units that can be defined and stored in ORACLEdatabase ?

Procedures and Functions,Packages and Database Triggers.

505. What are the advantages of having a Package ?Increased functionality (for example,global package variables can be declared and used by any proecdure inthe package) and performance (for example all objects of the package are parsed compiled, and loaded intomemory once)

161

Page 162: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 162/225

506. What are the uses of Database Trigger ?

Database triggers can be used to automatic data generation, audit data modifications, enforce complexIntegrity constraints, and customize complex security authorizations.

507. What is a Procedure ?

A Procedure consist of a set of SQL and PL/SQL statements that are grouped together as a unit to solve aspecific problem or perform a set of related tasks.

508. What is a Package ?A Package is a collection of related procedures, functions, variables and other package constructs together as aunit in the database.

509. What is difference between Procedures and Functions ?

A Function returns a value to the caller where as a Procedure does not.

510. What is Database Trigger ?

A Database Trigger is procedure (set of SQL and PL/SQL statements) that is automatically executed as a resultof an insert in,update to, or delete from a table.

511. Can the default values be assigned to actual parameters?

Yes

512. Can a primary key contain more than one columns?

Yes

513. What is an UTL_FILE.What are different procedures and functions associated with it?

UTL_FILE is a package that adds the ability to read and write to operating system files. Procedures associatedwith it are FCLOSE, FCLOSE_ALL and 5 procedures to output data to a file PUT, PUT_LINE, NEW_LINE, PUTF,FFLUSH.PUT, FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions associated with it are FOPEN, ISOPEN.

514. What are ORACLE PRECOMPILERS?

Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can be contained inside 3GL programswritten in C,C++,COBOL,PASCAL, FORTRAN,PL/1 AND ADA. The Precompilers are known as

Pro*C,Pro*Cobol,... This form of PL/SQL is known as embedded pl/sql,the language in which pl/sql isembedded is known as the host language. The prcompiler translates the embedded SQL and pl/sql ststementsinto calls to the precompiler runtime library.The output must be compiled and linked with this library to createran executable.

515. Differentiate between TRUNCATE and DELETE?

TRUNCATE deletes much faster than DELETETRUNCATEDELETEIt is a DDL statementIt is a DML statementIt is a one way trip,cannot ROLLBACKOne can RollbackDoesn't have selective features (where clause)HasDoesn't fire database triggersDoesIt requires disabling of referential constraints.

516. What is difference between a formal and an actual parameter?

The variables declared in the procedure and which are passed, as arguments are called actual, the parametersin the procedure declaration. Actual parameters contain the values that are passed to a procedure and receiveresults. Formal parameters are the placeholders for the values of actual parameters

517. What should be the return type for a cursor variable.Can we use a scalar data type as returntype?

The return type for a cursor must be a record type.It can be declared explicitly as a user-defined or%ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSOR RETURN students%ROWTYPE

518. What are different Oracle database objects?

-TABLES-VIEWS-INDEXES-SYNONYMS

162

Page 163: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 163/225

-SEQUENCES-TABLESPACES etc

519. What is difference between SUBSTR and INSTR?

SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDE INSTR provides characterposition in which a pattern is found in a string. eg INSTR('ABC-DC-F','-',2) output 7 (2nd occurence of '-')

520. Display the number value in Words?

SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))from emp;the output like,SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))--------- ----------------------------------------800 eight hundred1600 one thousand six hundred1250 one thousand two hundred fiftyIf you want to add some text like, Rs. Three Thousand only.SQL> select sal "Salary ",(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))"Sal in Words" from emp

 /Salary Sal in Words------- -----------------------------------------------

800 Rs. Eight Hundred only.1600 Rs. One Thousand Six Hundred only.1250 Rs. One Thousand Two Hundred Fifty only.

521. What is difference between SQL and SQL*PLUS?

SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its acommand line tool that allows user to type SQL commands to be executed directly against an Oracle database.SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used toformat query result, Set options, Edit SQL commands and PL/SQL.

522. What are various joins used while writing SUBQUERIES?

Self join-Its a join foreign key of a table references the same table. Outer Join--Its a join condition used whereOne can query all the rows of one of the tables in the join condition even though they don't satisfy the join

condition.Equi-join--Its a join condition that retrieves rows from one or more tables in which one or more columns in onetable are equal to one or more columns in the second table.

523. What a SELECT FOR UPDATE cursor represent.?

SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT]The processing done in a fetch loop modifies the rows that have been retrieved by the cursor. A convenientway of modifying the rows is done by a method with two parts: the FOR UPDATE clause in the cursordeclaration, WHERE CURRENT OF CLAUSE in an UPDATE or declaration statement.

524. What are various privileges that a user can grant to another user?

-SELECT-CONNECT-RESOURCES

525. Display the records between two range?

select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum <=&uptominus select rowid from emp where rownum<&Start);

526. minvalue.sql Select the Nth lowest value from a table?

select level, min('col_name') from my_table where level = '&n' connect by prior ('col_name') < 'col_name')group by level;Example:Given a table called emp with the following columns:-- id number-- name varchar2(20)-- sal number

---- For the second lowest salary:-- select level, min(sal) from emp-- where level=2-- connect by prior sal < sal-- group by level

163

Page 164: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 164/225

527. What is difference between Rename and Alias?

Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a tableor column which do not exist once the SQL statement is executed.

528. Difference between an implicit & an explicit cursor.?

only one row. However,queries that return more than one row you must declare an explicit cursor or use acursor FOR loop. Explicit cursor is a cursor in which the cursor name is explicitly assigned to a SELECTstatement via the CURSOR...IS statement. An implicit cursor is used for all SQL statements Declare, Open,

Fetch, Close. An explicit cursors are used to process multirow SELECT statements An implicit cursor is used toprocess INSERT, UPDATE, DELETE and single row SELECT. .INTO statements.

529. What is a OUTER JOIN?

Outer Join--Its a join condition used where you can query all the rows of one of the tables in the join conditioneven though they don’t satisfy the join condition.

530. What is a cursor?

Oracle uses work area to execute SQL statements and store processing information PL/SQL construct called acursor lets you name a work area and access its stored information A cursor is a mechanism used to fetchmore than one row in a Pl/SQl block.

531. What is the purpose of a cluster?

Oracle does not allow a user to specifically locate tables, since that is a part of the function of the RDBMS.However, for the purpose of increasing performance, oracle allows a developer to create a CLUSTER. ACLUSTER provides a means for storing data from different tables together for faster retrieval than if the tableplacement were left to the RDBMS.

532. What is OCI. What are its uses?

Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No precompiler isrequired,PL/SQL blocks are executed like other DML statements.The OCI library provides--functions to parse SQL statemets--bind input variables--bind output variables--execute statements--fetch the results

533. How you open and close a cursor variable.Why it is required?

OPEN cursor variable FOR SELECT...StatementCLOSE cursor variable In order to associate a cursor variable with a particular SELECT statement OPEN syntaxis used. In order to free the resources used for the query CLOSE statement is used.

534. Display Odd/ Even number of records?

Odd number of records:select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);Output:-135

Even number of records:select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)Output:-246

535. What are various constraints used in SQL?

-NULL-NOT NULL-CHECK

536. Can cursor variables be stored in PL/SQL tables.If yes how. If not why?

No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL table.

537. Difference between NO DATA FOUND and %NOTFOUND?

NO DATA FOUND is an exception raised only for the SELECT....INTO statements when the where clause of thequerydoes not match any rows. When the where clause of the explicit cursor does not match any rows the%NOTFOUND attribute is set to TRUE instead.

164

Page 165: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 165/225

538. Can you use a commit statement within a database trigger?

No

539. What WHERE CURRENT OF clause does in a cursor?

LOOPSELECT num_credits INTO v_numcredits FROM classesWHERE dept=123 and course=101;UPDATE students

FHKO;;;;;;;;;SET current_credits=current_credits+v_numcreditsWHERE CURRENT OF X;

540. There is a string 120000 12 0 .125 , how you will find the position of the decimal place?

INSTR('120000 12 0 .125',1,'.')output 13

541. What are different modes of parameters used in functions and procedures?

-IN -OUT -INOUT

542. How you were passing cursor variables in PL/SQL 2.2?

In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because the storage for a cursorvariable has to be allocated using Pro*C or OCI with version 2.2, the only means of passing a cursor variable to

a PL/SQL block is via bind variable or a procedure parameter.

543. When do you use WHERE clause and when do you use HAVING clause?

HAVING clause is used when you want to specify a condition for a group function and it is written after GROUPBY clause. The WHERE clause is used when you want to specify a condition for columns, single row functionsexcept group functions and it is written before GROUP BY clause if it is used.

544. Difference between procedure and function.?

Functions are named PL/SQL blocks that return a value and can be called with arguments procedure a namedblock that can be called with parameter. A procedure all is a PL/SQL statement by itself, while a Function call iscalled as part of an expression.

545. Which is more faster - IN or EXISTS?

EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.

546. What is syntax for dropping a procedure and a function .Are these operations possible?

Drop Procedure procedure_nameDrop Function function_name

547. How will you delete duplicating rows from a base table?

delete from table_name where rowid not in (select max(rowid) from table group byduplicate_values_field_name); or delete duplicate_values_field_name dv from table_name ta where rowid<(select min(rowid) from table_name tb where ta.dv=tb.dv);

548. Difference between database triggers and form triggers?

-Data base trigger(DBT) fires when a DML operation is performed on a data base table. Form trigger(FT) Fires

when user presses a key or navigates between fields on the screen-Can be row level or statement level No distinction between row level and statement level.-Can manipulate data stored in Oracle tables via SQL Can manipulate data in Oracle tables as well as variablesin forms.-Can be fired from any session executing the triggering DML statements. Can be fired only from the form thatdefine the trigger.-Can cause other database triggers to fire.Can cause other database triggers to fire, but not other formtriggers.

549. What is a cursor for loop?

Cursor For Loop is a loop where oracle implicitly declares a loop variable, the loop index that of the samerecord type as the cursor's record.

550. How you will avoid duplicating records in a query?

By using DISTINCT

551. What is a view ?

A view is stored procedure based on one or more tables, it’s a virtual table.

165

Page 166: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 166/225

552. What is difference between UNIQUE and PRIMARY KEY constraints?

A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. The columns thatcompose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is notautomatically defined to be mandatory must also specify the column is NOT NULL.

553. What is use of a cursor variable? How it is defined?

A cursor variable is associated with different statements at run time, which can hold different values at runtime. Static cursors can only be associated with one run time query. A cursor variable is reference type (like a

pointer in C).Declaring a cursor variable:TYPE type_name IS REF CURSOR RETURN return_type type_name is the name of the referencetype,return_type is a record type indicating the types of the select list that will eventually be returned by thecursor variable.

554. How do you find the numbert of rows in a Table ?

A bad answer is count them (SELECT COUNT(*) FROM table_name)A good answer is :-'By generating SQL to ANALYZE TABLE table_name COUNT STATISTICS by querying Oracle System Catalogues(e.g. USER_TABLES or ALL_TABLES).The best answer is to refer to the utility which Oracle released which makes it unnecessary to do ANALYZETABLE for each Table individually.

555. What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?

1,000,00

556. What are cursor attributes?

-%ROWCOUNT-%NOTFOUND-%FOUND-%ISOPEN

557. There is a % sign in one field of a column. What will be the query to find it?

'' Should be used before '%'.

558. What is ON DELETE CASCADE ?

When ON DELETE CASCADE is specified ORACLE maintains referential integrity by automatically removingdependent foreign key values if a referenced primary or unique key value is removed.

559. What is the fastest way of accessing a row in a table ?

Using ROWID.CONSTRAINTS

560. What is difference between TRUNCATE & DELETE ?

TRUNCATE commits after deleting entire table i.e., can not be rolled back. Database triggers do not fire onTRUNCATEDELETE allows the filtered deletion. Deleted records can be rolled back or committed.Databasetriggers fire on DELETE.

561. What is a transaction ?

Transaction is logical unit between two commits and commit and rollback.

562. What are the advantages of VIEW ?

To protect some of the columns of a table from other users.To hide complexity of a query.To hide complexity of calculations.

563. How will you a activate/deactivate integrity constraints ?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE constraint/DISABLE constraint.

564. Where the integrity constraints are stored in Data Dictionary ?

The integrity constraints are stored in USER_CONSTRAINTS.

565. What is the Subquery ?

566. How to access the current value and next value from a sequence ? Is it possible to access the currentvalue in a session before accessing next value ?

Sequence name CURRVAL, Sequence name NEXTVAL.It is not possible. Only if you access next value in thesession, current value can be accessed.

166

Page 167: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 167/225

567. What are the usage of SAVEPOINTS ?value in a session before accessing next value ?

SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of atransaction. Maximum of five save points are allowed.

568. What is ROWID ?in a session before accessing next value ?

ROWID is a pseudo column attached to each row of a table. It is 18 character long, blockno, rownumber arethe components of ROWID.

569. Explain Connect by Prior ?in a session before accessing next value ?Retrieves rows in hierarchical order.e.g. select empno, ename from emp where.

570. How many LONG columns are allowed in a table ? Is it possible to use LONG columns in WHERE clause orORDER BY ?

Only one LONG columns is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

571. What is Referential Integrity ?

Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tablesbased on the values of primary key or unique key of the referenced table.

572. What is a join ? Explain the different types of joins ?

Join is a query which retrieves related columns or rows from multiple tables.Self Join - Joining the table withitself.Equi Join - Joining two tables by equating two common columns.Non-Equi Join - Joining two tables byequating two common columns.Outer Join - Joining two tables in such a way that query can also retrieve rowsthat do not have corresponding join value in the other table.

573. If an unique key constraint on DATE column is created, will it validate the rows that are inserted withSYSDATE ?

It won't, Because SYSDATE format contains time attached with it.

574. Explain UNION,MINUS,UNION ALL, INTERSECT ?

INTERSECT returns all distinct rows selected by both queries.MINUS - returns all distinct rows selected by thefirst query but not by the second.UNION - returns all distinct rows selected by either queryUNION ALL - returnsall rows selected by either query, including all duplicates.

575. What is an Integrity Constraint ?Integrity constraint is a rule that restricts values to a column in a table.

576. Difference between SUBSTR and INSTR ?

INSTR (String1,String2(n,(m)),INSTR returns the position of the mth occurrence of the string 2 instring1. Thesearch begins from nth position of string1.SUBSTR (String1 n,m)SUBSTR returns a character string of size m instring1, starting from nth position of string1.

577. If a View on a single base table is manipulated will the changes be reflected on the base table ?

If changes are made to the tables which are base tables of a view will the changes be reference on the view.

578. What are the pre requisites ?

I. to modify data type of a column ? ii. to add a column with NOT NULL constraint ? To Modify the datatype of acolumn the column must be empty. to add a column with NOT NULL constrain, the table must be empty.

579. What is a database link ?

Database Link is a named path through which a remote database can be accessed.

580. What are the types of SQL Statement ?

Data Definition Language :CREATE,ALTER,DROP,TRUNCATE,REVOKE,NO AUDIT & COMMIT.

Data Manipulation Language:INSERT,UPDATE,DELETE,LOCK

TABLE,EXPLAIN PLAN & SELECT.Transactional Control:COMMIT & ROLLBACKSession Control: ALTERSESSION & SET

ROLESystem Control :ALTER SYSTEM.

167

Page 168: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 168/225

581. What is CYCLE/NO CYCLE in a Sequence ?

CYCLE specifies that the sequence continues to generate values after reaching either maximum or minimumvalue. After pan ascending sequence reaches its maximum value, it generates its minimum value. After adescending sequence reaches its minimum, it generates its maximum.NO CYCLE specifies that the sequencecannot generate more values after reaching its maximum or minimum value.

582. What is correlated sub-query ?

Correlated sub query is a sub query which has reference to the main query.

583. What are the data types allowed in a table ?

CHAR,VARCHAR2,NUMBER,DATE,RAW,LONG and LONG RAW.

584. What is difference between CHAR and VARCHAR2 ? What is the maximum SIZE allowed for each type ?

CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR it is 255and 2000 for VARCHAR2.

586. What are the different types of Coordinations of the Master with the Detail block?

POPULATE_GROUP(function)POPULATE_GROUP_WITH_QUERY(function)SET_GROUP_CHAR_CELL(procedure)SET_GROUPCELL(procedure)SET_GROUP_NUMBER_CELL(procedure)

587. Use the ADD_GROUP_COLUMN function to add a column to a record group that was created at designtime? I) TRUE II)FALSE

II) FALSE

588. Use the ADD_GROUP_ROW procedure to add a row to a static record group? I) TRUE II)FALSE

I) FALSE

589. maxvalue.sql Select the Nth Highest value from a table?

select level, max('col_name') from my_table where level = '&n' connect by prior ('col_name') > 'col_name')group by level;Example:Given a table called emp with the following columns:-- id number-- name varchar2(20)-- sal number---- For the second highest salary:-- select level, max(sal) from emp-- where level=2-- connect by prior sal > sal-- group by level

590. Find out nth highest salary from emp table?

SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHEREa.sal<=b.sal);For Eg:-

Enter value for n: 2SAL---------3700

591. Suppose a customer table is having different columns like customer no, payments.What will be the queryto select top three max payments?

SELECT customer_no, payments from customer C1WHERE 3<=(SELECT COUNT(*) from customer C2WHERE C1.payment <= C2.payment)

592. How you will avoid your query from using indexes?

SELECT * FROM emp

Where emp_no+' '=12345;i.e you have to concatenate the column name with space within codes in the where condition.SELECT /*+ FULL(a) */ ename, emp_no from empwhere emp_no=1234;i.e using HINTS

168

Page 169: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 169/225

593. What utility is used to create a physical backup?

Either rman or alter tablespace begin backup will do..

594. What are the Back ground processes in Oracle and what are they.

This is one of the most frequently asked question.There are basically 9 Processes but in a general system weneed to mention the first five background processes.They do the house keeping activities for the Oracle andare common in any system.The various background processes in oracle area) Data Base Writer(DBWR) :: Data Base Writer Writes Modified blocks from Database buffer cache to DataFiles.This is required since the data is not written whenever a transaction is commited.b)LogWriter(LGWR) :: LogWriter writes the redo log entries to disk. Redo Log data is generated in redo logbuffer of SGA. As transaction commits and log buffer fills, LGWR writes log entries into a online redo log file.c) System Monitor(SMON) :: The System Monitor performs instance recovery at instance startup.This is usefulfor recovery from system failured)Process Monitor(PMON) :: The Process Monitor peforms process recovery when user Process fails. PmonClears and Frees resources that process was using.e) CheckPoint(CKPT) :: At Specified times, all modified database buffers in SGA are written to data files byDBWR at Checkpoints and Updating all data files and control files of database to indicate the most recentcheckpointf)Archieves(ARCH) :: The Archiver copies online redo log files to archival storal when they are busy.g) Recoveror(RECO) :: The Recoveror is used to resolve the distributed transaction in networkh) Dispatcher (Dnnn) :: The Dispatcher is useful in Multi Threaded Architecturei) Lckn :: We can have upto 10 lock processes for inter instance locking in parallel sql.

595. How many types of Sql Statements are there in OracleThere are basically 6 types of sql statments.They area) Data Defination Language(DDL) :: The DDL statments define and maintain objects and drop objects.b) Data Manipulation Language(DML) :: The DML statments manipulate database data.c) Transaction Control Statements :: Manage change by DMLd) Session Control :: Used to control the properties of current session enabling and disabling roles andchanging .e.g :: Alter Statements,Set Rolee) System Control Statements :: Change Properties of Oracle Instance .e.g:: Alter Systemf) Embedded Sql :: Incorporate DDL,DML and T.C.S in Programming Language.e.g:: Using the Sql Statementsin languages such as 'C', Open,Fetch, execute and close

596. What is a Transaction in Oracle

A transaction is a Logical unit of work that compromises one or more SQL Statements executed by a singleUser. According to ANSI, a transaction begins with first executable statment and ends when it is explicitly

commited or rolled back.

597. Key Words Used in Oracle

The Key words that are used in Oracle are ::a) Commiting :: A transaction is said to be commited when the transaction makes permanent changesresulting from the SQL statements.b) Rollback :: A transaction that retracts any of the changes resulting from SQL statements in Transaction.c) SavePoint :: For long transactions that contain many SQL statements, intermediate markers or savepointsare declared. Savepoints can be used to divide a transactino into smaller points.d) Rolling Forward :: Process of applying redo log during recovery is called rolling forward.e) Cursor :: A cursor is a handle ( name or a pointer) for the memory associated with a specific stament. Acursor is basically an area allocated by Oracle for executing the Sql Statement. Oracle uses an implicit cursorstatement for Single row query and Uses Explcit cursor for a multi row query.f) System Global Area(SGA) :: The SGA is a shared memory region allocated by the Oracle that contains Dataand control information for one Oracle Instance.It consists of Database Buffer Cache and Redo log Buffer.g) Program Global Area (PGA) :: The PGA is a memory buffer that contains data and control information forserver process.g) Database Buffer Cache :: Databese Buffer of SGA stores the most recently used blocks of datatbasedata.The set of database buffers in an instance is called Database Buffer Cache.h) Redo log Buffer :: Redo log Buffer of SGA stores all the redo log entries.i) Redo Log Files :: Redo log files are set of files that protect altered database data in memory that has notbeen written to Data Files. They are basically used for backup when a database crashes.

 j) Process :: A Process is a 'thread of control' or mechansim in Operating System that executes series of steps.

585. Can a view be updated/inserted/deleted? If Yes under what conditions ?

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from oneor more tables then insert, update and delete is not possible.

603. What are the Different Optimisation Techniques

The Various Optimisation techniques area) Execute Plan :: we can see the plan of the query and change it accordingly based on the indexesb) Optimizer_hint ::set_item_property('DeptBlock',OPTIMIZER_HINT,'FIRST_ROWS');Select /*+ First_Rows */ Deptno,Dname,Loc,Rowid from deptwhere (Deptno > 25)c) Optimize_Sql ::

169

Page 170: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 170/225

By setting the Optimize_Sql = No, Oracle Forms assigns a single cursor for all SQL statements.This slow downsthe processing because for evertime the SQL must be parsed whenver they are executed.f45run module = my_firstform userid = scott/tiger optimize_sql = Nod) Optimize_Tp ::By setting the Optimize_Tp= No, Oracle Forms assigns seperate cursor only for each query SELECT statement.All other SQL statements reuse the cursor.f45run module = my_firstform userid = scott/tiger optimize_Tp = No

604. How do u implement the If statement in the Select Statement

We can implement the if statement in the select statement by using the Decode statement. e.g select DECODE(EMP_CAT,'1','First','2','Second'Null); Here the Null is the else statement where null is done .

605. How many types of Exceptions are there

There are 2 types of exceptions. They area) System Exceptionse.g. When no_data_found, When too_many_rowsb) User Defined Exceptionse.g. My_exception exceptionWhen My_exception then

606. What are the inline and the precompiler directives

The inline and precompiler directives detect the values directly

607. How do you use the same lov for 2 columns

We can use the same lov for 2 columns by passing the return values in global values and using the globalvalues in the code

608. How many minimum groups are required for a matrix report

The minimum number of groups in matrix report are 4

609. What is the difference between static and dynamic lov

The static lov contains the predetermined values while the dynamic lov contains values that come at run time

610. What are snap shots and views

Snapshots are mirror or replicas of tables. Views are built using the columns from one or more tables. The

Single Table View can be updated but the view with multi table cannot be updated

611. What are the OOPS concepts in Oracle.

Oracle does implement the OOPS concepts. The best example is the Property Classes. We can categorise theproperties by setting the visual attributes and then attach the property classes for the objects. OOPS supportsthe concepts of objects and classes and we can consider the peroperty classes as classes and the items asobjects

612. What is the difference between candidate key, unique key and primary key

Candidate keys are the columns in the table that could be the primary keys and the primary key is the key thathas been selected to identify the rows. Unique key is also useful for identifying the distinct rows in the table.)

613. What is concurrency

Cuncurrency is allowing simultaneous access of same data by different users. Locks useful for accesing thedatabase area) ExclusiveThe exclusive lock is useful for locking the row when an insert,update or delete is being done.This lock shouldnot be applied when we do only select from the row.b) Share lockWe can do the table as Share_Lock as many share_locks can be put on the same resource.

614. Previleges and Grants

Previleges are the right to execute a particulare type of SQL statements. e.g :: Right to Connect, Right tocreate, Right to resource Grants are given to the objects so that the object might be accessed accordingly.Thegrant has to be given by the owner of the object.

615. Table Space,Data Files,Parameter File, Control Files

Table Space :: The table space is useful for storing the data in the database.When a database is created twotable spaces are created.a) System Table space :: This data file stores all the tables related to the system and dba tablesb) User Table space :: This data file stores all the user related tablesWe should have seperate table spaces for storing the tables and indexes so that the access is fast.Data Files :: Every Oracle Data Base has one or more physical data files.They store the data for the

170

Page 171: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 171/225

database.Every datafile is associated with only one database.Once the Data file is created the size cannotchange.To increase the size of the database to store more data we have to add data file.Parameter Files :: Parameter file is needed to start an instance.A parameter file contains the list of instanceconfiguration parameters e.g.::db_block_buffers = 500db_name = ORA7db_domain = u.s.acme langControl Files :: Control files record the physical structure of the data files and redo log filesThey contain the Db name, name and location of dbs, data files ,redo log files and time stamp.

616. Physical Storage of the Data

The finest level of granularity of the data base are the data blocks.Data Block :: One Data Block correspond to specific number of physical database spaceExtent :: Extent is the number of specific number of contigious data blocks.Segments :: Set of Extents allocated for Extents. There are three types of Segmentsa) Data Segment :: Non Clustered Table has data segment data of every table is stored in cluster datasegmentb) Index Segment :: Each Index has index segment that stores datac) Roll Back Segment :: Temporarily store 'undo' information

617. What are the Pct Free and Pct Used

Pct Free is used to denote the percentage of the free space that is to be left when creating a table. SimilarlyPct Used is used to denote the percentage of the used space that is to be used when creating a table

eg.:: Pctfree 20, Pctused 40

618. What is Row Chaining

The data of a row in a table may not be able to fit the same data block.Data for row is stored in a chain of datablocks .

619. What is a 2 Phase Commit

Two Phase commit is used in distributed data base systems. This is useful to maintain the integrity of thedatabase so that all the users see the same values. It contains DML statements or Remote Procedural calls thatreference a remote object. There are basically 2 phases in a 2 phase commit.a) Prepare Phase :: Global coordinator asks participants to prepareb) Commit Phase :: Commit all participants to coordinator to Prepared, Read only or abort Reply

620. What is the difference between deleting and truncating of tables

Deleting a table will not remove the rows from the table but entry is there in the database dictionary and it canbe retrieved But truncating a table deletes it completely and it cannot be retrieved.

621. What are mutating tables

When a table is in state of transition it is said to be mutating. eg :: If a row has been deleted then the table issaid to be mutating and no operations can be done on the table except select.

622. What are Codd Rules

Codd Rules describe the ideal nature of a RDBMS. No RDBMS satisfies all the 12 codd rules and Oracle Satisfies11 of the 12 rules and is the only Rdbms to satisfy the maximum number of rules.

623. What is Normalisation

Normalisation is the process of organising the tables to remove the redundancy.There are mainly 5Normalisation rules.a) 1 Normal Form :: A table is said to be in 1st Normal Form when the attributes are atomicb) 2 Normal Form :: A table is said to be in 2nd Normal Form when all the candidate keys are dependant onthe primary keyc) 3rd Normal Form :: A table is said to be third Normal form when it is not dependant transitively

624. What is the Difference between a post query and a pre query

A post query will fire for every row that is fetched but the pre query will fire only once.

625. Deleting the Duplicate rows in the table

We can delete the duplicate rows in the table by using the Rowid

626. Can U disable database trigger? How?Yes. With respect to tableALTER TABLE TABLE[[ DISABLE all_trigger ]]

627. What is pseudo columns ? Name them?

171

Page 172: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 172/225

A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select frompseudocolumns, but you cannot insert, update, or delete their values. This section describes thesepseudocolumns:* CURRVAL* NEXTVAL* LEVEL* ROWID* ROWNUM

628. How many columns can table have?The number of columns in a table can range from 1 to 254.

629. Is space acquired in blocks or extents ?

In extents .

630. what is clustered index?

In an indexed cluster, rows are stored together based on their cluster key values . Can not applied for HASH.

631. what are the datatypes supported By oracle (INTERNAL)?

Varchar2, Number,Char , MLSLABEL.

632. What are attributes of cursor?

%FOUND , %NOTFOUND , %ISOPEN,%ROWCOUNT

633. Can you use select in FROM clause of SQL select ?

Yes.

634. Which trigger are created when master -detail rela?

master delete property* NON-ISOLATED (default)a) on check delete masterb) on clear detailsc) on populate details* ISOLATEDa) on clear detailsb) on populate details* CASCADEa) per-deleteb) on clear detailsc) on populate details

635. which system variables can be set by users?

SYSTEM.MESSAGE_LEVELSYSTEM.DATE_THRESHOLDSYSTEM.EFFECTIVE_DATESYSTEM.SUPPRESS_WORKING

636. What are object group?

An object group is a container for a group of objects. You define an object group when you want to packagerelated objects so you can copy or reference them in another module.

637. What are referenced objects?

Referencing allows you to create objects that inherit their functionality and appearance from other objects.Referencing an object is similar to copying an object, except that the resulting reference object maintains a linkto its source object. A reference object automatically inherits any changes that have been made to the sourceobject when you open or regenerate the module that contains the reference object.

638. Can you store objects in library?

Referencing allows you to create objects that inherit their functionality and appearance from other objects.Referencing an object is similar to copying an object, except that the resulting reference object maintains a linkto its source object. A reference object automatically inherits any changes that have been made to the source

object when you open or regenerate the module that contains the reference object.

639. Is forms 4.5 object oriented tool ? why?

yes , partially. 1) PROPERTY CLASS - inheritance property 2) OVERLOADING : procedures and functions

640. Can you issue DDL in forms?

172

Page 173: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 173/225

yes, but you have to use FORMS_DDL.Referencing allows you to create objects that inherit their functionality and appearance from other objects.Referencing an object is similar to copying an object, except that the resulting reference object maintains a linkto its source object. A reference object automatically inherits any changes that have been made to the sourceobject when you open or regenerate the module that contains the reference object. Any string expression up to32K:- a literal- an expression or a variable representing the text of a block of dynamically created PL/SQL code- a DML statement or- a DDL statementRestrictions:The statement you pass to FORMS_DDL may not contain bind variable references in the string, but the valuesof bind variables can be concatenated into the string before passing the result to FORMS_DDL.

641. What is SECURE property?

- Hides characters that the operator types into the text item. This setting is typically used for passwordprotection.

642. What are the types of triggers and how the sequence of firing in text item

Triggers can be classified as Key Triggers, Mouse Triggers ,Navigational Triggers.Key Triggers :: Key Triggers are fired as a result of Key action.e.g :: Key-next-field, Key-up,Key-DownMouse Triggers :: Mouse Triggers are fired as a result of the mouse navigation.e.g. When-mouse-button-presed,when-mouse-doubleclicked,etc

Navigational Triggers :: These Triggers are fired as a result of Navigation. E.g : Post-Text-item,Pre-text-item.We also have event triggers like when ?new-form-instance and when-new-block-instance.We cannot call restricted procedures like go_to(?my_block.first_item?) in the Navigational triggersBut can use them in the Key-next-item.The Difference between Key-next and Post-Text is an very important question. The key-next is fired as a resultof the key action while the post text is fired as a result of the mouse movement. Key next will not fire unlessthere is a key event. The sequence of firing in a text item are as follows ::a) pre - textb) when new itemc) key-nextd) when validatee) post text

643. Can you store pictures in database? How?

Yes , in long Raw datatype.

644. What are property classes ? Can property classes have trigger?

Property class inheritance is a powerful feature that allows you to quickly define objects that conform to yourown interface and functionality standards. Property classes also allow you to make global changes toapplications quickly. By simply changing the definition of a property class, you can change the definition of allobjects that inherit properties from that class.Yes . All type of triggers .

645. If you have property class attached to an item and you have same trigger written for the item .Which will fire first?

Item level trigger fires , If item level trigger fires, property level trigger won't fire. Triggers at the lowest levelare always given the first preference. The item level trigger fires first and then the block and then the Formlevel trigger.

646. What are record groups ? * Can record groups created at run-time?

A record group is an internal Oracle Forms data structure that has a column/row framework similar to adatabase table. However, unlike database tables, record groups are separate objects that belong to the formmodule in which they are defined. A record group can have an unlimited number of columns of type CHAR,LONG, NUMBER, or DATE provided that the total number of columns does not exceed 64K. Record groupcolumn names cannot exceed 30 characters.Programmatically, record groups can be used whenever the functionality offered by a two-dimensional array of multiple data types is desirable.TYPES OF RECORD GROUP:Query Record Group A query record group is a record group that has an associated SELECT statement. Thecolumns in a query record group derive their default names, data types, and lengths from the databasecolumns referenced in the SELECT statement. The records in a query record group are the rows retrieved bythe query associated with that record group.Non-query Record Group A non-query record group is a group that does not have an associated query, but

whose structure and values can be modified programmatically at runtime.Static Record Group A static record group is not associated with a query; rather, you define its structure androw values at design time, and they remain fixed at runtime.

647. What are ALERT?

An ALERT is a modal window that displays a message notifiying operator of some application condition.

173

Page 174: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 174/225

648. Can a button have icon and lable at the same time ?

-NO

649. What is mouse navigate property of button?

When Mouse Navigate is True (the default), Oracle Forms performs standard navigation to move the focus tothe item when the operator activates the item with the mouse.When Mouse Navigate is set to False, Oracle Forms does not perform navigation (and the resulting validation)

to move to the item when an operator activates the item with the mouse.

650. What is FORMS_MDI_WINDOW?

forms run inside the MDI application window. This property is useful for calling a form from another one.

651. What are timers ? when when-timer-expired does not fire?

The When-Timer-Expired trigger can not fire during trigger, navigation, or transaction processing.

652. Can object group have a block?

Yes , object group can have block as well as program units.

653. How many types of canvases are there.

There are 2 types of canvases called as Content and Stack Canvas. Content canvas is the default and the onethat is used mostly for giving the base effect. Its like a plate on which we add items and stacked canvas isused for giving 3 dimensional effect.

654. What are user-exits?

It invokes 3GL programs.

655. Can you pass values to-and-fro from foreign function ? how ?

Yes . You obtain a return value from a foreign function by assigning the return value to an Oracle Formsvariable or item. Make sure that the Oracle Forms variable or item is the same data type as the return valuefrom the foreign function.After assigning an Oracle Forms variable or item value to a PL/SQL variable, pass the PL/SQL variable as aparameter value in the PL/SQL interface of the foreign function. The PL/SQL variable that is passed as aparameter must be a valid PL/SQL data type; it must also be the appropriate parameter type as defined in the

PL/SQL interface.

656. What is IAPXTB structure ?

The entries of Pro * C and user exits and the form which simulate the proc or user_exit are stored in IAPXTBtable in d/b.

657. Can you call WIN-SDK thruo' user exits?

YES.

658. Does user exits supports DLL on MSWINDOWS ?

YES .

659. What is path setting for DLL?

Make sure you include the name of the DLL in the FORMS45_USEREXIT variable of the ORACLE.INI file, orrename the DLL to F45XTB.DLL. If you rename the DLL to F45XTB.DLL, replace the existing F45XTB.DLL in theORAWINBIN directory with the new F45XTB.DLL.

660. How is mapping of name of DLL and function done?

The dll can be created using the Visual C++ / Visual Basic Tools and then the dll is put in the path that isdefined the registery.

661. what is precompiler?

It is similar to C precompiler directives.

662. Can you connect to non - oracle datasource ? How?Yes .

663. what are key-mode and locking mode properties? level ?

174

Page 175: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 175/225

Key Mode : Specifies how oracle forms uniquely identifies rows in the database.This is property includes forapplication that will run against NON-ORACLE datasources .Key setting unique (default.)dateablen-updateable.

Locking mode :Specifies when Oracle Forms should attempt to obtain database locks on rows that correspond to queriedrecords in the form. a) immediate b) delayed

664. What are savepoint mode and cursor mode properties ? level?

Specifies whether Oracle Forms should issue savepoints during a session. This property is included primarily forapplications that will run against non-ORACLE data sources. For applications that will run against ORACLE, usethe default setting.Cursor mode - define cursur state across transaction Open/close.

665. Can you replace default form processing ? How ?

666. What is transactional trigger property?

Identifies a block as transactional control block. i.e. non - database block that oracle forms should manage astransactional block.(NON-ORACLE datasource) default - FALSE.

667. What is OLE automation ?

OLE automation allows an OLE server application to expose a set of commands and functions that can beinvoked from an OLE container application. OLE automation provides a way for an OLE container application touse the features of an OLE server application to manipulate an OLE object from the OLE containerenvironment. (FORMS_OLE)

668. What does invoke built-in do?

This procedure invokes a method.Syntax:PROCEDURE OLE2.INVOKE(object obj_type,method VARCHAR2,list list_type := 0);Parameters:object Is an OLE2 Automation Object.method Is a method (procedure) of the OLE2 object.list Is the name of an argument list assigned to the OLE2.CREATE_ARGLIST function.

669. What are OPEN_FORM,CALL_FORM,NEW_FORM? diff?

CALL_FORM : It calls the other form. but parent remains active, when called form completes the operation , itreleases lock and control goes back to the calling form.When you call a form, Oracle Forms issues a savepoint for the called form. If the CLEAR_FORM function causesa rollback when the called form is current, Oracle Forms rolls back uncommitted changes to this savepoint.OPEN_FORM : When you call a form, Oracle Forms issues a savepoint for the called form. If the CLEAR_FORMfunction causes a rollback when the called form is current, Oracle Forms rolls back uncommitted changes tothis savepoint.NEW_FORM : Exits the current form and enters the indicated form. The calling form is terminated as the parentform. If the calling form had been called by a higher form, Oracle Forms keeps the higher call active and treatsit as a call to the new form. Oracle Forms releases memory (such as database cursors) that the terminated

form was using.Oracle Forms runs the new form with the same Runform options as the parent form. If the parent form was acalled form, Oracle Forms runs the new form with the same options as the parent form.

670. What is call form stack?

When successive forms are loaded via the CALL_FORM procedure, the resulting module hierarchy is known asthe call form stack.

671. Can u port applictions across the platforms? how?

Yes we can port applications across platforms.Consider the form developed in a windows system.The formwould be generated in unix system by using f45gen my_form.fmb scott/tiger

672. What is a visual attribute?

Visual attributes are the font, color, and pattern properties that you set for form and menu objects that appearin your application's interface.

673. Diff. between VAT and Property Class? imp

Named visual attributes define only font, color, and pattern attributes; property classes can contain these andany other properties.

175

Page 176: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 176/225

You can change the appearance of objects at runtime by changing the named visual attributeprogrammatically; property class assignment cannot be changed programmatically. When an object isinheriting from both a property class and a named visual attribute, the named visual attribute settings takeprecedence, and any visual attribute properties in the class are ignored.

673. Which trigger related to mouse?

When-Mouse-ClickWhen-Mouse-DoubleClickWhen-Mouse-DownWhen-Mouse-EnterWhen-Mouse-LeaveWhen-Mouse-MoveWhen-Mouse-Up

674. What is Current record attribute property?

Specifies the named visual attribute used when an item is part of the current record. Current Record Attributeis frequently used at the block level to display the current row in a multi-record If you define an item-levelCurrent Record Attribute, you can display a pre-determined item in a special color when it is part of the currentrecord, but you cannot dynamically highlight the current item, as the input focus changes.

675. Can u change VAT at run time?

Yes. You can programmatically change an object's named visual attribute setting to change the font, color, and

pattern of the object at runtime.

676. Can u set default font in forms?

Yes. Change windows registry(regedit). Set form45_font to the desired font.

 _break

677. What is Log Switch ?

The point at which ORACLE ends writing to one online redo log file and begins writing to another is called a logswitch.

678. What is On-line Redo Log?

The On-line Redo Log is a set of tow or more on-line redo files that record all committed changes made to thedatabase. Whenever a transaction is committed, the corresponding redo entries temporarily stores in redo logbuffers of the SGA are written to an on-line redo log file by the background process LGWR. The on-line redo logfiles are used in cyclical fashion.

679. Which parameter specified in the DEFAULT STORAGE clause of CREATE TABLESPACE cannot be alteredafter creating the tablespace?

All the default storage parameters defined for the tablespace can be changed using the ALTER TABLESPACEcommand. When objects are created their INITIAL and MINEXTENS values cannot be changed.

680. What are the steps involved in Database Startup ?

Start an instance, Mount the Database and Open the Database.

< ? Recovery Instance in involved steps the are What>

Rolling forward to recover data that has not been recorded in data files, yet has been recorded in the on-line

redo log, including the contents of rollback segments. Rolling back transactions that have been explicitly rolledback or have not been committed as indicated by the rollback segments regenerated in step a. Releasing anyresources (locks) held by transactions in process at the time of the failure. Resolving any pending distributedtransactions undergoing a two-phase commit at the time of the instance failure.

682. Can Full Backup be performed when the database is open ?

No.

683. What are the different modes of mounting a Database with the Parallel Server ?

Exclusive Mode If the first instance that mounts a database does so in exclusive mode, only that Instance canmount the database.Parallel Mode If the first instance that mounts a database is started in parallel mode, other instances that arestarted in parallel mode can also mount the database.

684. What are the advantages of operating a database in ARCHIVELOG mode over operating it in NOARCHIVELOG mode ?

Complete database recovery from disk failure is possible only in ARCHIVELOG mode. Online database backup ispossible only in ARCHIVELOG mode.

176

Page 177: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 177/225

685. What are the steps involved in Database Shutdown ?

Close the Database, Dismount the Database and Shutdown the Instance.

686. What is Archived Redo Log ?

Archived Redo Log consists of Redo Log files that have archived before being reused.

687. What is Restricted Mode of Instance Startup ?

An instance can be started in (or later altered to be in) restricted mode so that when the database is openconnections are limited only to those whose user accounts have been granted the RESTRICTED SESSIONsystem privilege.

677. Can u have OLE objects in forms?

Yes.

678. Can u have VBX and OCX controls in forms ?

Yes.

679. What r the types of windows (Window style)?

Specifies whether the window is a Document window or a Dialog window.

680. What is OLE Activation style property?Specifies the event that will activate the OLE containing item.

681. Can u change the mouse pointer ? How?

Yes. Specifies the mouse cursor style. Use this property to dynamically change the shape of the cursor.

682. How many types of columns are there and what are they

Formula columns :: For doing mathematical calculations and returning one value Summary Columns :: Fordoing summary calculations such as summations etc. Place holder Columns :: These columns are useful forstoring the value in a variable

683. Can u have more than one layout in report

It is possible to have more than one layout in a report by using the additional layout option in the layouteditor.

684. Can u run the report with out a parameter form

Yes it is possible to run the report without parameter form by setting the PARAM value to Null

685. What is the lock option in reports layout

By using the lock option we cannot move the fields in the layout editor outside the frame. This is useful formaintaining the fields .

686. What is Flex

Flex is the property of moving the related fields together by setting the flex property on

687. What are the minimum number of groups required for a matrix report

The minimum of groups required for a matrix report are 4 e -----

688.. What is a Synonym ?

A synonym is an alias for a table, view, sequence or program unit.

689. What is a Sequence ?

A sequence generates a serial list of unique numbers for numerical columns of a database's tables.

690. What is a Segment ?

A segment is a set of extents allocated for a certain logical structure.

691. What is schema?A schema is collection of database objects of a User.

692. Describe Referential Integrity ?

177

Page 178: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 178/225

A rule defined on a column (or set of columns) in one table that allows the insert or update of a row only if thevalue for the column or set of columns (the dependent value) matches a value in a column of a related table(the referenced value). It also specifies the type of data manipulation allowed on referenced data and theaction to be performed on dependent data as a result of any action on referenced data.

693. What is Hash Cluster ?

A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value.All rows with the same hash key value are stores together on disk.

694. What is a Private Synonyms ?

A Private Synonyms can be accessed only by the owner.

695. What is Database Link ?

A database link is a named object that describes a "path" from one database to another.

696. What is index cluster?

A cluster with an index on the cluster key.

697.What is hash cluster?

A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value.All rows with the same hash key value are stores together on disk.

698.When can hash cluster used?

Hash clusters are better choice when a table is often queried with equality queries. For such queries thespecified cluster key value is hashed. The resulting hash key value points directly to the area on disk thatstores the specified rows.

699.When can hash cluster used?

Hash clusters are better choice when a table is often queried with equality queries. For such queries thespecified cluster key value is hashed. The resulting hash key value points directly to the area on disk thatstores the specified rows.

700. What are the types of database links?

Private database link, public database link & network database link.

701. What is private database link?

Private database link is created on behalf of a specific user. A private database link can be used only when theowner of the link specifies a global object name in a SQL statement or in the definition of the owner's views orprocedures.

702. What is public database link?

Public database link is created for the special user group PUBLIC. A public database link can be used when anyuser in the associated database specifies a global object name in a SQL statement or object definition.

703. What is network database link?

Network database link is created and managed by a network domain service. A network database link can be

used when any user of any database in the network specifies a global object name in a SQL statement orobject definition.

704. What is data block?

Oracle database's data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk.

705. How to define data block size?

A data block size is specified for each Oracle database when the database is created. A database users andallocated free database space in Oracle data blocks. Block size is specified in init.ora file and cannot bechanged latter.

706. What is row chaining?

In circumstances, all of the data for a row in a table may not be able to fit in the same data block. When thisoccurs, the data for the row is stored in a chain of data block (one or more) reserved for that segment.

707. What is an extent?

178

Page 179: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 179/225

An extent is a specific number of contiguous data blocks, obtained in a single allocation and used to store aspecific type of information.

708. What are the different types of segments?

Data segment, index segment, rollback segment and temporary segment.

709. What is a data segment?

Each non-clustered table has a data segment. All of the table's data is stored in the extents of its datasegment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's datasegment.

709. What is an index segment?

Each index has an index segment that stores all of its data.

710. What is rollback segment?

A database contains one or more rollback segments to temporarily store "undo" information.

711. What are the uses of rollback segment?

To generate read-consistent database information during database recovery and to rollback uncommittedtransactions by the users.

712. What is a temporary segment?

Temporary segments are created by Oracle when a SQL statement needs a temporary work area to completeexecution. When the statement finishes execution, the temporary segment extents are released to the systemfor future use.

713. What is a datafile?

Every Oracle database has one or more physical data files. A database's data files contain all the databasedata. The data of logical database structures such as tables and indexes is physically stored in the data filesallocated for a database.

714. What are the characteristics of data files?

A data file can be associated with only one database. Once created a data file can't change size. One or moredata files form a logical unit of database storage called a tablespace.

715. What is a redo log?

The set of redo log files for a database is collectively known as the database redo log.

716. What is the function of redo log?

The primary function of the redo log is to record all changes made to data.

717. What is the use of redo log information?

The information in a redo log file is used only to recover the database from a system or media failure preventsdatabase data from being written to a database's data files.

718. What does a control file contains?- Database name- Names and locations of a database's files and redolog files.- Time stamp of database creation.

719. What is the use of control file?

When an instance of an Oracle database is started, its control file is used to identify the database and redo logfiles that must be opened for database operation to proceed. It is also used in database recovery.

720. Is it possible to split the print reviewer into more than one region?

Yes

721. Is it possible to center an object horizontally in a repeating frame that has a variable horizontal size?

Yes

722. For a field in a repeating frame, can the source come from the column which does not exist in the datagroup which forms the base for the frame?

Yes

179

Page 180: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 180/225

723. Can a field be used in a report without it appearing in any data group?

Yes

724. The join defined by the default data link is an outer join yes or no?

Yes

725. Can a formula column referred to columns in higher group?

Yes

726. Can a formula column be obtained through a select statement?

Yes

727. Is it possible to insert comments into sql statements return in the data model editor?

Yes

728. Is it possible to disable the parameter from while running the report?

Yes

729. When a form is invoked with call_form, Does oracle forms issues a save point?

Yes730. Explain the difference between a hot backup and a cold backup and the benefits associated with

each.

A hot backup is basically taking a backup of the database while it is still up and running and it must be inarchive log mode. A cold backup is taking a backup of the database while it is shut down and does not requirebeing in archive log mode. The benefit of taking a hot backup is that the database is still available for use whilethe backup is occurring and you can recover the database to any point in time. The benefit of taking a coldbackup is that it is typically easier to administer the backup and recovery process. In addition, since you aretaking cold backups the database does not require being in archive log mode and thus there will be a slightperformance gain as the database is not cutting archive logs to disk.

731. You have just had to restore from backup and do not have any control files. How would you go aboutbringing up this database?

I would create a text based backup control file, stipulating where on disk all the data files where and then issuethe recover command with the using backup control file clause.

732. How do you switch from an init.ora file to a spfile?

Issue the create spfile from pfile command.

732. Explain the difference between a data block, an extent and a segment.

A data block is the smallest unit of logical storage for a database object. As objects grow they take chunks of additional storage that are composed of contiguous data blocks. These groupings of contiguous data blocks arecalled extents. All the extents that an object takes when grouped together are considered the segment of thedatabase object.

733. Give two examples of how you might determine the structure of the table DEPT.

Use the describe command or use the dbms_metadata.get_ddl package.

734. Where would you look for errors from the database engine?

In the alert log.

735. Compare and contrast TRUNCATE and DELETE for a table.

Both the truncate and delete command have the desired outcome of getting rid of all the rows in a table. Thedifference between the two is that the truncate command is a DDL operation and just moves the high watermark and produces a now rollback. The delete command, on the other hand, is a DML operation, which willproduce a rollback and thus take longer to complete.

736. Give the reasoning behind using an index.

Faster access to data blocks in a table.

737. Give the two types of tables involved in producing a star schema and the type of data they hold.

Fact tables and dimension tables. A fact table contains measurements while dimension tables will contain datathat will help describe the fact tables.

180

Page 181: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 181/225

738. What type of index should you use on a fact table?

A Bitmap index.

739. Give two examples of referential integrity constraints.

A primary key and a foreign key.

740. A table is classified as a parent table and you want to drop and re-create it. How would you do thiswithout affecting the children tables?

Disable the foreign key constraint to the parent, drop the table, re-create the table, enable the foreign keyconstraint.

741. Explain the difference between ARCHIVELOG mode and NOARCHIVELOG mode and the benefits anddisadvantages to each.

ARCHIVELOG mode is a mode that you can put the database in for creating a backup of all transactions thathave occurred in the database so that you can recover to any point in time. NOARCHIVELOG mode is basicallythe absence of ARCHIVELOG mode and has the disadvantage of not being able to recover to any point in time.NOARCHIVELOG mode does have the advantage of not having to write transactions to an archive log and thusincreases the performance of the database slightly.

742. What command would you use to create a backup control file?

Alter database backup control file to trace.

743. Give the stages of instance startup to a usable state where normal users may access it.

STARTUP NOMOUNT - Instance startupSTARTUP MOUNT - The database is mountedSTARTUP OPEN - The database is opened

744. What column differentiates the V$ views to the GV$ views and how?

The INST_ID column which indicates the instance in a RAC environment the information came from.

745. How would you go about generating an EXPLAIN plan?

Create a plan table with utlxplan.sql.Use the explain plan set statement_id = 'tst1' into plan_table for a SQL statementLook at the explain plan with utlxplp.sql or utlxpls.sql

746. How would you go about increasing the buffer cache hit ratio?

Use the buffer cache advisory over a given workload and then query the v$db_cache_advice table. If a changewas necessary then I would use the alter system set db_cache_size command.

747. Explain an ORA-01555

You get this error when you get a snapshot too old within rollback. It can usually be solved by increasing theundo retention or increasing the size of rollbacks. You should also look at the logic involved in the applicationgetting the error message.

748. Explain the difference between $ORACLE_HOME and $ORACLE_BASE.

ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath ORACLE_BASE is where theoracle products reside.

749. How would you determine the time zone under which a database was operating?

select DBTIMEZONE from dual;

750. Explain the use of setting GLOBAL_NAMES equal to TRUE.

Setting GLOBAL_NAMES dictates how you might connect to a database. This variable is either TRUE or FALSEand if it is set to TRUE it enforces database links to have the same name as the remote database to which theyare linking.

751. What command would you use to encrypt a PL/SQL application?

WRAP

752. Explain the difference between a FUNCTION, PROCEDURE and PACKAGE.A function and procedure are the same in that they are intended to be a collection of PL/SQL code that carriesa single task. While a procedure does not have to return any values to the calling application, a function willreturn a single value. A package on the other hand is a collection of functions and procedures that are groupedtogether based on their commonality to a business function or application.

181

Page 182: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 182/225

753. Explain the use of table functions.

Table functions are designed to return a set of rows through PL/SQL logic but are intended to be used as anormal table or view in a SQL statement. They are also used to pipeline information in an ETL process.

754. Name three advisory statistics you can collect.

Buffer Cache Advice, Segment Level Statistics, & Timed Statistics

755. Where in the Oracle directory tree structure are audit traces placed?

In unix $ORACLE_HOME/rdbms/audit, in Windows the event viewer

756. Explain materialized views and how they are used.

Materialized views are objects that are reduced sets of information that have been summarized, grouped, oraggregated from base tables. They are typically used in data warehouse or decision support systems.

757. When a user process fails, what background process cleans up after it?

PMON

758. What background process refreshes materialized views?

The Job Queue Processes.

759. How would you determine what sessions are connected and what resources they are waiting for?

Use of V$SESSION and V$SESSION_WAIT

760. Describe what redo logs are.

Redo logs are logical and physical structures that are designed to hold all the changes made to a database andare intended to aid in the recovery of a database.

761. How would you force a log switch?

ALTER SYSTEM SWITCH LOGFILE;

762. Give two methods you could use to determine what DDL changes have been made.

You could use Logminer or Streams

763. What does coalescing a tablespace do?

Coalescing is only valid for dictionary-managed tablespaces and de-fragments space by combining neighboringfree extents into large single extents.

764. What is the difference between a TEMPORARY tablespace and a PERMANENT tablespace?

A temporary tablespace is used for temporary objects such as sort structures while permanent tablespaces areused to store those objects meant to be used as the true objects of the database.

765. Name a tablespace automatically created when you create a database.

The SYSTEM tablespace.

766. When creating a user, what permissions must you grant to allow them to connect to thedatabase?

Grant the CONNECT to the user.

767. How do you add a data file to a tablespace

ALTER TABLESPACE <tablespace_name> ADD DATAFILE <datafile_name> SIZE

768. How do you resize a data file?

ALTER DATABASE DATAFILE <datafile_name> RESIZE <new_size>;

769. What view would you use to look at the size of a data file?

DBA_DATA_FILES

770. What view would you use to determine free space in a tablespace?

DBA_FREE_SPACE

771. How would you determine who has added a row to a table?

182

Page 183: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 183/225

Turn on fine grain auditing for the table.

772. How can you rebuild an index?

ALTER INDEX <index_name> REBUILD;

773. Explain what partitioning is and what its benefit is.

Partitioning is a method of taking large tables and indexes and splitting them into smaller, more manageablepieces.

774. You have just compiled a PL/SQL package but got errors, how would you view the errors?

SHOW ERRORS

775. How can you gather statistics on a table?

The ANALYZE command.

776. How can you enable a trace for a session?

Use the DBMS_SESSION.SET_SQL_TRACE orUse ALTER SESSION SET SQL_TRACE = TRUE;

777. What is the difference between the SQL*Loader and IMPORT utilities?

These two Oracle utilities are used for loading data into the database. The difference is that the import utilityrelies on the data being produced by another Oracle utility EXPORT while the SQL*Loader utility allows data tobe loaded that has been produced by other utilities from different data sources just so long as it conforms toASCII formatted or delimited files.

778. Name two files used for network connection to a database.

TNSNAMES.ORA and SQLNET.ORA

GENERAL INTERVIEW QUESTIONS

1.What are the various types of Exceptions ?

User defined and Predefined Exceptions.

2.Can we define exceptions twice in same block ?

No.

3.What is the difference between a procedure and a function ?

Functions return a single variable by value whereas procedures do not return any variable by value. Ratherthey return multiple variables by passing variables by reference through their OUT parameter.

4.Can you have two functions with the same name in a PL/SQL block ?

Yes.

5.Can you have two stored functions with the same name ?

183

Page 184: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 184/225

Yes.

6.Can you call a stored function in the constraint of a table ?

No.

7.What are the various types of parameter modes in a procedure ?

IN, OUT AND INOUT.

8.What is Over Loading and what are its restrictions ?

OverLoading means an object performing different functions depending upon the no. of parameters or the datatype of the parameters passed to it.

9.Can functions be overloaded ?

Yes.

10.Can 2 functions have same name & input parameters but differ only by return datatype

No.

11.What are the constructs of a procedure, function or a package ?

The constructs of a procedure, function or a package are :variables and constantscursorsexceptions

12.Why Create or Replace and not Drop and recreate procedures ?

So that Grants are not dropped.

13.Can you pass parameters in packages ? How ?

Yes. You can pass parameters to procedures or functions in a package.

14.What are the parts of a database trigger ?

The parts of a trigger are:A triggering event or statementA trigger restrictionA trigger action

15.What are the various types of database triggers ?

There are 12 types of triggers, they are combination of :Insert, Delete and Update Triggers.Before and After Triggers.Row and Statement Triggers.(3*2*2=12)

16.What is the advantage of a stored procedure over a database trigger ?

We have control over the firing of a stored procedure but we have no control over the firing of a trigger.

17.What is the maximum no. of statements that can be specified in a trigger statement ?

One.

18.Can views be specified in a trigger statement ?

No

19.What are the values of :new and :old in Insert/Delete/Update Triggers ?

INSERT : new = new value, old = NULLDELETE : new = NULL, old = old valueUPDATE : new = new value, old = old value

20.What are cascading triggers? What is the maximum no of cascading triggers at a time?When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading.Max = 32.

21.What are mutating triggers ?

184

Page 185: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 185/225

A trigger giving a SELECT on the table on which the trigger is written.

22.What are constraining triggers ?

A trigger giving an Insert/Updat e on a table having referential integrity constraint on the triggering table.

23.Describe Oracle database's physical and logical structure ?

Physical : Data files, Redo Log files, Control file.Logical : Tables, Views, Tablespaces, etc.

24.Can you increase the size of a tablespace ? How ?

Yes, by adding datafiles to it.

26.What is the use of Control files ?

Contains pointers to locations of various data files, redo log files, etc.

27.What is the use of Data Dictionary ?

Used by Oracle to store information about various physical and logical Oracle structures e.g. Tables,Tablespaces, datafiles, etc

28.What are the advantages of clusters ?

Access time reduced for joins.

29.What are the disadvantages of clusters ?

The time for Insert increases.

30.Can Long/Long RAW be clustered ?

No.

31.Can null keys be entered in cluster index, normal index ?

Yes.

32.Can Check constraint be used for self referential integrity ? How ?Yes. In the CHECK condition for a column of a table, we can reference some other column of the same tableand thus enforce self referential integrity.

33.What are the min. extents allocated to a rollback extent ?

Two

34.What are the states of a rollback segment ? What is the difference between partly available and needsrecovery ?

The various states of a rollback segment are :ONLINE, OFFLINE, PARTLY AVAILABLE, NEEDS RECOVERY and INVALID.

35.What is the difference between unique key and primary key ?

Unique key can be null; Primary key cannot be null.

36.An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ?

No.

37.Can you define multiple savepoints ?

Yes.

38.Can you Rollback to any savepoint ?

Yes.

40.What is the maximum no. of columns a table can have ?254.

41.What is the significance of the & and && operators in PL SQL ?

185

Page 186: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 186/225

The & operator means that the PL SQL block requires user input for a variable. The && operator means that thevalue of this variable should be the same as inputted by the user previously for this same variable. If atransaction is very large, and the rollback segment is not able to hold the rollback information, then will thetransaction span across different rollback segments or will it terminate ? It will terminate (Please check ).

42.Can you pass a parameter to a cursor ?

Explicit cursors can take parameters, as the example below shows. A cursor parameter can appear in a querywherever a constant can appear. CURSOR c1 (median IN NUMBER) IS SELECT job, ename FROM emp WHEREsal > median;

43.What are the various types of RollBack Segments ?

Public Available to all instancesPrivate Available to specific instance

44.Can you use %RowCount as a parameter to a cursor ?

Yes

45.Is the query below allowed :Select sal, ename Into x From emp Where ename = 'KING'(Where x is a record of Number(4) and Char(15))

Yes

46.Is the assignment given below allowed :ABC = PQR (Where ABC and PQR are records)

Yes

47.Is this for loop allowed :For x in &Start..&End Loop

Yes

48.How many rows will the following SQL return :Select * from emp Where rownum < 10;

9 rows

49.How many rows will the following SQL return :Select * from emp Where rownum = 10;

No rows

50.Which symbol preceeds the path to the table in the remote database ?

@

51.Are views automatically updated when base tables are updated ?

Yes

52.Can a trigger written for a view ?

No

53.If all the values from a cursor have been fetched and another fetch is issued, the output will be : error, lastrecord or first record ?

Last Record

54.A table has the following data : [[5, Null, 10]]. What will the average function return ?

7.5

55.Is Sysdate a system variable or a system function?

System Function

56.Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference we getthe next number 2. Suppose at this point we issue an rollback and again issue a nextval. What will the outputbe ?

3

56.Definition of relational DataBase by Dr. Codd (IBM)?

186

Page 187: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 187/225

A Relational Database is a database where all data visible to the user is organized strictly as tables of datavalues and where all database operations work on these tables.

57.What is Multi Threaded Server (MTA) ?

In a Single Threaded Architecture (or a dedicated server configuration) the database manager creates aseparate process for each database user. But in MTA the database manager can assign multiple users (multipleuser processes) to a single dispatcher (server process), a controlling process that queues request for work thusreducing the databases memory requirement and resources.

58.Which are initial RDBMS, Hierarchical & N/w database ?

RDBMS - R systemHierarchical - IMSN/W - DBTG

60.What is Functional Dependency

Given a relation R, attribute Y of R is functionally dependent on attribute X of R if and only if each X-value hasassociated with it precisely one -Y value in R

61.What is Auditing ?

The database has the ability to audit all actions that take place within it.a) Login attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL) or Least(1,NULL) NULL

62.While designing in client/server what are the 2 imp. things to be considered ?

Network Overhead (traffic), Speed and Load of client server

64.When to create indexes ?

To be created when table is queried for less than 2% or 4% to 25% of the table rows.

65.How can you avoid indexes ?

TO make index access path unavailable - Use FULL hint to optimizer for full table scan - Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes instead of another. - Use an expression in theWhere Clause of the SQL.

66.What is the result of the following SQL :Select 1 from dualUNIONSelect 'A' from dual;

Error

67.Can database trigger written on synonym of a table and if it can be then what would be the effect if originaltable is accessed.

Yes, database trigger would fire.

68.Can you alter synonym of view or view ?

No

69.Can you create index on view

No

70.What is the difference between a view and a synonym ?

Synonym is just a second name of table used for multiple link of database. View can be created with manytables, and with virtual columns and with conditions. But synonym can be on view.

71.What is the difference between alias and synonym ?

Alias is temporary and used with one query. Synonym is permanent and not used as alias.

72.What is the effect of synonym and table name used in same Select statement ?

Valid

73.What's the length of SQL integer ?

32 bit length

74.What is the difference between foreign key and reference key ?

187

Page 188: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 188/225

Foreign key is the key i.e. attribute which refers to another table primary key. Reference key is the primarykey of table referred by another table.

75.Can dual table be deleted, dropped or altered or updated or inserted ?

Yes

76.If content of dual is updated to some value computation takes place or not ?

Yes

77.If any other table same as dual is created would it act similar to dual?

Yes

78.For which relational operators in where clause, index is not used ?

<> , like '% ...' is NOT functions, field +constant, field || ''

79.Assume that there are multiple databases running on one machine. How can you switch from one toanother ?

Changing the ORACLE_SID

80.What are the advantages of Oracle ?

Portability : Oracle is ported to more platforms than any of its competitors, running on more than 100hardware platforms and 20 networking protocols.Market Presence : Oracle is by far the largest RDBMS vendor and spends more on R & D than most of itscompetitors earn in total revenue. This market clout means that you are unlikely to be left in the lurch byOracle and there are always lots of third party interfaces available.Backup and Recovery : Oracle provides industrial strength support for on-line backup and recovery and goodsoftware fault tolerence to disk failure. You can also do point-in-time recovery.Performance : Speed of a 'tuned' Oracle Database and application is quite good, even with large databases.Oracle can manage > 100GB databases.Multiple database support : Oracle has a superior ability to manage multiple databases within the sametransaction using a two-phase commit protocol.

81.What is a forward declaration ? What is its use ?

PL/SQL requires that you declare an identifier before using it. Therefore, you must declare a subprogrambefore calling it. This declaration at the start of a subprogram is called forward declaration. A forwarddeclaration consists of a subprogram specification terminated by a semicolon.

82.What are actual and formal parameters ?

Actual Parameters : Subprograms pass information using parameters. The variables or expressions referencedin the parameter list of a subprogram call are actual parameters. For example, the following procedure call liststwo actual parameters named emp_num and amount:Eg. raise_salary(emp_num, amount);Formal Parameters : The variables declared in a subprogram specification and referenced in the subprogrambody are formal parameters. For example, the following procedure declares two formal parameters namedemp_id and increase: Eg. PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary REAL;

GENERAL INTERVIEW QUESTIONS (6)

83.What are the types of Notation ?

Position, Named, Mixed and Restrictions.

84.What all important parameters of the init.ora are supposed to be increased if you want to increase the SGAsize ?

In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 & 3500) shared_pool_sizewas changed from 3.5MB to 9MB (std values are 3.5, 5 & 9MB) open_cursors was changed from 200 to 300(std values are 200 & 300) db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of databasecreation}.The initial SGA was around 4MB when the server RAM was 32MB and The new SGA was around 13MB when theserver RAM was increased to 128MB.

85.If I have an execute privilege on a procedure in another users schema, can I execute his procedure eventhough I do not have privileges on the tables within the procedure ?

Yes

86.What are various types of joins ?

Equijoins, Non-equijoins, self join, outer join

188

Page 189: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 189/225

87.What is a package cursor ?

A package cursor is a cursor which you declare in the package specification without an SQL statement. TheSQL statement for the cursor is attached dynamically at runtime from calling procedures.

88.If you insert a row in a table, then create another table and then say Rollback. In this case will the row beinserted ?

Yes. Because Create table is a DDL which commits automatically as soon as it is executed. The DDL commitsthe transaction even if the create statement fails internally (eg table already exists error) and not syntactically.

89.What are the various types of queries ??

Normal QueriesSub QueriesCo-related queriesNested queriesCompound queries

90.What is a transaction ?

A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements.

91.What is implicit cursor and how is it used by Oracle ?

An implicit cursor is a cursor which is internally created by Oracle. It is created by Oracle for each individual

SQL.

92.Which of the following is not a schema object : Indexes, tables, public synonyms, triggers and packages ?

Public synonyms

94.What is PL/SQL?

PL/SQL is Oracle's Procedural Language extension to SQL. The language includes object oriented programmingtechniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, bringsstate-of-the-art programming to the Oracle database server and a variety of Oracle tools.

95.Is there a PL/SQL Engine in SQL*Plus?

No. Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine. Thus, all your PL/SQL are send directly to

the database engine for execution. This makes it much more efficient as SQL statements are not stripped off and send to the database individually.

96.Is there a limit on the size of a PL/SQL block?

Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is 100K.You can run the following select statement to query the size of an existing package or procedure.SQL> select * from dba_object_size where name = 'procedure_name'

97.Can one read/write files from PL/SQL?

Included in Oracle 7.3 is a UTL_FILE package that can read and write files. The directory you intend writing tohas to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writinga file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.DECLAREfileHandler UTL_FILE.FILE_TYPE;BEGINfileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));UTL_FILE.FCLOSE(fileHandler);END;

98.How can I protect my PL/SQL source code?

PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the sourcecode. This is done via a standalone utility that transforms the PL/SQL source code into portable binary objectcode (somewhat larger than the original). This way you can distribute software without having to worry aboutexposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will still understand and know howto execute such scripts. Just be careful, there is no "decode" command available.The syntax is:wrap iname=myscript.sql oname=xxxx.yyy

99.Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ?

From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements.Eg: CREATE OR REPLACE PROCEDURE DYNSQLAScur integer;

189

Page 190: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 190/225

rc integer;BEGINcur := DBMS_SQL.OPEN_CURSOR;DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);rc := DBMS_SQL.EXECUTE(cur);DBMS_SQL.CLOSE_CURSOR(cur);END;

XML

1. What is XML?

XML is the Extensible Markup Language. It improves the functionality of the Web by letting you identify yourinformation in a more accurate, flexible, and adaptable way.It is extensible because it is not a fixed format like HTML (which is a single, predefined markup language).Instead, XML is actually a metalanguage—a language for describing other languages—which lets you designyour own markup languages for limitless different types of documents. XML can do this because it's written inSGML, the international standard metalanguage for text document markup (ISO 8879).

2. What is a markup language?

A markup language is a set of words and symbols for describing the identity of pieces of a document (forexample ‘this is a paragraph’, ‘this is a heading’, ‘this is a list’, ‘this is the caption of this figure’, etc). Programscan use this with a stylesheet to create output for screen, print, audio, video, Braille, etc.Some markup languages (eg those used in wordprocessors) only describe appearances (‘this is italics’, ‘this isbold’), but this method can only be used for display, and is not normally re-usable for anything else.

3. Where should I use XML?

Its goal is to enable generic SGML to be served, received, and processed on the Web in the way that is nowpossible with HTML. XML has been designed for ease of implementation and for interoperability with both SGMLand HTML.Despite early attempts, browsers never allowed other SGML, only HTML (although there were plugins), andthey allowed it (even encouraged it) to be corrupted or broken, which held development back for over adecade by making it impossible to program for it reliably. XML fixes that by making it compulsory to stick tothe rules, and by making the rules much simpler than SGML.But XML is not just for Web pages: in fact it's very rarely used for Web pages on its own because browsers stilldon't provide reliable support for formatting and transforming it. Common uses for XML include:Information identificationbecause you can define your own markup, you can define meaningful names for all your information items.Information storagebecause XML is portable and non-proprietary, it can be used to store textual information across any platform.

Because it is backed by an international standard, it will remain accessible and processable as a data format.Information structureXML can therefore be used to store and identify any kind of (hierarchical) information structure, especially forlong, deep, or complex document sets or data sources, making it ideal for an information-management back-end to serving the Web. This is its most common Web application, with a transformation system to serve it asHTML until such time as browsers are able to handle XML consistently. PublishingThe original goal of XML as defined in the quotation at the start of this section. Combining the three previoustopics (identity, storage, structure) means it is possible to get all the benefits of robust document managementand control (with XML) and publish to the Web (as HTML) as well as to paper (as PDF) and to other formats (egBraille, Audio, etc) from a single source document by using the appropriate stylesheets. Messaging and datatransferXML is also very heavily used for enclosing or encapsulating information in order to pass it between differentcomputing systems which would otherwise be unable to communicate. By providing a lingua franca for dataidentity and structure, it provides a common envelope for inter-process communication (messaging). WebservicesBuilding on all of these, as well as its use in browsers, machine-processable data can be exchanged betweenconsenting systems, where before it was only comprehensible by humans (HTML). Weather services, e-commerce sites, blog newsfeeds, AJaX sites, and thousands of other data-exchange services use XML for datamanagement and transmission, and the web browser for display and interaction.

4. Why is XML such an important development?

It removes two constraints which were holding back Web developments:1. dependence on a single, inflexible document type (HTML) which was being much abused for tasks it wasnever designed for;2. the complexity of full SGML, whose syntax allows many powerful but hard-to-program options.XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary,persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web;and it removes the more complex options of SGML, making it easier to program for.

5. Describe the differences between XML and HTML.

It's amazing how many developers claim to be proficient programming with XML, yet do not understand thebasic differences between XML and HTML. Anyone with a fundamental grasp of XML should be able describesome of the main differences outlined in the table below.

Differences Between XML and HTMLTable 1.

190

Page 191: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 191/225

XML HTML

User definable tags Defined set of tags designed for webdisplay

Content driven Format driven

End tags required for well formeddocuments

End tags not required

Quotes required around attributesvalues

Quotes not required

Slash required in empty tags Slash not required

6. Describe the role that XSL can play when dynamically generating HTML pages from a relational database.

Even if candidates have never participated in a project involving this type of architecture, they shouldrecognize it as one of the common uses of XML. Querying a database and then formatting the result set so thatit can be validated as an XML document allows developers to translate the data into an HTML table using XSLTrules. Consequently, the format of the resulting HTML table can be modified without changing the databasequery or application code since the document rendering logic is isolated to the XSLT rules.

7. What is SGML?

SGML is the Standard Generalized Markup Language (ISO 8879:1986), the international standard for definingdescriptions of the structure of different types of electronic document. There is an SGML FAQ from DavidMegginson at http://math.albany.edu:8800/hm/sgml/cts-faq.htmlFAQ; and Robin Cover's SGML Web pagesare at http://www.oasis-open.org/cover/general.html. For a little light relief, try Joe English's ‘Not the SGMLFAQ’ at http://www.flightlab.com/~joe/sgml/faq-not.txtFAQ.SGML is very large, powerful, and complex. It has been in heavy industrial and commercial use for nearly twodecades, and there is a significant body of expertise and software to go with it.XML is a lightweight cut-down version of SGML which keeps enough of its functionality to make it useful butremoves all the optional features which made SGML too complex to program for in a Web environment.

8. Aren't XML, SGML, and HTML all the same thing?

Not quite; SGML is the mother tongue, and has been used for describing thousands of different documenttypes in many fields of human activity, from transcriptions of ancient Irish manuscripts to the technicaldocumentation for stealth bombers, and from patients' clinical records to musical notation. SGML is very largeand complex, however, and probably overkill for most common office desktop applications.XML is an abbreviated version of SGML, to make it easier to use over the Web, easier for you to define yourown document types, and easier for programmers to write programs to handle them. It omits all the complexand less-used options of SGML in return for the benefits of being easier to write applications for, easier tounderstand, and more suited to delivery and interoperability over the Web. But it is still SGML, and XML filesmay still be processed in the same way as any other SGML file (see the question on XML software).HTML is just one of many SGML or XML applications—the one most frequently used on the Web.Technical readers may find it more useful to think of XML as being SGML-- rather than HTML++.

9. Who is responsible for XML?

XML is a project of the World Wide Web Consortium (W3C), and the development of the specification issupervised by an XML Working Group. A Special Interest Group of co-opted contributors and experts fromvarious fields contributed comments and reviews by email.XML is a public format: it is not a proprietary development of any company, although the membership of the

WG and the SIG represented companies as well as research and academic institutions. The v1.0 specificationwas accepted by the W3C as a Recommendation on Feb 10, 1998.

10. Why is XML such an important development?

It removes two constraints which were holding back Web developments:1. dependence on a single, inflexible document type (HTML) which was being much abused for tasks it wasnever designed for;2. the complexity of full question A.4, SGML, whose syntax allows many powerful but hard-to-program options.

XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary,persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web;and it removes the more complex options of SGML, making it easier to program for.

11. Give a few examples of types of applications that can benefit from using XML.

There are literally thousands of applications that can benefit from XML technologies. The point of this questionis not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allowthe candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, oneappropriate answer is that XML allows content management systems to store documents independently of theirformat, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chainmanagement systems. In these instances, XML provides a mechanism for multiple companies to exchange data

191

Page 192: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 192/225

according to an agreed upon set of rules. A third common response involves wireless applications that requireWML to render data on hand held devices.

12. What is DOM and how does it relate to XML?

The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup thatdefines an application independent mechanism to access, parse, or update XML data. In simple terms it is ahierarchical model that allows developers to manipulate XML documents easily Any developer that has workedextensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is notunreasonable to expect advanced candidates to thoroughly understand its internal workings and be able toexplain how DOM differs from an event-based interface like SAX.

13. What is SOAP and how does it relate to XML?

The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information indistributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules,and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirementfor the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, isnot as important as identifying it as a natural application of XML.

14. Why not just carry on extending HTML?

HTML was already overburdened with dozens of interesting but incompatible inventions from differentmanufacturers, because it provides only one way of describing your information.XML allows groups of people or organizations to question C.13, create their own customized markupapplications for exchanging information in their domain (music, chemistry, electronics, hill-walking, finance,

surfing, petroleum geology, linguistics, cooking, knitting, stellar cartography, history, engineering, rabbit-keeping, question C.19, mathematics, genealogy, etc).HTML is now well beyond the limit of its usefulness as a way of describing information, and while it willcontinue to play an important role for the content it currently represents, many new applications require amore robust and flexible infrastructure.

15. Why should I use XML?

Here are a few reasons for using XML (in no particular order). Not all of these will apply to your ownrequirements, and you may have additional reasons not mentioned here (if so, please let the editor of the FAQknow!).* XML can be used to describe and identify information accurately and unambiguously, in a way thatcomputers can be programmed to ‘understand’ (well, at least manipulate as if they could understand).* XML allows documents which are all the same type to be created consistently and without structural errors,because it provides a standardised way of describing, controlling, or allowing/disallowing particular types of document structure. [Note that this has absolutely nothing whatever to do with formatting, appearance, or theactual text content of your documents, only the structure of them.]* XML provides a robust and durable format for information storage and transmission. Robust because it isbased on a proven standard, and can thus be tested and verified; durable because it uses plain-text fileformats which will outlast proprietary binary ones.* XML provides a common syntax for messaging systems for the exchange of information betweenapplications. Previously, each messaging system had its own format and all were different, which made inter-system messaging unnecessarily messy, complex, and expensive. If everyone uses the same syntax it makeswriting these systems much faster and more reliable.* XML is free. Not just free of charge (free as in beer) but free of legal encumbrances (free as in speech). Itdoesn't belong to anyone, so it can't be hijacked or pirated. And you don't have to pay a fee to use it (you canof course choose to use commercial software to deal with it, for lots of good reasons, but you don't pay for XMLitself).* XML information can be manipulated programmatically (under machine control), so XML documents can bepieced together from disparate sources, or taken apart and re-used in different ways. They can be convertedinto almost any other format with no loss of information.

* XML lets you separate form from content. Your XML file contains your document information (text, data) andidentifies its structure: your formatting and other processing needs are identified separately in a stylesheet orprocessing system. The two are combined at output time to apply the required formatting to the text or dataidentified by its structure (location, position, rank, order, or whatever).

16. Can you walk us through the steps necessary to parse XML documents?

Superficially, this is a fairly basic question. However, the point is not to determine whether candidatesunderstand the concept of a parser but rather have them walk through the process of parsing XML documentsstep-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriateparser, and handling errors are all important aspects to this process that should be included in the candidate'sresponse.

17. Give some examples of XML DTDs or schemas that you have worked with.

Although XML does not require data to be validated against a DTD, many of the benefits of using thetechnology are derived from being able to validate XML documents against business or technical architecturerules. Polling for the list of DTDs that developers have worked with provides insight to their general exposureto the technology. The ideal candidate will have knowledge of several of the commonly used DTDs such asFpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project whereno standard existed.

192

Page 193: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 193/225

18. Using XSLT, how would you extract a specific attribute from an element in an XML document?

Successful candidates should recognize this as one of the most basic applications of XSLT. If they are not ableto construct a reply similar to the example below, they should at least be able to identify the componentsnecessary for this operation: xsl:template to match the appropriate XML element, xsl:value-of to select theattribute value, and the optional xsl:apply-templates to continue processing the document.

Extract Attributes from XML DataExample 1.<xsl:template match="element-name">

Attribute Value:<xsl:value-of select="@attribute"/><xsl:apply-templates/></xsl:template>

19. When constructing an XML DTD, how do you create an external entity reference in an attribute value?

Every interview session should have at least one trick question. Although possible when using SGML, XML DTDsdon't support defining external entity references in attribute values. It's more important for the candidate torespond to this question in a logical way than than the candidate know the somewhat obscure answer.

20. How would you build a search engine for large volumes of XML data?

The way candidates answer this question may provide insight into their view of XML data. For those who viewXML primarily as a way to denote structure for text files, a common answer is to build a full-text search andhandle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standardway of transferring structured data between disparate systems. These candidates often describe some scheme

of importing XML into a relational or object database and relying on the database's engine for searching.Lastly, candidates that have worked with vendors specializing in this area often say that the best way thehandle this situation is to use a third party software package optimized for XML data.

21. What is the difference between XML and C or C++ or Java?Updated

C and C++ (and other languages like FORTRAN, or Pascal, or Visual Basic, or Java or hundreds more) areprogramming languages with which you specify calculations, actions, and decisions to be carried out in order:mod curconfig[if left(date,6) = "01-Apr",t.put "April googlel!",f.put days('31102005','DDMMYYYY') -days(sdate,'DDMMYYYY')" more shopping days to Samhain"];XML is a markup specification language with which you can design ways of describing information (text ordata), usually for storage, transmission, or processing by a program. It says nothing about what you should do

with the data (although your choice of element names may hint at what they are for):<part num="DA42" models="LS AR DF HG KJ"update="2001-11-22"><name>Camshaft end bearing retention circlip</name><image drawing="RR98-dh37" type="SVG" x="476"y="226"/> <maker id="RQ778">Ringtown Fasteners Ltd</maker><notes>Angle-nosed insertion tool <toolid="GH25"/> is required for the removaland replacement of this part.</notes></part>On its own, an SGML or XML file (including HTML) doesn't do anything. It's a data format which just sits thereuntil you run a program which does something with it.

22. Does XML replace HTML?

No. XML itself does not replace HTML. Instead, it provides an alternative which allows you to define your ownset of markup elements. HTML is expected to remain in common use for some time to come, and the current

version of HTML is in XML syntax. XML is designed to make the writing of DTDs much simpler than with fullSGML. (See the question on DTDs for what one is and why you might want one.)

23. Do I have to know HTML or SGML before I learn XML?

No, although it's useful because a lot of XML terminology and practice derives from two decades' experience of SGML.Be aware that ‘knowing HTML’ is not the same as ‘understanding SGML’. Although HTML was written as anSGML application, browsers ignore most of it (which is why so many useful things don't work), so just becausesomething is done a certain way in HTML browsers does not mean it's correct, least of all in XML.

23. What does an XML document actually look like (inside)?

The basic structure of XML is similar to other applications of SGML, including HTML. The basic components canbe seen in the following examples. An XML document starts with a Prolog:

1. The XML Declarationwhich specifies that this is an XML document;2. Optionally a Document Type Declaration

which identifies the type of document and says where the Document Type Description (DTD) is stored;The Prolog is followed by the document instance:

193

Page 194: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 194/225

1. A root element, which is the outermost (top level) element (start-tag plus end-tag) which encloseseverything else: in the examples below the root elements are conversation and titlepage;2. A structured mix of descriptive or prescriptive elements enclosing the character data content (text), andoptionally any attributes (‘name=value’ pairs) inside some start-tags.XML documents can be very simple, with straightforward nested markup of your own design:<?xml version="1.0" standalone="yes"?><conversation><br><greeting>Hello, world!</greeting><response>Stop the planet, I want to getoff!</response></conversation>Or they can be more complicated, with a Schema or question C.11, Document Type Description (DTD) orinternal subset (local DTD changes in [square brackets]), and an arbitrarily complex nested structure:<?xml version="1.0" encoding="iso-8859-1"?><!DOCTYPE titlepageSYSTEM "http://www.google.bar/dtds/typo.dtd"[<!ENTITY % active.links "INCLUDE">]><titlepage id="BG12273624"><white-space type="vertical" amount="36"/><title font="Baskerville" alignment="centered"size="24/30">Hello, world!</title><white-space type="vertical" amount="12"/><!-- In some copies the followingdecoration is hand-colored, presumablyby the author -->

<image location="http://www.google.bar/fleuron.eps"type="URI" alignment="centered"/><white-space type="vertical" amount="24"/><author font="Baskerville" size="18/22"style="italic">Vitam capias</author><white-space type="vertical" role="filler"/></titlepage>

Or they can be anywhere between: a lot will depend on how you want to define your document type (or whoseyou use) and what it will be used for. Database-generated or program-generated XML documents used in e-commerce is usually unformatted (not for human reading) and may use very long names or values, withmultiple redundancy and sometimes no character data content at all, just values in attributes:<?xml version="1.0"?> <ORDER-UPDATE AUTHMD5="4baf7d7cff5faa3ce67acf66ccda8248"ORDER-UPDATE-ISSUE="193E22C2-EAF3-11D9-9736-CAFC705A30B3"ORDER-UPDATE-DATE="2005-07-01T15:34:22.46" ORDER-UPDATE-DESTINATION="6B197E02-EAF3-11D9-

85D5-997710D9978F"ORDER-UPDATE-ORDERNO="8316ADEA-EAF3-11D9-9955-D289ECBC99F3"><ORDER-UPDATE-DELTA-MODIFICATION-DETAIL ORDER-UPDATE-ID="BAC352437484"><ORDER-UPDATE-DELTA-MODIFICATION-VALUE ORDER-UPDATE-ITEM="56"ORDER-UPDATE-QUANTITY="2000"/></ORDER-UPDATE-DELTA-MODIFICATION-DETAIL></ORDER-UPDATE>

24. How does XML handle white-space in my documents?

All white-space, including linebreaks, TAB characters, and normal spaces, even between ‘structural’ elementswhere no text can ever appear, is passed by the parser unchanged to the application (browser, formatter,viewer, converter, etc), identifying the context in which the white-space was found (element content, datacontent, or mixed content, if this information is available to the parser, eg from a DTD or Schema). This meansit is the application's responsibility to decide what to do with such space, not the parser's:

* insignificant white-space between structural elements (space which occurs where only element content isallowed, ie between other elements, where text data never occurs) will get passed to the application (in SGMLthis white-space gets suppressed, which is why you can put all that extra space in HTML documents and notworry about it)* significant white-space (space which occurs within elements which can contain text and markup mixedtogether, usually mixed content or PCDATA) will still get passed to the application exactly as under SGML. It isthe application's responsibility to handle it correctly.The parser must inform the application that white-space has occurred in element content, if it can detect it.(Users of SGML will recognize that this information is not in the ESIS, but it is in the Grove.)

<chapter><title>My title forChapter 1.</title><para>text</para></chapter>

In the example above, the application will receive all the pretty-printing linebreaks, TABs, and spaces betweenthe elements as well as those embedded in the chapter title. It is the function of the application, not the

194

Page 195: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 195/225

parser, to decide which type of white-space to discard and which to retain. Many XML applications haveconfigurable options to allow programmers or users to control how such white-space is handled.

25. Which parts of an XML document are case-sensitive?

All of it, both markup and text. This is significantly different from HTML and most other SGML applications. Itwas done to allow markup in non-Latin-alphabet languages, and to obviate problems with case-folding inwriting systems which are caseless.* Element type names are case-sensitive: you must follow whatever combination of upper- or lower-case youuse to define them (either by first usage or in a DTD or Schema). So you can't say <BODY>…</body>: upper-and lower-case must match; thus <Img/>, <IMG/>, and <img/> are three different element types;* For well-formed XML documents with no DTD, the first occurrence of an element type name defines thecasing;* Attribute names are also case-sensitive, for example the two width attributes in <PIC width="7in"/> and<PIC WIDTH="6in"/> (if they occurred in the same file) are separate attributes, because of the different caseof width and WIDTH;* Attribute values are also case-sensitive. CDATA values (eg Url="MyFile.SGML") always have been, but NAMEtypes (ID and IDREF attributes, and token list attributes) are now case-sensitive as well;* All general and parameter entity names (eg Á), and your data content (text), are case-sensitive as always.

27. How can I make my existing HTML files work in XML?

Either convert them to conform to some new document type (with or without a DTD or Schema) and write astylesheet to go with them; or edit them to conform to XHTML.It is necessary to convert existing HTML files because XML does not permit end-tag minimisation (missing

, etc), unquoted attribute values, and a number of other SGML shortcuts which have been normal in mostHTML DTDs. However, many HTML authoring tools already produce almost (but not quite) well-formed XML.You may be able to convert HTML to XHTML using the Dave Raggett's HTML Tidy program, which can clean upsome of the formatting mess left behind by inadequate HTML editors, and even separate out some of theformatting to a stylesheet, but there is usually still some hand-editing to do.

28. Is there an XML version of HTML?

Yes, the W3C recommends using XHTML which is ‘a reformulation of HTML 4 in XML 1.0’. This specificationdefines HTML as an XML application, and provides three DTDs corresponding to the ones defined by HTML 4.*(Strict, Transitional, and Frameset).The semantics of the elements and their attributes are as defined in the W3C Recommendation for HTML 4.These semantics provide the foundation for future extensibility of XHTML. Compatibility with existing HTMLbrowsers is possible by following a small set of guidelines (see the W3C site).

29. If XML is just a subset of SGML, can I use XML files directly with existing SGML tools?

Yes, provided you use up-to-date SGML software which knows about the WebSGML Adaptations TC to ISO8879 (the features needed to support XML, such as the variant form for EMPTY elements; some aspects of theSGML Declaration such as NAMECASE GENERAL NO; multiple attribute token list declarations, etc).An alternative is to use an SGML DTD to let you create a fully-normalised SGML file, but one which does notuse empty elements; and then remove the DocType Declaration so it becomes a well-formed DTDless XML file.Most SGML tools now handle XML files well, and provide an option switch between the two standards.

30. Can XML use non-Latin characters?

Yes, the XML Specification explicitly says XML uses ISO 10646, the international standard character repertoirewhich covers most known languages. Unicode is an identical repertoire, and the two standards track eachother. The spec says (2.2): ‘All XML processors must accept the UTF-8 and UTF-16 encodings of ISO 10646…’.There is a Unicode FAQ at http://www.unicode.org/faq/FAQ.UTF-8 is an encoding of Unicode into 8-bit characters: the first 128 are the same as ASCII, and higher-ordercharacters are used to encode anything else from Unicode into sequences of between 2 and 6 bytes. UTF-8 inits single-octet form is therefore the same as ISO 646 IRV (ASCII), so you can continue to use ASCII forEnglish or other languages using the Latin alphabet without diacritics. Note that UTF-8 is incompatible with ISO8859-1 (ISO Latin-1) after code point 127 decimal (the end of ASCII).UTF-16 is an encoding of Unicode into 16-bit characters, which lets it represent 16 planes. UTF-16 isincompatible with ASCII because it uses two 8-bit bytes per character (four bytes above U+FFFF).

31. What's a Document Type Definition (DTD) and where do I get one?

A DTD is a description in XML Declaration Syntax of a particular type or class of document. It sets out whatnames are to be used for the different types of element, where they may occur, and how they all fit together.(A question C.16, Schema does the same thing in XML Document Syntax, and allows more extensive data-checking.)For example, if you want a document type to be able to describe Lists which contain Items, the relevant part of your DTD might contain something like this:<!ELEMENT List (Item)+>

<!ELEMENT Item (#PCDATA)>

This defines a list as an element type containing one or more items (that's the plus sign); and it defines itemsas element types containing just plain text (Parsed Character Data or PCDATA). Validators read the DTD beforethey read your document so that they can identify where every element type ought to come and how eachrelates to the other, so that applications which need to know this in advance (most editors, search engines,

195

Page 196: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 196/225

navigators, and databases) can set themselves up correctly. The example above lets you create lists like:

<List><Item>Chocolate</Item><Item>Music</Item><Item>Surfingv</Item></List>

(The indentation in the example is just for legibility while editing: it is not required by XML.)A DTD provides applications with advance notice of what names and structures can be used in a particulardocument type. Using a DTD and a validating editor means you can be certain that all documents of thatparticular type will be constructed and named in a consistent and conformant manner.DTDs are not required for processing the tip in question Bwell-formed documents, but they are needed if youwant to take advantage of XML's special attribute types like the built-in ID/IDREF cross-reference mechanism;or the use of default attribute values; or references to external non-XML files (‘Notations’); or if you simplywant a check on document validity before processing.There are thousands of DTDs already in existence in all kinds of areas (see the SGML/XML Web pages forpointers). Many of them can be downloaded and used freely; or you can write your own (see the question oncreating your own DTD. Old SGML DTDs need to be converted to XML for use with XML systems: read thequestion on converting SGML DTDs to XML, but most popular SGML DTDs are already available in XML form.The alternatives to a DTD are various forms of question C.16, Schema. These provide more extensivevalidation features than DTDs, including character data content validation.

32. Does XML let me make up my own tags?

No, it lets you make up names for your own element types. If you think tags and elements are the same thing

you are already in considerable trouble: read the rest of this question carefully.

33. How do I create my own document type?

Document types usually need a formal description, either a DTD or a Schema. Whilst it is possible to processwell-formed XML documents without any such description, trying to create them without one is asking fortrouble. A DTD or Schema is used with an XML editor or API interface to guide and control the construction of the document, making sure the right elements go in the right places.Creating your own document type therefore begins with an analysis of the class of documents you want todescribe: reports, invoices, letters, configuration files, credit-card verification requests, or whatever. Once youhave the structure correct, you write code to express this formally, using DTD or Schema syntax.

34. How do I write my own DTD?

You need to use the XML Declaration Syntax (very simple: declaration keywords begin withBecause there is no other element which contains Shopping-List, that element is assumed to be the ‘root’ element, which encloses everything else in the document. You can now use it to create an XML file: give youreditor the declarations:<?xml version="1.0"?><!DOCTYPE Shopping-List SYSTEM "shoplist.dtd">

(assuming you put the DTD in that file). Now your editor will let you create files according to the pattern:<Shopping-List>

<Item>Chocolate</Item><Item>Sugar</Item><Item>Butter</Item></Shopping-List>

It is possible to develop complex and powerful DTDs of great subtlety, but for any significant use you shouldlearn more about document systems analysis and document type design. See for example Developing SGML

DTDs: From Text to Model to Markup (Maler and el Andaloussi, 1995): this was written for SGML but perhaps95% of it applies to XML as well, as XML is much simpler than full SGML—see the list of restrictions whichshows what has been cut out.

WarningIncidentally, a DTD file never has a DOCTYPE Declaration in it: that only occurs in an XML document instance(it's what references the DTD). And a DTD file also never has an XML Declaration at the top either.Unfortunately there is still software around which inserts one or both of these.

35. Can a root element type be explicitly declared in the DTD?

No. This is done in the document's Document Type Declaration, not in the DTD.

36. I keep hearing about alternatives to DTDs. What's a Schema?

The W3C XML Schema recommendation provides a means of specifying formal data typing and validation of element content in terms of data types, so that document type designers can provide criteria for checking the

data content of elements as well as the markup itself. Schemas are written in XML Document Syntax, like XMLdocuments are, avoiding the need for processing software to be able to read XML Declaration Syntax (used forDTDs).There is a separate Schema FAQ at http://www.schemavalid.comFAQ. The term ‘vocabulary’ is sometimesused to refer to DTDs and Schemas together. Schemas are aimed at e-commerce, data control, and database-style applications where character data content requires validation and where stricter data control is neededthan is possible with DTDs; or where strong data typing is required. They are usually unnecessary for

196

Page 197: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 197/225

traditional text document publishing applications.Unlike DTDs, Schemas cannot be specified in an XML Document Type Declaration. They can be specified in aNamespace, where Schema-aware software should pick it up, but this is optional:

<invoice id="abc123"xmlns="http://example.org/ns/books/"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://acme.wilycoyote.org/xsd/invoice.xsd">...</invoice>

More commonly, you specify the Schema in your processing software, which should record separately whichSchema is used by which XML document instance.In contrast to the complexity of the W3C Schema model, Relax NG is a lightweight, easy-to-use XML schemalanguage devised by James Clark (see http://relaxng.org/) with development hosted by OASIS. It allowssimilar richness of expression and the use of XML as its syntax, but it provides an additional, simplified, syntaxwhich is easier to use for those accustomed to DTDs.

37. How do I get XML into or out of a database?

Ask your database manufacturer: they all provide XML import and export modules to connect XML applicationswith databases. In some trivial cases there will be a 1:1 match between field names in the database table andelement type names in the XML Schema or DTD, but in most cases some programming will be required toestablish the desired match. This can usually be stored as a procedure so that subsequent uses are simplycommands or calls with the relevant parameters.

In less trivial, but still simple, cases, you could export by writing a report routine that formats the output as anXML document, and you could import by writing an XSLT transformation that formatted the XML data as a loadfile.

38. Can I encode mathematics using XML?Updated

Yes, if the document type you use provides for math, and your users' browsers are capable of rendering it. Themathematics-using community has developed the MathML Recommendation at the W3C, which is a native XMLapplication suitable for embedding in other DTDs and Schemas.It is also possible to make XML fragments from other DTDs, such as ISO 12083 Math, or OpenMath, or one of your own making. Browsers which display math embedded in SGML existed for many years (eg DynaText,Panorama, Multidoc Pro), and mainstream browsers are now rendering MathML. David Carlisle has produced aset of stylesheets for rendering MathML in browsers. It is also possible to use XSLT to convert XML mathmarkup to LATEX for print (PDF) rendering, or to use XSL:FO.Please note that XML is not itself a programming language, so concepts such as arithmetic and if-statements

(if-then-else logic) are not meaningful in XML documents.39. How will XML affect my document links?

The linking abilities of XML systems are potentially much more powerful than those of HTML, so you'll be ableto do much more with them. Existing href-style links will remain usable, but the new linking technology isbased on the lessons learned in the development of other standards involving hypertext, such as TEI andHyTime, which let you manage bidirectional and multi-way links, as well as links to a whole element or span of text (within your own or other documents) rather than to a single point. These features have been available toSGML users for many years, so there is considerable experience and expertise available in using them.Currently only Mozilla Firefox implements XLink.The XML Linking Specification (XLink) and the XML Extended Pointer Specification (XPointer) documentscontain the details. An XLink can be either a URI or a TEI-style Extended Pointer (XPointer), or both. A URI onits own is assumed to be a resource; if an XPointer follows it, it is assumed to be a sub-resource of that URI;an XPointer on its own is assumed to apply to the current document (all exactly as with HTML).An XLink may use one of #, ?, or |. The # and ? mean the same as in HTML applications; the | means the sub-resource can be found by applying the link to the resource, but the method of doing this is left to the

application. An XPointer can only follow a #.The TEI Extended Pointer Notation (EPN) is much more powerful than the fragment address on the end of some URIs, as it allows you to specify the location of a link end using the structure of the document as well as(or in addition to) known, fixed points like IDs. For example, the linked second occurrence of the word

 ‘XPointer’ two paragraphs back could be referred to with the URI (shown here with linebreaks and spaces forclarity: in practice it would of course be all one long string):

http://xml.silmaril.ie/faq.xml#ID(hypertext).child(1,#element,'answer').child(2,#element,'para').child(1,#element,'link')This means the first link element within the second paragraph within the answer in the element whose ID ishypertext (this question). Count the objects from the start of this question (which has the ID hypertext) in theXML source:1. the first child object is the element containing the question ();

2. the second child object is the answer (the element);3. within this element go to the second paragraph;4. find the first link element.Eve Maler explained the relationship of XLink and XPointer as follows:XLink governs how you insert links into your XML document, where the link might point to anything (eg a GIFfile); XPointer governs the fragment identifier that can go on a URL when you're linking to an XML document,from anywhere (eg from an HTML file).

197

Page 198: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 198/225

[Or indeed from an XML file, a URI in a mail message, etc…Ed.]David Megginson has produced an xpointer function for Emacs/psgml which will deduce an XPointer for anylocation in an XML document. XML Spy has a similar function.

40. How does XML handle metadata?

Because XML lets you define your own markup languages, you can make full use of the extended hypertextfeatures of XML (see the question on Links) to store or link to metadata in any format (eg using ISO 11179, asa Topic Maps Published Subject, with Dublin Core, Warwick Framework, or with Resource DescriptionFramework (RDF), or even Platform for Internet Content Selection (PICS)).There are no predefined elements in XML, because it is an architecture, not an application, so it is not part of XML's job to specify how or if authors should or should not implement metadata. You are therefore free to useany suitable method. Browser makers may also have their own architectural recommendations or methods topropose.

41. Can I use JavaScript, ActiveX, etc in XML files?

This will depend on what facilities your users' browsers implement. XML is about describing information;scripting languages and languages for embedded functionality are software which enables the information to bemanipulated at the user's end, so these languages do not normally have any place in an XML file itself, but instylesheets like XSL and CSS where they can be added to generated HTML.XML itself provides a way to define the markup needed to implement scripting languages: as a neutralstandard it neither encourages not discourages their use, and does not favour one language over another, so itis possible to use XML markup to store the program code, from where it can be retrieved by (for example)XSLT and re-expressed in a HTML script element.

Server-side script embedding, like PHP or ASP, can be used with the relevant server to modify the XML code onthe fly, as the document is served, just as they can with HTML. Authors should be aware, however, thatembedding server-side scripting may mean the file as stored is not valid XML: it only becomes valid whenprocessed and served, so care must be taken when using validating editors or other software to handle ormanage such files. A better solution may be to use an XML serving solution like Cocoon, AxKit, or PropelX.

42. Can I use Java to create or manage XML files?

Yes, any programming language can be used to output data from any source in XML format. There is a growingnumber of front-ends and back-ends for programming environments and data management environments toautomate this. Java is just the most popular one at the moment.There is a large body of middleware (APIs) written in Java and other languages for managing data either inXML or with XML input or output.

43. How do I execute or run an XML file?

You can't and you don't. XML itself is not a programming language, so XML files don't ‘run’ or ‘execute’. XML isa markup specification language and XML files are just data: they sit there until you run a program whichdisplays them (like a browser) or does some work with them (like a converter which writes the data in anotherformat, or a database which reads the data), or modifies them (like an editor).If you want to view or display an XML file, open it with an XML editor or an question B.3, XML browser.The water is muddied by XSL (both XSLT and XSL:FO) which use XML syntax to implement a declarativeprogramming language. In these cases it is arguable that you can ‘execute’ XML code, by running a processingapplication like Saxon, which compiles the directives specified in XSLT files into Java bytecode to process XML.

44. How do I control formatting and appearance?

In HTML, default styling was built into the browsers because the tagset of HTML was predefined and hardwiredinto browsers. In XML, where you can define your own tagset, browsers cannot possibly be expected to guessor know in advance what names you are going to use and what they will mean, so you need a stylesheet if youwant to display formatted text.Browsers which read XML will accept and use a CSS stylesheet at a minimum, but you can also use the morepowerful XSLT stylesheet language to transform your XML into HTML—which browsers, of course, already knowhow to display (and that HTML can still use a CSS stylesheet). This way you get all the document managementbenefits of using XML, but you don't have to worry about your readers needing XML smarts in their browsers.

45. How do I use graphics in XML?

Graphics have traditionally just been links which happen to have a picture file at the end rather than anotherpiece of text. They can therefore be implemented in any way supported by the XLink and XPointerspecifications (see question C.18, ‘How will XML affect my document links?’), including using similar syntax toexisting HTML images. They can also be referenced using XML's built-in NOTATION and ENTITY mechanism in asimilar way to standard SGML, as external unparsed entities.However, the SVG specification (see the tip below, by Peter Murray-Rust) lets you use XML markup to drawvector graphics objects directly in your XML file. This provides enormous power for the inclusion of portablegraphics, especially interactive or animated sequences, and it is now slowly becoming supported in browsers.

The XML linking specifications for external images give you much better control over the traversal andactivation of links, so an author can specify, for example, whether or not to have an image appear when thepage is loaded, or on a click from the user, or in a separate window, without having to resort to scripting.XML itself doesn't predicate or restrict graphic file formats: GIF, JPG, TIFF, PNG, CGM, EPS, and SVG at aminimum would seem to make sense; however, vector formats (EPS, SVG) are normally essential for non-photographic images (diagrams).

198

Page 199: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 199/225

You cannot embed a raw binary graphics file (or any other binary [non-text] data) directly into an XML filebecause any bytes happening to resemble markup would get misinterpreted: you must refer to it by linking(see below). It is, however, possible to include a text-encoded transformation of a binary file as a CDATAMarked Section, using something like UUencode with the markup characters ], & and > removed from the mapso that they could not occur as an erroneous CDATA termination sequence and be misinterpreted. You couldeven use simple hexadecimal encoding as used in PostScript. For vector graphics, however, the solution is touse SVG (see the tip below, by Peter Murray-Rust).Sound files are binary objects in the same way that external graphics are, so they can only be referencedexternally (using the same techniques as for graphics). Music files written in MusiXML or an XML variant of SMDL could however be embedded in the same way as for SVG.The point about using entities to manage your graphics is that you can keep the list of entity declarationsseparate from the rest of the document, so you can re-use the names if an image is needed more than once,but only store the physical file specification in a single place. This is available only when using a DTD, not aSchema.

46. How do I include one XML file in another?

This works exactly the same as for SGML. First you declare the entity you want to include, and then youreference it by name:<?xml version="1.0"?><!DOCTYPE novel SYSTEM "/dtd/novel.dtd" [<!ENTITY chap1 SYSTEM "mydocs/chapter1.xml"><!ENTITY chap2 SYSTEM "mydocs/chapter2.xml"><!ENTITY chap3 SYSTEM "mydocs/chapter3.xml"><!ENTITY chap4 SYSTEM "mydocs/chapter4.xml">

<!ENTITY chap5 SYSTEM "mydocs/chapter5.xml">]><novel><header>...blah blah...</header>&chap1;&chap2;&chap3;&chap4;&chap5;</novel>

The difference between this method and the one used for including a DTD fragment (see question D.15, ‘Howdo I include one DTD (or fragment) in another?’) is that this uses an external general (file) entity which is

referenced in the same way as for a character entity (with an ampersand).The one thing to make sure of is that the included file must not have an XML or DOCTYPE Declaration on it. If you've been using one for editing the fragment, remove it before using the file in this way. Yes, this is a pain inthe butt, but if you have lots of inclusions like this, write a script to strip off the declaration (and paste it backon again for editing).

47. What is parsing and how do I do it in XML

Parsing is the act of splitting up information into its component parts (schools used to teach this in languageclasses until the teaching profession collectively caught the anti-grammar disease).

 ‘Mary feeds Spot’ parses as1. Subject = Mary, proper noun, nominative case2. Verb = feeds, transitive, third person singular, present tense3. Object = Spot, proper noun, accusative caseIn computing, a parser is a program (or a piece of code or API that you can reference inside your own

programs) which analyses files to identify the component parts. All applications that read input have a parserof some kind, otherwise they'd never be able to figure out what the information means. Microsoft Wordcontains a parser which runs when you open a .doc file and checks that it can identify all the hidden codes.Give it a corrupted file and you'll get an error message.XML applications are just the same: they contain a parser which reads XML and identifies the function of eachthe pieces of the document, and it then makes that information available in memory to the rest of theprogram.While reading an XML file, a parser checks the syntax (pointy brackets, matching quotes, etc) for well-formedness, and reports any violations (reportable errors). The XML Specification lists what these are.Validation is another stage beyond parsing. As the component parts of the program are identified, a validatingparser can compare them with the pattern laid down by a DTD or a Schema, to check that they conform. In theprocess, default values and datatypes (if specified) can be added to the in-memory result of the validation thatthe validating parser gives to the application.

<person corpid="abc123" birth="1960-02-31" gender="female"> <name> <forename>Judy</forename><surname>O'Grady</surname> </name> </person>The example above parses as: 1. Element person identified with Attribute corpid containing abc123 andAttribute birth containing 1960-02-31 and Attribute gender containing female containing ...2. Element name containing ...3. Element forename containing text ‘Judy’ followed by ...4. Element surname containing text ‘O'Grady’ (and lots of other stuff too).

199

Page 200: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 200/225

As well as built-in parsers, there are also stand-alone parser-validators, which read an XML file and tell you if they find an error (like missing angle-brackets or quotes, or misplaced markup). This is essential for testingfiles in isolation before doing something else with them, especially if they have been created by hand withoutan XML editor, or by an API which may be too deeply embedded elsewhere to allow easy testing.

48. When should I use a CDATA Marked Section?

You should almost never need to use CDATA Sections. The CDATA mechanism was designed to let an authorquote fragments of text containing markup characters (the open-angle-bracket and the ampersand), forexample when documenting XML (this FAQ uses CDATA Sections quite a lot, for obvious reasons). A CDATASection turns off markup recognition for the duration of the section (it gets turned on again only by the closingsequence of double end-square-brackets and a close-angle-bracket).Consequently, nothing in a CDATA section can ever be recognised as anything to do with markup: it's just astring of opaque characters, and if you use an XML transformation language like XSLT, any markup charactersin it will get turned into their character entity equivalent.If you try, for example, to use:some text with <![CDATA[markup]]> in it.in the expectation that the embedded markup would remain untouched, it won't: it will just outputsome text with <em>markup</em> in it.In other words, CDATA Sections cannot preserve the embedded markup as markup. Normally this is exactlywhat you want because this technique was designed to let people do things like write documentation aboutmarkup. It was not designed to allow the passing of little chunks of (possibly invalid) unparsed HTMLembedded inside your own XML through to a subsequent process—because that would risk invalidating theoutput.As a result you cannot expect to keep markup untouched simply because it looked as if it was safely ‘hidden’ 

inside a CDATA section: it can't be used as a magic shield to preserve HTML markup for future use as markup,only as characters.

49. How can I handle embedded HTML in my XML

Apart from using CDATA Sections, there are two common occasions when people want to handle embeddedHTML inside an XML element:1. when they have received (possibly poorly-designed) XML from somewhere else which they must find a wayto handle;2. when they have an application which has been explicitly designed to store a string of characters containing< and & character entity references with the objective of turning them back into markup in a later process (egFreeMind, Atom).Generally, you want to avoid this kind of trick, as it usually indicates that the document structure and designhas been insufficiently thought out. However, there are occasions when it becomes unavoidable, so if youreally need or want to use embedded HTML markup inside XML, and have it processable later as markup, there

are a couple of techniques you may be able to use:* Provide templates for the handling of that markup in your XSLT transformation or whatever software you usewhich simply replicates what was there, eg<xsl:template match="b"><b><xsl:apply-templates/></b></xsl:template/>* Use XSLT's ‘deep copy’ instruction, which outputs nested well-formed markup verbatim, eg<xsl:template match="ol"><xsl:copy-of select="."/></xsl:template/>* As a last resort, use the disable-output-escaping attribute on the xsl:text element of XSL[T] which isavailable in some processors, eg<xsl:text disable-output-escaping="yes"><![CDATA[<b>Now!</b>]]></xsl:text>

* Some processors (eg JX) are now providing their own equivalents for disabling output escaping. Theirproponents claim it is ‘highly desirable’ or ‘what most people want’, but it still needs to be treated with care toprevent unwanted (possibly dangerous) arbitrary code from being passed untouched through your system. Italso adds another dependency to your software.For more details of using these techniques in XSL[T], see the relevant question in the XSL FAQ.

50. What are the special characters in XML

For normal text (not markup), there are no special characters: just make sure your document refers to thecorrect encoding scheme for the language and/or writing system you want to use, and that your computercorrectly stores the file using that encoding scheme. See the question on non-Latin characters for a longerexplanation.If your keyboard will not allow you to type the characters you want, or if you want to use characters outsidethe limits of the encoding scheme you have chosen, you can use a symbolic notation called ‘entity referencing’.Entity references can either be numeric, using the decimal or hexadecimal Unicode code point for the character(eg if your keyboard has no Euro symbol (€) you can type €); or they can be character, using an establishedname which you declare in your DTD (eg ) and then use as € in your document. If you are using a Schema,you must use the numeric form for all except the five below because Schemas have no way to make characterentity declarations.If you use XML with no DTD, then these five character entities are assumed to be predeclared, and you can usethem without declaring them:&lt;

200

Page 201: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 201/225

The less-than character (<) starts element markup (the first character of a start-tag or an end-tag).&amp;

The ampersand character (>) starts entity markup (the first character of a character entity reference).&gt;The greater-than character (>) ends a start-tag or an end-tag.&quot;The double-quote character (") can be symbolised with this character entity reference when you need toembed a double-quote inside a string which is already double-quoted.&apos;The apostrophe or single-quote character (') can be symbolised with this character entity reference when youneed to embed a single-quote or apostrophe inside a string which is already single-quoted.If you are using a DTD then you must declare all the character entities you need to use (if any), including anyof the five above that you plan on using (they cease to be predeclared if you use a DTD). If you are using aSchema, you must use the numeric form for all except the five above because Schemas have no way to makecharacter entity declarations.

51. Do I have to change any of my server software to work with XML?

The only changes needed are to make sure your server serves up .xml, .css, .dtd, .xsl, and whatever other filetypes you will use as the correct MIME content (media) types.The details of the settings are specified in RFC 3023. Most new versions of Web server software come preset.If not, all that is needed is to edit the mime-types file (or its equivalent: as a server operator you already knowwhere to do this, right?) and add or edit the relevant lines for the right media types. In some servers (egApache), individual content providers or directory owners may also be able to change the MIME types for

specific file types from within their own directories by using directives in a .htaccess file. The media typesrequired are:* text/xml for XML documents which are ‘readable by casual users’;* application/xml for XML documents which are ‘unreadable by casual users’;* text/xml-external-parsed-entity for external parsed entities such as document fragments (eg separatechapters which make up a book) subject to the readability distinction of text/xml;* application/xml-external-parsed-entity for external parsed entities subject to the readability distinction of application/xml;* application/xml-dtd for DTD files and modules, including character entity sets.The RFC has further suggestions for the use of the +xml media type suffix for identifying ancillary files such asXSLT (application/xslt+xml).If you run scripts generating XHTML which you wish to be treated as XML rather than HTML, they may need tobe modified to produce the relevant Document Type Declaration as well as the right media type if yourapplication requires them to be validated.

51. I'm trying to understand the XML Spec: why does it have such difficult terminology?

For implementation to succeed, the terminology needs to be precise. Design goal eight of the specification tellsus that ‘the design of XML shall be formal and concise’. To describe XML, the specification therefore usesformal language drawn from several fields, specifically those of text engineering, international standards andcomputer science. This is often confusing to people who are unused to these disciplines because they use well-known English words in a specialised sense which can be very different from their common meanings—forexample: grammar, production, token, or terminal.The specification does not explain these terms because of the other part of the design goal: the specificationshould be concise. It doesn't repeat explanations that are available elsewhere: it is assumed you know this andeither know the definitions or are capable of finding them. In essence this means that to grok the fullness of the spec, you do need a knowledge of some SGML and computer science, and have some exposure to thelanguage of formal standards.Sloppy terminology in specifications causes misunderstandings and makes it hard to implement consistently, soformal standards have to be phrased in formal terminology. This FAQ is not a formal document, and the astute

reader will already have noticed it refers to ‘element names’ where ‘element type names’ is more correct; butthe former is more widely understood.

52. Can I still use server-side inclusions?

Yes, so long as what they generate ends up as part of an XML-conformant file (ie either valid or just well-formed).Server-side tag-replacers like shtml, PHP, JSP, ASP, Zope, etc store almost-valid files using comments,Processing Instructions, or non-XML markup, which gets replaced at the point of service by text or XML markup(it is unclear why some of these systems use non-HTML/XML markup). There are also some XML-basedpreprocessors for formats like XVRL (eXtensible Value Resolution Language) which resolve specialisedreferences to external data and output a normalised XML file.

53. Can I (and my authors) still use client-side inclusions?

The same rule applies as for server-side inclusions, so you need to ensure that any embedded code which gets

passed to a third-party engine (eg calls to SQL, VB, Java, etc) does not contain any characters which might bemisinterpreted as XML markup (ie no angle brackets or ampersands). Either use a CDATA marked section toavoid your XML application parsing the embedded code, or use the standard <, and & character entityreferences instead.

54. How can I include a conditional statement in my XML?

201

Page 202: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 202/225

You can't: XML isn't a programming language, so you can't say things like<google if {DB}="A">bar</google>If you need to make an element optional, based on some internal or external criteria, you can do so in aSchema. DTDs have no internal referential mechanism, so it isn't possible to express this kind of conditionalityin a DTD at the individual element level.It is possible to express presence-or-absence conditionality in a DTD for the whole document, by usingparameter entities as switches to include or ignore certain sections of the DTD based on settings eitherhardwired in the DTD or supplied in the internal subset. Both the TEI and Docbook DTDs use this mechanism toimplement modularity.Alternatively you can make the element entirely optional in the DTD or Schema, and provide code in yourprocessing software that checks for its presence or absence. This defers the checking until the processingstage: one of the reasons for Schemas is to provide this kind of checking at the time of document creation orediting.

55. I have to do an overview of XML for my manager/client/investor/advisor. What should I mention?

• XML is not a markup language. XML is a ‘metalanguage’, that is, it's a language that lets you defineyour own markup languages (see definition).* XML is a markup language [two (seemingly) contradictory statements one after another is anattention-getting device that I'm fond of], not a programming language. XML is data: is does not ‘do’ anything, it has things done to it.* XML is non-proprietary: your data cannot be held hostage by someone else.* XML allows multi-purposing of your data.* Well-designed XML applications most often separate ‘content’ from ‘presentation’. You shoulddescribe what something is rather what something looks like (the exception being data content which

never gets presented to humans).Saying ‘the data is in XML’ is a relatively useless statement, similar to saying ‘the book is in a naturallanguage’. To be useful, the former needs to specify ‘we have used XML to define our own markuplanguage’ (and say what it is), similar to specifying ‘the book is in French’.A classic example of multipurposing and separation that I often use is a pharmaceutical company.They have a large base of data on a particular drug that they need to publish as:* reports to the FDA;* drug information for publishers of drug directories/catalogs;* ‘prescribe me!’ brochures to send to doctors;* little pieces of paper to tuck into the boxes;* labels on the bottles;* two pages of fine print to follow their ad in Reader's Digest;* instructions to the patient that the local pharmacist prints out;* etc.Without separation of content and presentation, they need to maintain essentially identical

information in 20 places. If they miss a place, people die, lawyers get rich, and the drug companygets poor. With XML (or SGML), they maintain one set of carefully validated information, and write 20programs to extract and format it for each application. The same 20 programs can now be applied toall the hundreds of drugs that they sell.In the Web development area, the biggest thing that XML offers is fixing what is wrong with HTML:* browsers allow non-compliant HTML to be presented;* HTML is restricted to a single set of markup (‘tagset’).If you let broken HTML work (be presented), then there is no motivation to fix it. Web pages aretherefore tag soup that are useless for further processing. XML specifies that processing must notcontinue if the XML is non-compliant, so you keep working at it until it complies. This is more work upfront, but the result is not a dead-end.If you wanted to mark up the names of things: people, places, companies, etc in HTML, you don'thave many choices that allow you to distinguish among them. XML allows you to name things as whatthey are:<person>Charles Goldfarb</person> worked

at <company>IBM</company>gives you a flexibility that you don't have with HTML:<B>Charles Goldfarb</B> worked at<B>IBM<</B>With XML you don't have to shoe-horn your data into markup that restricts your options.

56. What is the purpose of XML namespaces?

XML namespaces are designed to provide universally unique names for elements and attributes. This allowspeople to do a number of things, such as:* Combine fragments from different documents without any naming conflicts. (See example below.)* Write reusable code modules that can be invoked for specific elements and attributes. Universally uniquenames guarantee that such modules are invoked only for the correct elements and attributes.* Define elements and attributes that can be reused in other schemas or instance documents without fear of name collisions. For example, you might use XHTML elements in a parts catalog to provide part descriptions.Or you might use the nil attribute defined in XML Schemas to indicate a missing value.As an example of how XML namespaces are used to resolve naming conflicts in XML documents that containelement types and attributes from multiple XML languages, consider the following two XML documents:<?xml version="1.0" ?><Address><Street>Apple 7</Street><City>Color</City><State>State</State>

202

Page 203: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 203/225

<Country>Country</Country><PostalCode>H98d69</PostalCode></Address>and:<?xml version="1.0" ?><Server><Name>OurWebServer</Name><Address>888.90.67.8</Address></Server>

Each document uses a different XML language and each language defines an Address element type. Each of these Address element types is different -- that is, each has a different content model, a different meaning,and is interpreted by an application in a different way. This is not a problem as long as these element typesexist only in separate documents. But what if they are combined in the same document, such as a list of departments, their addresses, and their Web servers? How does an application know which Address elementtype it is processing?One solution is to simply rename one of the Address element types -- for example, we could rename thesecond element type IPAddress. However, this is not a useful long term solution. One of the hopes of XML isthat people will standardize XML languages for various subject areas and write modular code to process thoselanguages. By reusing existing languages and code, people can quickly define new languages and writeapplications that process them. If we rename the second Address element type to IPAddress, we will break anycode that expects the old name.A better answer is to assign each language (including its Address element type) to a different namespace. Thisallows us to continue using the Address name in each language, but to distinguish between the two differentelement types. The mechanism by which we do this is XML namespaces.

(Note that by assigning each Address name to an XML namespace, we actually change the name to a two-partname consisting of the name of the XML namespace plus the name Address. This means that any code thatrecognizes just the name Address will need to be changed to recognize the new two-part name. However, thisonly needs to be done once, as the two-part name is universally unique.

57. What is an XML namespace?

An XML namespace is a collection of element type and attribute names. The collection itself is unimportant -- infact, a reasonable argument can be made that XML namespaces don't actually exist as physical or conceptualentities . What is important is the name of the XML namespace, which is a URI. This allows XML namespaces toprovide a two-part naming system for element types and attributes. The first part of the name is the URI usedto identify the XML namespace -- the namespace name. The second part is the element type or attribute nameitself -- the local part, also known as the local name. Together, they form the universal name.This two-part naming system is the only thing defined by the XML namespaces recommendation.

58. Does the XML namespaces recommendation define anything except a two-part naming system for elementtypes and attributes?

No.This is a very important point and a source of much confusion, so we will repeat it:THE XML NAMESPACES RECOMMENDATION DOES NOT DEFINE ANYTHING EXCEPT A TWO-PART NAMINGSYSTEM FOR ELEMENT TYPES AND ATTRIBUTES.In particular, they do not provide or define any of the following:* A way to merge two documents that use different DTDs.* A way to associate XML namespaces and schema information.* A way to validate documents that use XML namespaces.* A way to associate element type or attribute declarations in a DTD with an XML namespace.

58. What do XML namespaces actually contain?

XML namespaces are collections of names, nothing more. That is, they contain the names of element types andattributes, not the elements or attributes themselves. For example, consider the following document.<google:A xmlns:google="http://www.google.org/"><B google:C="google" D="bar"/></google:A>The element type name A and the attribute name C are in the http://www.google.org/ namespace becausethey are mapped there by the google prefix. The element type name B and the attribute name D are not in anyXML namespace because no prefix maps them there. On the other hand, the elements A and B and theattributes C and D are not in any XML namespace, even though they are physically within the scope of thehttp://www.google.org/ namespace declaration. This is because XML namespaces contain names, not elementsor attributes.XML namespaces also do not contain the definitions of the element types or attributes. This is an importantdifference, as many people are tempted to think of an XML namespace as a schema, which it is not.

59. Are the names of all element types and attributes in some XML namespace?

No.If an element type or attribute name is not specifically declared to be in an XML namespace -- that is, it isunprefixed and (in the case of element type names) there is no default XML namespace -- then that name isnot in any XML namespace. If you want, you can think of it as having a null URI as its name, although no "null"XML namespace actually exists. For example, in the following, the element type name B and the attributenames C and E are not in any XML namespace:

203

Page 204: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 204/225

<google:A xmlns:google="http://www.google.org/"><B C="bar"/><google:D E="bar"/></google:A>

60. Do XML namespaces apply to entity names, notation names, or processing instruction targets?

No.XML namespaces apply only to element type and attribute names. Furthermore, in an XML document thatconforms to the XML namespaces recommendation, entity names, notation names, and processing instructiontargets must not contain colons.

61. Who can create an XML namespace?

Anybody can create an XML namespace -- all you need to do is assign a URI as its name and decide whatelement type and attribute names are in it. The URI must be under your control and should not be being usedto identify a different XML namespace, such as by a coworker.(In practice, most people that create XML namespaces also describe the element types and attributes whosenames are in it -- their content models and types, their semantics, and so on. However, this is not part of theprocess of creating an XML namespace, nor does the XML namespace include or provide a way to discover suchinformation.)

62. Do I need to use XML namespaces?

Maybe, maybe not.

If you don't have any naming conflicts in the XML documents you are using today, as is often the case withdocuments used inside a single organization, then you probably don't need to use XML namespaces. However,if you do have conflicts today, or if you expect conflicts in the future due to distributing your documentsoutside your organization or bringing outside documents into your organization, then you should probably useXML namespaces.Regardless of whether you use XML namespaces in your own documents, it is likely that you will use them inconjunction with some other XML technology, such as XSL, XHTML, or XML Schemas. For example, thefollowing XSLT (XSL Transformations) stylesheet uses XML namespaces to distinguish between element typesdefined in XSLT and those defined elsewhere:<xsl:stylesheet version="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="Address"><!-- The Addresses element type is not part of the XSLT namespace. --><Addresses><xsl:apply-templates/>

</Addresses></xsl:template></xsl:stylesheet>

63. What is the relationship between XML namespaces and the XML 1.0 recommendation?

Although the XML 1.0 recommendation anticipated the need for XML namespaces by noting that element typeand attribute names should not include colons, it did not actually support XML namespaces. Thus, XMLnamespaces are layered on top of XML 1.0. In particular, any XML document that uses XML namespaces is alegal XML 1.0 document and can be interpreted as such in the absence of XML namespaces. For example,consider the following document:

<google:A xmlns:google="http://www.google.org/"><google:B google:C="bar"/></google:A>

If this document is processed by a namespace-unaware processor, that processor will see two elements whosenames are google:A and google:B. The google:A element has an attribute named xmlns:google and thegoogle:B element has an attribute named google:C. On the other hand, a namespace-aware processor will seetwo elements with universal names {http://www.google.org}A and {http://www.google.org}B. The{http://www.google.org}A does not have any attributes; instead, it has a namespace declaration that mapsthe google prefix to the URI http://www.google.org. The {http://www.google.org}B element has an attributenamed {http://www.google.org}C.Needless to say, this has led to a certain amount of confusion. One area of confusion is the relationshipbetween XML namespaces and validating XML documents against DTDs. This occurs because the XMLnamespaces recommendation did not describe how to use XML namespaces with DTDs. Fortunately, a similarsituation does not occur with XML schema languages, as all of these support XML namespaces.The other main area of confusion is in recommendations and specifications such as DOM and SAX whose firstversion predates the XML namespaces recommendation. Although these have since been updated to includeXML namespace support, the solutions have not always been pretty due to backwards compatibilityrequirements. All recommendations in the XML family now support XML namespaces.

64. What is the difference between versions 1.0 and 1.1 of the XML namspaces recommendation?

There are only two differences between XML namespaces 1.0 and XML namespaces 1.1:* Version 1.1 adds a way to undeclare prefixes. For more information, see question 4.7.* Version 1.1 uses IRIs (Internationalized Resource Identifiers) instead of URIs. Basically, URIs are restricted

204

Page 205: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 205/225

to a subset of ASCII characters, while IRIs allow much broader use of Unicode characters. For complete details,see section 9 of Namespaces in XML 1.1.NOTE: As of this writing (February, 2003), Namespaces in XML 1.1 is still a candidate recommendation and notwidely used. PART II: DECLARING AND USING XML NAMESPACES

65. How do I declare an XML namespace in an XML document?

To declare an XML namespace, you use an attribute whose name has the form:xmlns:prefix--OR--xmlnsThese attributes are often called xmlns attributes and their value is the name of the XML namespace beingdeclared; this is a URI. The first form of the attribute (xmlns:prefix) declares a prefix to be associated with theXML namespace. The second form (xmlns) declares that the specified namespace is the default XMLnamespace.For example, the following declares two XML namespaces, named http://www.google.com/ito/addresses andhttp://www.google.com/ito/servers. The first declaration associates the addr prefix with thehttp://www.google.com/ito/addresses namespace and the second declaration states that thehttp://www.google.com/ito/servers namespace is the default XML namespace.<Departmentxmlns:addr="http://www.google.com/ito/addresses"xmlns="http://www.google.com/ito/servers">NOTE: Technically, xmlns attributes are not attributes at all -- they are XML namespace declarations that justhappen to look like attributes. Unfortunately, they are not treated consistently by the various XMLrecommendations, which means that you must be careful when writing an XML application.

For example, in the XML Information Set (http://www.w3.org/TR/xml-infoset), xmlns "attributes" do notappear as attribute information items. Instead, they appear as namespace declaration information items. Onthe other hand, both DOM level 2 and SAX 2.0 treat namespace attributes somewhat ambiguously. In SAX 2.0,an application can instruct the parser to return xmlns "attributes" along with other attributes, or omit themfrom the list of attributes. Similarly, while DOM level 2 sets namespace information based on xmlns"attributes", it also forces applications to manually add namespace declarations using the same mechanism theapplication would use to set any other attributes.

66. Where can I declare an XML namespace?

You can declare an XML namespace on any element in an XML document. The namespace is in scope for thatelement and all its descendants unless it is overridden.

67. Can I use an attribute default in a DTD to declare an XML namespace?

Yes.For example, the following uses the FIXED attribute xmlns:google on the A element type to associate thegoogle prefix with the http://www.google.org/ namespace. The effect of this is that both A and B are in thehttp://www.google.org/ namespace.<?xml version="1.0" ?><!DOCTYPE google:A [<!ELEMENT google:A (google:B)><!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"><!ELEMENT google:B (#PCDATA)>]><!-- google prefix declared through default attribute. --><google:A><google:B>abc</google:B></google:A>

IMPORTANT: You should be very careful about placing XML namespace declarations in external entities(external DTDs), as non-validating parsers are not required to read these. For example, suppose the precedingDTD was placed in an external entity (google.dtd) and that the document was processed by a non-validatingparser that did not read google.dtd. This would result in a namespace error because the google prefix wasnever declared:<?xml version="1.0" ?><!-- google.dtd might not be read by non-validating parsers. --><!DOCTYPE google:A SYSTEM "google.dtd"><!-- google prefix not declared unless google.dtd is read. --><google:A><google:B>abc</google:B></google:A>

68. Do the default values of xmlns attributes declared in the DTD apply to the DTD?

No.Declaring a default value of an xmlns attribute in the DTD does not declare an XML namespace for the DTD. (Infact, no XML namespace declarations apply to DTDs.) Instead, these defaults (declarations) take effect onlywhen the attribute is instantiated on an element. For example:<?xml version="1.0" ?><!DOCTYPE google:A [

205

Page 206: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 206/225

<!ELEMENT google:A (google:B)><!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"><!ELEMENT google:B (#PCDATA)>]><google:A> <========== Namespace declaration takes effect here.<google:B>abc</google:B></google:A> <========= Namespace declaration ends here.For more information, see question 7.2. (Note that an earlier version of MSXML (the parser used by InternetExplorer) did use fixed xmlns attribute declarations as XML namespace declarations, but that this was removedin MSXML 4.

69. How do I override an XML namespace declaration that uses a prefix?

To override the prefix used in an XML namespace declaration, you simply declare another XML namespace withthe same prefix. For example, in the following, the google prefix is associated with the http://www.google.org/namespace on the A and B elements and the http://www.bar.org/ namespace on the C and D elements. Thatis, the names A and B are in the http://www.google.org/ namespace and the names C and D are in thehttp://www.bar.org/ namespace.

<google:A xmlns:google="http://www.google.org/"><google:B><google:C xmlns:google="http://www.bar.org/"><google:D>abcd</google:D></google:C>

</google:B></google:A>

In general, this leads to documents that are confusing to read and should be avoided.

70. How do I override a default XML namespace declaration?

To override the current default XML namespace, you simply declare another XML namespace as the default. Forexample, in the following, the default XML namespace is the http://www.google.org/ namespace on the A andB elements and the http://www.bar.org/ namespace on the C and D elements. That is, the names A and B arein the http://www.google.org/ namespace and the names C and D are in the http://www.bar.org/ namespace.

<A xmlns="http://www.google.org/"><B><C xmlns="http://www.bar.org/">

<D>abcd</D></C></B></A>

Using multiple default XML namespaces can lead to documents that are confusing to read and should be donecarefully.

71. How do I undeclare an XML namespace prefix?

In version 1.0 of the XML namespaces recommendation, you cannot "undeclare" an XML namespace prefix. Itremains in scope until the end of the element on which it was declared unless it is overridden. Furthermore,trying to undeclare a prefix by redeclaring it with an empty (zero-length) name (URI) results in a namespaceerror. For example:

<google:A xmlns:google="http://www.google.org/"><google:B><google:C xmlns:google=""> <==== This is an error in v1.0, legal in v1.1.<google:D>abcd</google:D></google:C></google:B></google:A>

In version 1.1 of the XML namespaces recommendation [currently a candidate recommendation -- February,2003], you can undeclare an XML namespace prefix by redeclaring it with an empty name. For example, in theabove document, the XML namespace declaration xmlns:google="" is legal and removes the mapping from thegoogle prefix to the http://www.google.org URI. Because of this, the use of the google prefix in the google:Delement results in a namespace error.

71. How do I undeclare the default XML namespace?

To "undeclare" the default XML namespace, you declare a default XML namespace with an empty (zero-length)name (URI). Within the scope of this declaration, unprefixed element type names do not belong to any XMLnamespace. For example, in the following, the default XML namespace is the http://www.google.org/ for the Aand B elements and there is no default XML namespace for the C and D elements. That is, the names A and Bare in the http://www.google.org/ namespace and the names C and D are not in any XML namespace.

206

Page 207: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 207/225

<A xmlns="http://www.google.org/"><B><C xmlns=""><D>abcd</D></C></B></A>

72. Why are special attributes used to declare XML namespaces?

I don't know the answer to this question, but the likely reason is that the hope that they would simplify theprocess of moving fragments from one document to another document. An early draft of the XML namespacesrecommendation proposed using processing instructions to declare XML namespaces. While these were simpleto read and process, they weren't easy to move to other documents. Attributes, on the other hand, areintimately attached to the elements being moved.Unfortunately, this hasn't worked as well as was hoped. For example, consider the following XML document:

<google:A xmlns:google="http://www.google.org/"><google:B><google:C>bar</google:C></google:B></google:A>

Simply using a text editor to cut the fragment headed by the <B> element from one document and paste itinto another document results in the loss of namespace information because the namespace declaration is not

part of the fragment -- it is on the parent element (<A>) -- and isn't moved.Even when this is done programmatically, the situation isn't necessarily any better. For example, suppose anapplication uses DOM level 2 to "cut" the fragment from the above document and "paste" it into a differentdocument. Although the namespace information is transferred (it is carried by each node), the namespacedeclaration (xmlns attribute) is not, again because it is not part of the fragment. Thus, the application mustmanually add the declaration before serializing the document or the new document will be invalid.

73. How do different XML technologies treat XML namespace declarations?

This depends on the technology -- some treat them as attributes and some treat them as namespacedeclarations. For example, SAX1 treats them as attributes and SAX2 can treat them as attributes ornamespace declarations, depending on how the parser is configured. DOM levels 1 and 2 treat them asattributes, but DOM level 2 also interprets them as namespace declarations. XPath, XSLT, and XML Schemastreat them as namespaces declarations.The reason that different technologies treat these differently is that many of these technologies predate XML

namespaces. Thus, newer versions of them need to worry both about XML namespaces and backwardscompatibility issues.

74. How do I use prefixes to refer to element type and attribute names in an XML namespace?

Make sure you have declared the prefix and that it is still in scope . All you need to do then is prefix the localname of an element type or attribute with the prefix and a colon. The result is a qualified name, which theapplication parses to determine what XML namespace the local name belongs to.For example, suppose you have associated the serv prefix with the http://www.our.com/ito/servers namespaceand that the declaration is still in scope. In the following, serv:Address refers to the Address name in thehttp://www.our.com/ito/servers namespace. (Note that the prefix is used on both the start and end tags.)<!-- serv refers to the http://www.our.com/ito/servers namespace. --><serv:Address>127.66.67.8</serv:Address>

Now suppose you have associated the xslt prefix with the http://www.w3.org/1999/XSL/Transform namespace.In the following, xslt:version refers to the version name in the http://www.w3.org/1999/XSL/Transformnamespace:<!-- xslt refers to the http://www.w3.org/1999/XSL/Transform namespace. --><html xslt:version="1.0">

75. How do I use the default XML namespace to refer to element type names in an XML namespace?

Make sure you have declared the default XML namespace and that that declaration is still in scope . All youneed to do then is use the local name of an element type. Even though it is not prefixed, the result is still aqualified name ), which the application parses to determine what XML namespace it belongs to.For example, suppose you declared the http://www.w3.org/to/addresses namespace as the default XMLnamespace and that the declaration is still in scope. In the following, Address refers to the Address name inthe http://www.w3.org/to/addresses namespace.

<!-- http://www.w3.org/to/addresses is the default XML namespace. --><Address>123.45.67.8</Address>

76. How do I use the default XML namespace to refer to attribute names in an XML namespace?

You can't.The default XML namespace only applies to element type names, so you can refer to attribute names that arein an XML namespace only with a prefix. For example, suppose that you declared the

207

Page 208: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 208/225

http://http://www.w3.org/to/addresses namespace as the default XML namespace. In the following, the typeattribute name does not refer to that namespace, although the Address element type name does. That is, theAddress element type name is in the http://http://www.fyicneter.com/ito/addresses namespace, but the typeattribute name is not in any XML namespace.

<!-- http://http://www.w3.org/to/addresses is the default XML namespace. --><Address type="home">

To understand why this is true, remember that the purpose of XML namespaces is to uniquely identify elementand attribute names. Unprefixed attribute names can be uniquely identified based on the element type towhich they belong, so there is no need identify them further by including them in an XML namespace. In fact,the only reason for allowing attribute names to be prefixed is so that attributes defined in one XML languagecan be used in another XML language.

77. When should I use the default XML namespace instead of prefixes?

This is purely a matter of choice, although your choice may affect the readability of the document. Whenelements whose names all belong to a single XML namespace are grouped together, using a default XMLnamespace might make the document more readable. For example:

<!-- A, B, C, and G are in the http://www.google.org/ namespace. --><A xmlns="http://www.google.org/"><B>abcd</B><C>efgh</C><!-- D, E, and F are in the http://www.bar.org/ namespace. -->

<D xmlns="http://www.bar.org/"><E>1234</E><F>5678</F></D><!-- Remember! G is in the http://www.google.org/ namespace. --><G>ijkl</G></A>

When elements whose names are in multiple XML namespaces are interspersed, default XML namespacesdefinitely make a document more difficult to read and prefixes should be used instead. For example:

<A xmlns="http://www.google.org/"><B xmlns="http://www.bar.org/">abcd</B><C xmlns="http://www.google.org/">efgh</C><D xmlns="http://www.bar.org/">

<E xmlns="http://www.google.org/">1234</E><F xmlns="http://www.bar.org/">5678</F></D><G xmlns="http://www.google.org/">ijkl</G></A>

In some cases, default namespaces can be processed faster than namespace prefixes, but the difference iscertain to be negligible in comparison to total processing time.

78. What is the scope of an XML namespace declaration?

The scope of an XML namespace declaration is that part of an XML document to which the declaration applies.An XML namespace declaration remains in scope for the element on which it is declared and all of itsdescendants, unless it is overridden or undeclared on one of those descendants.For example, in the following, the scope of the declaration of the http://www.google.org/ namespace is the

element A and its descendants (B and C). The scope of the declaration of the http://www.bar.org/ namespaceis only the element C.<google:A xmlns:google="http://www.google.org/"><google:B><bar:C xmlns:bar="http://www.bar.org/" /></google:B></google:A>

79. Does the scope of an XML namespace declaration include the element it is declared on?

Yes.For example, in the following, the names B and C are in the http://www.bar.org/ namespace, not thehttp://www.google.org/ namespace. This is because the declaration that associates the google prefix with thehttp://www.bar.org/ namespace occurs on the B element, overriding the declaration on the A element thatassociates it with the http://www.google.org/ namespace.<google:A xmlns:google="http://www.google.org/"><google:B xmlns:google="http://www.bar.org/"><google:C>abcd</google:C></google:B></google:A>

Similarly, in the following, the names B and C are in the http://www.bar.org/ namespace, not the

208

Page 209: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 209/225

http://www.google.org/ namespace because the declaration declaring http://www.bar.org/ as the default XMLnamespace occurs on the B element, overriding the declaration on the A element.

<A xmlns="http://www.google.org/"><B xmlns="http://www.bar.org/"><C>abcd</C></B></A>

A final example is that, in the following, the attribute name D is in the http://www.bar.org/ namespace.<google:A xmlns:google="http://www.google.org/"><google:B google:D="In http://www.bar.org/ namespace"xmlns:google="http://www.bar.org/"><C>abcd</C></google:B></google:A>

One consequence of XML namespace declarations applying to the elements they occur on is that they actuallyapply before they appear. Because of this, software that processes qualified names should be particularlycareful to scan the attributes of an element for XML namespace declarations before deciding what XMLnamespace (if any) an element type or attribute name belongs to.

80. If an element or attribute is in the scope of an XML namespace declaration, is its name in that namespace?

Not necessarily.

When an element or attribute is in the scope of an XML namespace declaration, the element or attribute'sname is checked to see if it has a prefix that matches the prefix in the declaration. Whether the name isactually in the XML namespace depends on whether the prefix matches. For example, in the following, theelement type names A, B, and D and the attribute names C and E are in the scope of the declaration of thehttp://www.google.org/ namespace. While the names A, B, and C are in that namespace, the names D and Eare not.

<google:A xmlns:google="http://www.google.org/"><google:B google:C="google" /><bar:D bar:E="bar" /></google:A>

81. What happens when an XML namespace declaration goes out of scope?

When an XML namespace declaration goes out of scope, it simply no longer applies. For example, in the

following, the declaration of the http://www.google.org/ namespace does not apply to the C element becausethis is outside its scope. That is, it is past the end of the B element, on which the http://www.google.org/namespace was declared.<!-- B is in the http://www.google.org/ namespace;C is not in any XML namespace. --><A><B xmlns="http://www.google.org/">abcd</B><C>efgh</C></A>

In addition to the declaration no longer applying, any declarations that it overrode come back into scope. Forexample, in the following, the declaration of the http://www.google.org/ namespace is brought back into scopeafter the end of the B element. This is because it was overridden on the B element by the declaration of thehttp://www.bar.org/ namespace.<!-- A and C are in the http://www.google.org/ namespace.

B is in the http://www.bar.org/ namespace. --><A xmlns="http://www.google.org/"><B xmlns="http://www.bar.org/">abcd</B><C>efgh</C></A>

82. What happens if no XML namespace declaration is in scope?

If no XML namespace declaration is in scope, then any prefixed element type or attribute names result innamespace errors. For example, in the following, the names google:A and google:B result in namespaceerrors.<?xml version="1.0" ?><google:A google:B="error" />

In the absence of an XML namespace declaration, unprefixed element type and attribute names do not belongto any XML namespace. For example, in the following, the names A and B are not in any XML namespace.

83. Can multiple XML namespace declarations be in scope at the same time?

Yes, as long as they don't use the same prefixes and at most one of them is the default XML namespace. Forexample, in the following, the http://www.google.org/ and http://www.bar.org/ namespaces are both in scopefor all elements:<A xmlns:google="http://www.google.org/"

209

Page 210: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 210/225

xmlns:bar="http://www.bar.org/"><google:B>abcd</google:B><bar:C>efgh</bar:C></A>One consequence of this is that you can place all XML namespace declarations on the root element and theywill be in scope for all elements. This is the simplest way to use XML namespaces.

84. How can I declare XML namespaces so that all elements and attributes are in their scope?

XML namespace declarations that are made on the root element are in scope for all elements and attributes inthe document. This means that an easy way to declare XML namespaces is to declare them only on the rootelement.

85. Does the scope of an XML namespace declaration ever include the DTD?

No.XML namespaces can be declared only on elements and their scope consists only of those elements and theirdescendants. Thus, the scope can never include the DTD.

86. Can I use XML namespaces in DTDs?

Yes and no.In particular, DTDs can contain qualified names but XML namespace declarations do not apply to DTDs .This has a number of consequences. Because XML namespace declarations do not apply to DTDs:1. There is no way to determine what XML namespace a prefix in a DTD points to. Which means...2. Qualified names in a DTD cannot be mapped to universal names. Which means...3. Element type and attribute declarations in a DTD are expressed in terms of qualified names, not universalnames. Which means...4. Validation cannot be redefined in terms of universal names as might be expected.This situation has caused numerous complaints but, as XML namespaces are already a recommendation, isunlikely to change. The long term solution to this problem is an XML schema language: all of the proposed XMLschema languages provide a mechanism by which the local name in an element type or attribute declarationcan be associated with an XML namespace. This makes it possible to redefine validity in terms of universalnames.

87. Do XML namespace declarations apply to DTDs?

No.In particular, an xmlns attribute declared in the DTD with a default is not an XML namespace declaration forthe DTD.. (Note that an earlier version of MSXML (the parser used by Internet Explorer) did use such

declarations as XML namespace declarations, but that this was removed in MSXML 4.

88. Can I use qualified names in DTDs?

Yes.For example, the following is legal:

<!ELEMENT google:A (google:B)><!ATTLIST google:Agoogle:C CDATA #IMPLIED><!ELEMENT google:B (#PCDATA)>

However, because XML namespace declarations do not apply to DTDs , qualified names in the DTD cannot beconverted to universal names. As a result, qualified names in the DTD have no special meaning. For example,google:A is just google:A -- it is not A in the XML namespace to which the prefix google is mapped.

The reason qualified names are allowed in the DTD is so that validation will continue to work.

89. Can the content model in an element type declaration contain element types whose names come fromother XML namespaces?

Yes and no.The answer to this question is yes in the sense that a qualified name in a content model can have a differentprefix than the qualified name of the element type being declared. For example, the following is legal:<!ELEMENT google:A (bar:B, baz:C)>The answer to this question is no in the sense that XML namespace declarations do not apply to DTDs so theprefixes used in an element type declaration are technically meaningless. In particular, they do not specify thatthe name of a certain element type belongs to a certain namespace. Nevertheless, the ability to mix prefixes inthis manner is crucial when: a) you have a document whose names come from multiple XML namespaces , andb) you want to construct that document in a way that is both valid and conforms to the XML namespacesrecommendation .

90. Can the attribute list of an element type contain attributes whose names come from other XMLnamespaces?

Yes and no.For example, the following is legal:

210

Page 211: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 211/225

<!ATTLIST google:Abar:B CDATA #IMPLIED>

91. How can I construct an XML document that is valid and conforms to the XML namespacesrecommendation?

In answering this question, it is important to remember that:* Validity is a concept defined in XML 1.0,* XML namespaces are layered on top of XML 1.0 , and* The XML namespaces recommendation does not redefine validity, such as in terms of universal names .Thus, validity is the same for a document that uses XML namespaces and one that doesn't. In particular, withrespect to validity:* xmlns attributes are treated as attributes, not XML namespace declarations.* Qualified names are treated like other names. For example, in the name google:A, google is not treated as anamespace prefix, the colon is not treated as separating a prefix from a local name, and A is not treated as alocal name. The name google:A is treated simply as the name google:A.Because of this, XML documents that you might expect to be valid are not. For example, the followingdocument is not valid because the element type name A is not declared in the DTD, in spite of the fact bothgoogle:A and A share the universal name {http://www.google.org/}A:<?xml version="1.0" ?><!DOCTYPE google:A [<!ELEMENT google:A EMPTY><!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"xmlns CDATA #FIXED "http://www.google.org/">

]><A/>

Similarly, the following is not valid because the xmlns attribute is not declared in the DTD:

<?xml version="1.0" ?><!DOCTYPE A [<!ELEMENT A EMPTY>]><A xmlns="http://www.google.org/" />

Furthermore, documents that you might expect to be invalid are valid. For example, the following document isvalid but contains two definitions of the element type with the universal name {http://www.google.org/}A:

<?xml version="1.0" ?>

<!DOCTYPE google:A [<!ELEMENT google:A (bar:A)><!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"><!ELEMENT bar:A (#PCDATA)><!ATTLIST bar:Axmlns:bar CDATA #FIXED "http://www.google.org/">]><google:A><bar:A>abcd</bar:A></google:A>

Finally, validity has nothing to do with correct usage of XML namespaces. For example, the following documentis valid but does not conform to the XML namespaces recommendation because the google prefix is neverdeclared:

<?xml version="1.0" ?><!DOCTYPE google:A [<!ELEMENT google:A EMPTY>]><google:A />

Therefore, when constructing an XML document that uses XML namespaces, you need to do both of thefollowing if you want the document to be valid:* Declare xmlns attributes in the DTD.* Use the same qualified names in the DTD and the body of the document.For example:<?xml version="1.0" ?><!DOCTYPE google:A [<!ELEMENT google:A (google:B)<!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"><!ELEMENT google:B EMPTY>]><google:A><google:B /></google:A>

211

Page 212: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 212/225

There is no requirement that the same prefix always be used for the same XML namespace. For example, thefollowing is also valid:<?xml version="1.0" ?><!DOCTYPE google:A [<!ELEMENT google:A (bar:B)><!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"><!ELEMENT bar:B EMPTY><!ATTLIST bar:Bxmlns:bar CDATA #FIXED "http://www.google.org/">]><google:A><bar:B /></google:A>

However, documents that use multiple prefixes for the same XML namespace or the same prefix for multipleXML namespaces are confusing to read and thus prone to error. They also allow abuses such as defining anelement type or attribute with a given universal name more than once, as was seen earlier. Therefore, a betterset of guidelines for writing documents that are both valid and conform to the XML namespacesrecommendation is:* Declare all xmlns attributes in the DTD.* Use the same qualified names in the DTD and the body of the document.* Use one prefix per XML namespace.* Do not use the same prefix for more than one XML namespace.* Use at most one default XML namespace.

The latter three guidelines guarantee that prefixes are unique. This means that prefixes fulfill the role normallyplayed by namespace names (URIs) -- uniquely identifying an XML namespace -- and that qualified names areequivalent to universal names, so a given universal name is always represented by the same qualified name.Unfortunately, this is contrary to the spirit of prefixes, which were designed for their flexibility. For a slightlybetter solution.

92. How can I allow the prefixes in my document to be different from the prefixes in my DTD?

One of the problems with the solution proposed in question is that it requires the prefixes in the document tomatch those in the DTD. Fortunately, there is a workaround for this problem, although it does require that asingle prefix be used for a particular namespace URI throughout the document. (This is a good practiceanyway, so it's not too much of a restriction.) The solution assumes that you are using a DTD that is externalto the document, which is common practice.To use different prefixes in the external DTD and XML documents, you declare the prefix with a pair of 

parameter entities in the DTD. You can then override these entities with declarations in the internal DTD in agiven XML document. This works because the internal DTD is read before the external DTD and the firstdefinition of a particular entity is the one that is used. The following paragraphs describe how to use a singlenamespace in your DTD. You will need to modify them somewhat to use multiple namespaces.To start with, declare three parameter entities in your DTD:

<!ENTITY % p "" ><!ENTITY % s "" ><!ENTITY % nsdecl "xmlns%s;" >

The p entity ("p" is short for "prefix") is used in place of the actual prefix in element type and attribute names.The s entity ("s" is short for "suffix") is used in place of the actual prefix in namespace declarations. The nsdeclentity ("nsdecl" is short for "namespace declaration") is used in place of the name of the xmlns attribute indeclarations of that attribute.Now use the p entity to define parameter entities for each of the names in your namespace. For example,

suppose element type names A, B, and C and attribute name D are in your namespace.

<!ENTITY % A "%p;A"><!ENTITY % B "%p;B"><!ENTITY % C "%p;C"><!ENTITY % D "%p;D">

Next, declare your element types and attributes using the "name" entities, not the actual names. For example:

<!ELEMENT %A; ((%B;)*, %C;)><!ATTLIST %A;%nsdecl; CDATA "http://www.google.org/"><!ELEMENT %B; EMPTY><!ATTLIST %B;%D; NMTOKEN #REQUIRED

E CDATA #REQUIRED><!ELEMENT %C; (#PCDATA)>

There are several things to notice here.* Attribute D is in a namespace, so it is declared with a "name" entity. Attribute E is not in a namespace, so noentity is used.* The nsdecl entity is used to declare the xmlns attribute. (xmlns attributes must be declared on every element

212

Page 213: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 213/225

type on which they can occur.) Note that a default value is given for the xmlns attribute.* The reference to element type B in the content model of A is placed inside parentheses. The reason for this isthat a modifier -- * in this case -- is applied to it. Using parentheses is necessary because the replacementvalues of parameter entities are padded with spaces; directly applying the modifier to the parameter entityreference would result in illegal syntax in the content model.For example, suppose the value of the A entity is "google:A", the value of the B entity is "google:B", and thevalue of the C entity is "google:C". The declaration:<!ELEMENT %A; (%B;*, %C;)>would resolve to:<!ELEMENT google:A ( google:B *, google:C )>

This is illegal because the * modifier must directly follow the reference to the google:B element type. Byplacing the reference to the B entity in parentheses, the declaration resolves to:

<!ELEMENT google:A (( google:B )*, google:C )>

This is legal because the * modifier directly follows the closing parenthesis.

Now let's see how this all works. Suppose our XML document won't use prefixes, but instead wants the defaultnamespace to be the http://www.google.org/ namespace. In this case, no entity declarations are needed in thedocument. For example, our document might be:

<!DOCTYPE A SYSTEM "http://www.google.org/google.dtd"><A><B D="bar" E="baz buz" />

<B D="boo" E="biz bez" /><C>bizbuz</C></A>

This document is valid because the declarations for p, s, and nsdecl in the DTD set p and s to "" and nsdecl to"xmlns". That is, after replacing the p, s, and nsdecl parameter entities, the DTD is as follows. Notice that boththe DTD and document use the element type names A, B, and C and the attribute names D and E.<!ELEMENT A (( B )*, C )><!ATTLIST Axmlns CDATA "http://www.google.org/"><!ELEMENT B EMPTY><!ATTLIST BD NMTOKEN #REQUIREDE CDATA #REQUIRED><!ELEMENT C (#PCDATA)>

But what if the document wants to use a different prefix, such as google? In this case, the document mustoverride the declarations of the p and s entities in its internal DTD. That is, it must declare these entities sothat they use google as a prefix (followed by a colon) and a suffix (preceded by a colon). For example:

<!DOCTYPE google:A SYSTEM "http://www.google.org/google.dtd" [<!ENTITY % p "google:"><!ENTITY % s ":google">]><google:A><google:B google:D="bar" E="baz buz" /><google:B google:D="boo" E="biz bez" /><google:C>bizbuz</google:C></google:A>

In this case, the internal DTD is read before the external DTD, so the values of the p and s entities from thedocument are used. Thus, after replacing the p, s, and nsdecl parameter entities, the DTD is as follows. Noticethat both the DTD and document use the element type names google:A, google:B, and google:C and theattribute names google:D and E.

<!ELEMENT google:A (( google:B )*, google:C )><!ATTLIST google:Axmlns:google CDATA "http://www.google.org/"><!ELEMENT google:B EMPTY><!ATTLIST google:Bgoogle:D NMTOKEN #REQUIREDE CDATA #REQUIRED><!ELEMENT google:C (#PCDATA)>

93. How can I validate an XML document that uses XML namespaces?

When people ask this question, they usually assume that validity is different for documents that use XMLnamespaces and documents that don't. In fact, it isn't -- it's the same for both. Thus, there is no differencebetween validating a document that uses XML namespaces and validating one that doesn't. In either case, yousimply use a validating parser or other software that performs validation.

213

Page 214: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 214/225

94. If I start using XML namespaces, do I need to change my existing DTDs?

Probably. If you want your XML documents to be both valid and conform to the XML namespacesrecommendation, you need to declare any xmlns attributes and use the same qualified names in the DTD as inthe body of the document.If your DTD contains element type and attribute names from a single XML namespace, the easiest thing to dois to use your XML namespace as the default XML namespace. To do this, declare the attribute xmlns (noprefix) for each possible root element type. If you can guarantee that the DTD is always read , set the defaultvalue in each xmlns attribute declaration to the URI used as your namespace name. Otherwise, declare yourXML namespace as the default XML namespace on the root element of each instance document.

If your DTD contains element type and attribute names from multiple XML namespaces, you need to choose asingle prefix for each XML namespace and use these consistently in qualified names in both the DTD and thebody of each document. You also need to declare your xmlns attributes in the DTD and declare your XMLnamespaces. As in the single XML namespace case, the easiest way to do this is add xmlns attributes to eachpossible root element type and use default values if possible.

95. How do I create documents that use XML namespaces?

The same as you create documents that don't use XML namespaces. If you're currently using Notepad onWindows or emacs on Linux, you can continue using Notepad or emacs. If you're using an XML editor that isnot namespace-aware, you can also continue to use that, as qualified names are legal names in XMLdocuments and xmlns attributes are legal attributes. And if you're using an XML editor that is namespace-aware, it will probably provide features such as automatically declaring XML namespaces and keeping track of prefixes and the default XML namespace for you.

96. How can I check that a document conforms to the XML namespaces recommendation?

Unfortunately, I know of no software that only checks for conformance to the XML namespacesrecommendation. It is possible that some namespace-aware validating parsers (such as those fromDataChannel (Microsoft), IBM, Oracle, or Sun) check XML namespace conformance as part of parsing andvalidating. Thus, you might be able to run your document through such parsers as a way of testingconformance.Note that writing an application to check conformance to the XML namespaces recommendation is not as easyas it might seem. The problem is that most parsers do not make DTD information available to the application,so it might not be possible to check conformance in the DTD. Also note that writing a SAX 1.0 application thatchecks conformance in the body of the document (as opposed to the DTD) should be an easy thing to do.

97. Can I use the same document with both namespace-aware and namespace-unaware applications?

Yes.This situation is quite common, such as when a namespace-aware application is built on top of a namespace-unaware parser. Another common situation is when you create an XML document with a namespace-unaware

XML editor but process it with a namespace-aware application.Using the same document with both namespace-aware and namespace-unaware applications is possiblebecause XML namespaces use XML syntax. That is, an XML document that uses XML namespaces is still an XMLdocument and is recognized as such by namespace-unaware software.The only thing you need to be careful about when using the same document with both namespace-aware andnamespace-unaware applications is when the namespace-unaware application requires the document to bevalid. In this case, you must be careful to construct your document in a way that is both valid and conforms tothe XML namespaces recommendation. (It is possible to construct documents that conform to the XMLnamespaces recommendation but are not valid and vice versa.)

98. What software is needed to process XML namespaces?

From a document author's perspective, this is generally not a relevant question. Most XML documents arewritten in a specific XML language and processed by an application that understands that language. If thelanguage uses an XML namespace, then the application will already use that namespace -- there is no need forany special XML namespace software.

99. How do I use XML namespaces with Internet Explorer 5.0 and/or the MSXML parser?

WARNING! The following applies only to earlier versions of MSXML. It does not apply to MSXML 4, which is thecurrently shipping version [July, 2002].An early version of the MSXML parser, which was shipped as part of Internet Explorer 5.0, required that everyXML namespace prefix used in an element type or attribute declaration had to be "declared" in the attributedeclaration for that element type. This had to be done with a fixed xmlns attribute declaration. For example,the following was accepted by MSXML and both xmlns:google attributes were required:<!ELEMENT google:A (#PCDATA)><!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"><!ELEMENT google:B (#PCDATA)><!ATTLIST google:Bxmlns:google CDATA #FIXED "http://www.google.org/">

MSXML returned an error for the following because the second google prefix was not "declared":

<!ELEMENT google:A (#PCDATA)><!ATTLIST google:Axmlns:google CDATA #FIXED "http://www.google.org/"><!ELEMENT google:B (#PCDATA)>

214

Page 215: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 215/225

The reason for this restriction was so that MSXML could use universal names to match element type andattribute declarations to elements and attributes during validation. Although this would have simplified many of the problems of writing documents that are both valid and conform to the XML namespaces recommendationsome users complained about it because it was not part of the XML namespaces recommendation. In responseto these complaints, Microsoft removed this restriction in later versions, which are now shipping. Ironically, theidea was later independently derived as a way to resolve the problems of validity and namespaces. However, ithas not been implemented by anyone.

100. How do applications process documents that use XML namespaces?

Applications process documents that use XML namespaces in almost exactly the same way they processdocuments that don't use XML namespaces. For example, if a namespace-unaware application adds a newsales order to a database when it encounters a SalesOrder element, the equivalent namespace-awareapplication does the same. The only difference is that the namespace-aware application:* Might need to check for xmlns attributes and parse qualified names. Whether it does this depends onwhether such processing is already done by lower-level software, such as a namespace-aware DOMimplementation.* Uses universal (two-part) names instead of local (one-part) names. For example, the namespace-awareapplication might add a new sales order in response to an {http://www.google.com/ito/sales}SalesOrderelement instead of a SalesOrder element.

101. How do I use XML namespaces with SAX 1.0?

The easiest way to use XML namespaces with SAX 1.0 is to use John Cowan's Namespace SAX Filter (seehttp://www.ccil.org/~cowan/XML). This is a SAX filter that keeps track of XML namespace declarations, parses

qualified names, and returns element type and attribute names as universal names in the form:URI^local-nameFor example:http://www.google.com/ito/sales^SalesOrderYour application can then base its processing on these longer names. For example, the code:public void startElement(String elementName, AttributeList attrs)throws SAXException{...if (elementName.equals("SalesOrder")){

 // Add new database record.}...}

might become:public void startElement(String elementName, AttributeList attrs)throws SAXException{...if (elementName.equals("http://www.google.com/sales SalesOrder")){

 // Add new database record.}...}or:public void startElement(String elementName, AttributeList attrs)throws SAXException{

... // getURI() and getLocalName() are utility functions // to parse universal names.if (getURI(elementName).equals("http://www.foo.com/ito/sales")){if (getLocalName(elementName).equals("SalesOrder")){

 // Add new database record.}}...}If you do not want to use the Namespace SAX Filter, then you will need to do the following in addition toidentifying element types and attributes by their universal names:* In startElement, scan the attributes for XML namespace declarations before doing any other processing. Youwill need to maintain a table of current prefix-to-URI mappings (including a null prefix for the default XMLnamespace).* In startElement and endElement, check whether the element type name includes a prefix. If so, use yourmappings to map this prefix to a URI. Depending on how your software works, you might also check if the localpart of the qualified name includes any colons, which are illegal.* In startElement, check whether attribute names include a prefix. If so, process as in the previous point.

215

Page 216: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 216/225

102. How do I use XML namespaces with SAX 2.0?

SAX 2.0 primarily supports XML namespaces through the following methods: * startElement and endElement inthe ContentHandler interface return namespace names (URIs) and local names as well as qualified names. *getValue, getType, and getIndex in the Attributes interface can retrieve attribute information by namespacename (URI) and local name as well as by qualified name.

103. How do I use XML namespaces with DOM level 2?

 // Check the local name.

 // getNodeName() is a DOM level 1 method.if (elementNode.getNodeName().equals("SalesOrder")){

 // Add new database record.}

might become the following namespace-aware code:

 // Check the XML namespace name (URI). // getNamespaceURI() is a DOM level 2 method.

String SALES_NS = "http://www.foo.com/ito/sales";if (elementNode.getNamespaceURI().equals(SALES_NS)){

 // Check the local name. // getLocalName() is a DOM level 2 method.

if (elementNode.getLocalName().equals("SalesOrder")){

 // Add new database record.}}

Note that, unlike SAX 2.0, DOM level 2 treats xmlns attributes as normal attributes.

104. Can an application process documents that use XML namespaces and documents that don't use XMLnamespaces?

Yes.

This is a common situation for generic applications, such as editors, browsers, and parsers, that are not wiredto understand a particular XML language. Such applications simply treat all element type and attribute namesas qualified names. Those names that are not mapped to an XML namespace -- that is, unprefixed elementtype names in the absence of a default XML namespace and unprefixed attribute names -- are simplyprocessed as one-part names, such as by using a null XML namespace name (URI).Note that such applications must decide how to treat documents that do not conform to the XML namespacesrecommendation. For example, what should the application do if an element type name contains a colon (thusimplying the existence of a prefix), but there are no XML namespace declarations in the document? Theapplication can choose to treat this as an error, or it can treat the document as one that does not use XMLnamespaces, ignore the "error", and continue processing.

105. Can an application be both namespace-aware and namespace-unaware?

Yes.However, there is generally no reason to do this. The reason is that most applications understand a particularXML language, such as one used to transfer sales orders between companies. If the element type and attributenames in the language belong to an XML namespace, the application must be namespace-aware; if not, theapplication must be namespace-unaware.For a few applications, being both namespace-aware and namespace-unaware makes sense. For example, aparser might choose to redefine validity in terms of universal names and have both namespace-aware andnamespace-unaware validation modes. However, such applications are uncommon.

106. What does a namespace-aware application do when it encounters an error?

The XML namespaces recommendation does not specify what a namespace-aware application does when itencounters a document that does not conform to the recommendation. Therefore, the behavior is application-dependent. For example, the application could stop processing, post an error to a log and continue processing,or ignore the error.PART III: NAMES, PREFIXES, AND URIs

107. What is a qualified name?A qualified name is a name of the following form. It consists of an optional prefix and colon, followed by thelocal part, which is sometimes known as a local name.prefix:local-part--OR--local-part

216

Page 217: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 217/225

For example, both of the following are qualified names. The first name has a prefix of serv; the second namedoes not have a prefix. For both names, the local part (local name) is Address.serv:AddressAddress

In most circumstances, qualified names are mapped to universal names.

108. What characters are allowed in a qualified name?

The prefix can contain any character that is allowed in the Name [5] production in XML 1.0 except a colon. Thesame is true of the local name. Thus, there can be at most one colon in a qualified name -- the colon used toseparate the prefix from the local name.

109. Where can qualified names appear?

Qualified names can appear anywhere an element type or attribute name can appear: in start and end tags, asthe document element type, and in element type and attribute declarations in the DTD. For example:

<!DOCTYPE foo:A [<!ELEMENT foo:A (foo:B)><!ATTLIST foo:Afoo:C CDATA #IMPLIED><!ELEMENT foo:B (#PCDATA)>]>

<foo:A xmlns:foo="http://www.foo.org/" foo:C="bar"><foo:B>abcd<foo:A>

Qualified names cannot appear as entity names, notation names, or processing instruction targets.

110. Can qualified names be used in attribute values?

Yes, but they have no special significance. That is, they are not necessarily recognized as such and mapped touniversal names. For example, the value of the C attribute in the following is the string "foo:D", not theuniversal name {http://www.foo.org/}D.<foo:A xmlns:foo="http://www.foo.org/"><foo:B C="foo:D"/><foo:A>

In spite of this, there is nothing to stop an application from recognizing a qualified name in an attribute valueand processing it as such. This is being done in various technologies today. For example, in the following XMLSchemas definition, the attribute value xsd:string identifies the type of the foo attribute as the universal name{http://www.w3.org/1999/XMLSchema}string.

<xsd:attribute name="foo" type="xsd:string" />

There are two potential problems with this. First, the application must be able to retrieve the prefix mappingscurrently in effect. Fortunately, both SAX 2.0 and DOM level 2 support this capability. Second, any generalpurpose transformation tool, such as one that writes an XML document in canonical form and changesnamespace prefixes in the process, will not recognize qualified names in attribute values and therefore nottransform them correctly. Although this may be solved in the future by the introduction of the QName(qualified name) data type in XML Schemas, it is a problem today.

111. How are qualified names mapped to names in XML namespaces?

If a qualified name in the body of a document (as opposed to the DTD) includes a prefix, then that prefix isused to map the local part of the qualified name to a universal name -- that is, a name in an XML namespace.For example, in the following, the prefix foo is used to map the local names A, B, and C to names in thehttp://www.foo.org/ namespace:<?xml version="1.0" ?><foo:A xmlns:foo="http://www.foo.org/" foo:C="bar"><foo:B>abcd<foo:A>

If a qualified name in the body of a document does not include a prefix and a default XML namespace is inscope then one of two things happens. If the name is used as an element tag, it is mapped to a name in thedefault XML namespace. If it is used as an attribute name, it is not in any XML namespace. For example, in thefollowing, A and B are in the http://www.foo.org/ namespace and C is not in any XML namespace:

<?xml version="1.0" ?><A xmlns="http://www.foo.org/" C="bar"><B>abcd</B><A>

If a qualified name in the body of a document does not include a prefix and no default XML namespace is inscope, then that name is not in any XML namespace. For example, in the following, A, B, and C are not in any

217

Page 218: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 218/225

XML namespace:<?xml version="1.0" ?><A C="bar"><B>abcd</B><A>

Qualified names in the DTD are never mapped to names in an XML namespace because they are never in thescope of an XML namespace declaration.

112. How are universal names represented?There is no standard way to represent a universal name. However, three representations are common.The first representation keeps the XML namespace name (URI) and the local name separate. For example,many DOM level 1 implementations have different methods for returning the XML namespace name (URI) andthe local name of an element or attribute node.The second representation concatenates the namespace name (URI) and the local name with caret (^). Theresult is a universally unique name, since carets are not allowed in URIs or local names. This is the methodused by John Cowan's Namespace SAX Filter . For example, the universal name that has the URIhttp://www.google.org/to/servers and the local name Address would be represented as:http://www.foo.com/ito/servers^AddressThe third representation places the XML namespace name (URI) in braces and concatenates this with the localname. This notation is suggested only for documentation and I am aware of no code that uses it. For example,the above name would be represented as:{http://www.foo.com/ito/servers}Address

113. Are universal names universally unique?

No, but it is reasonable to assume they are.Universal element type and attribute names are not guaranteed to be universally unique -- that is, uniquewithin the space of all XML documents -- because it is possible for two different people, each defining their ownXML namespace, to use the same URI and the same element type or attribute name. However, this occurs onlyif:* One or both people use a URI that is not under their control, such as somebody outside Netscape using theURI http://www.netscape.com/, or* Both people have control over a URI and both use it.

The first case means somebody is cheating when assigning URIs (a process governed by trust) and the secondcase means that two people within an organization are not paying attention to each other's work. For widelypublished element type and attribute names, neither case is very likely. Thus, it is reasonable to assume thatuniversal names are universally unique. (Since both cases are possible, applications that present security risks

should be careful about assuming that universal names are universally unique.)For information about the ability of universal names to uniquely identify element types and attributes (asopposed to the names themselves being unique).

114. What is an XML namespace prefix?

An XML namespace prefix is a prefix used to specify that a local element type or attribute name is in aparticular XML namespace. For example, in the following, the serv prefix specifies that the Address elementtype name is in the http://www.foo.com/ito/addresses namespace:<serv:Addresses xmlns:serv="http://www.foo.com/ito/addresses">

115. What characters are allowed in an XML namespace prefix?

The prefix can contain any character that is allowed in the Name [5] production in XML 1.0 except a colon.

116. Can I use the same prefix for more than one XML namespace?Yes.

117. What happens if there is no prefix on an element type name?

If a default XML namespace declaration is in scope, then the element type name is in the default XMLnamespace. Otherwise, the element type name is not in any XML namespace.

118. What does the URI used as an XML namespace name point to?

The URI used as an XML namespace name is simply an identifier. It is not guaranteed to point to anything and,in general, it is a bad idea to assume that it does. This point causes a lot of confusion, so we'll repeat it here:URIs USED AS XML NAMESPACE NAMES ARE JUST IDENTIFIERS. THEY ARE NOT GUARANTEED TO POINT TOANYTHING.While this might be confusing when URLs are used as namespace names, it is obvious when other types of 

URIs are used as namespace names. For example, the following namespace declaration uses an ISBN URN:xmlns:xbe="urn:ISBN:0-7897-2504-5"and the following namespace declaration uses a UUID URN:xmlns:foo="urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"Clearly, neither namespace name points to anything on the Web.NOTE: Namespace URIs that are URLs may point to RDDL documents, although this does not appear to be

218

Page 219: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 219/225

widely implemented. For details, see the next question.NOTE: An early version of the W3C's XML Schemas used namespace URIs to point to an XML Schemadocument containing the definitions of the element types and attributes named in the namespace. However,this proved very controversial and the idea has been withdrawn.

119. What is an XML namespace name?

An XML namespace name is a URI that uniquely identifies the namespace. URIs are used because they arewidely understood and well documented. Because people may only allocate URIs under their control, it is easy

to ensure that no two XML namespaces are identified by the same URI.

120. Can I resolve the URI used as an XML namespace name?

Yes.

121. Can I use a relative URI as a namespace name?

Yes. However, such usage is deprecated, so you should never do it.

122. What is XPointer?

XPointer is set of recommendations developed by the W3C. The core recommendations are the XPointerFramework which provides an extensible addressing behavior for fragment identifiers in XML media types.XPointer gains its extensibility through the XPointer Framework, which identifies the syntax and processingarchitecture for XPointer expressions and through an extensible set of XPointer addressing schemes. Theseschemes, e.g., element() or xpointer(), are actually QNames. The xmlns() scheme makes it possible for an

XPointer to declare namespace bindings and thereby use third-party schemes as readily as W3C definedXPointer schemes.

123. How do I install the XPointer processor?

Download the latest "cweb-xpointer" release from SourceForge. This project uses Apache Maven and Java1.4+, so you will need to install those as well. Normally you will also want to download one of the XPointerFramework integrations, such as the xpointer+dom4j or the xpointer+jdom package. These "integrationpackages" provide support for a specific XML Document model.The project dependencies are explicitly declared in the Maven POM. This means that Maven can automagicallydownload the required releases of dependent JARs.There are several release artifacts. The "uberjar" release provides an executable command line utility (seebelow) and bundles all dependancies (except for Java itself). If you want to integrate into an existingapplication, then you should use the cweb-xpointer JAR and also download copies of its dependencies. If youare using a Maven project, then this is all very, very easy.

124. What is server-side XPointer?

The XPointer Framework provides an authoritative and extensible interpretation of the semantics of fragmentidentifiers for XML media types. However, HTTP does NOT transmit the fragment identifier as part of the HTTPrequest. Therefore XPointer is generally applied by the client, not by the server.For example, assuming that http://www.myorg.org/myTripleStore identifies a resource that is willing tonegotiate for RDF/XML, then the following is typical of an HTTP request for an RDF/XML representation of thatresource and the server's response.Request:

GET /myTripleStore HTTP/1.1Host: www.myorg.orgAccept: application/rdf+xml

Response:HTTP/1.1 200 OkContent-Type: application/rdf+xml

<rdf:RDF />This request asks for the entire triple store, serialized as RDF/XML.Server-side XPointer uses the HTTP "Range" header to transmit the XPointer expression to the server. Forexample, let's assume that the URI of the triple store is the same, but we want to select the subresourcesidentified by the following RDQL query:SELECT (?x foaf:mbox ?mbox)WHERE (?x foaf:name "John Smith") (?x foaf:mbox ?mbox)USING foaf FOR<http://xmlns.com/foaf/0.1/>)

In that case the HTTP request, including a copy of the RDQL query wrapped up as an XPointer expression,looks as follows. Note that we have added a range-unit whose value is xpointer to indicate that the value of the

Range header should be interpreted by an XPointer processor. Also note the use of the XPointer xmlns()scheme to set bind the namespace URI for the rdql() XPointer scheme. This is necessary since this scheme hasnot been standardized by the W3C.GET /myTripleStore HTTP/1.1Host: www.myorg.orgAccept: application/rdf+xml

219

Page 220: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 220/225

Range: xpointer = xmlns(x:http://www.mindswap.org)x:rdql(SELECT (?x foaf:mbox ?mbox)WHERE (?x foaf:name "John Smith") (?x foaf:mbox ?mbox)USING foaf FOR <http://xmlns.com/foaf/0.1/>)

The response looks as follows. The HTTP 206 (Partial Content) status code is used to indicate that the serverrecognized and processed the Range header and that the response entity includes only the identified logicalrange of the addressed resource.HTTP/1.1 206 Partial ContentContent-Type: application/rdf+xml

<!-- Only the selected sub-graph is transmitted to the client. --> <rdf:RDF />

125. What about non-XML resources?

You can use the XPointer Framework with non-XML resources. This is especially effective when your resource isbacked by some kind of a DBMS, or when you want to query a data model, such as RDF, and not the XMLsyntax of a representation of that data model.However, please note that the authoratitive interpretation of the fragment identifier is determined by theInternet Media Type. If you want to opt-in for XPointer, then you can always create publish your own InternetMedia Type with IANA and specify that it supports the XPointer Framework for some kind of non-XML resource.In this case, you are going to need to declare your own XPointer schemes as well.

126. What XPointer schemes are supported in this release?

The XPointer integration distributions support shorthand pointers. In addition, they bundle support for at lastthe following XPointer schemes:* xmlns()* element()* xpath() - This is not a W3C defined XPointer scheme since W3C has not published an XPointer sheme forXPath. The namespace URI for this scheme is http://www.cogweb.org/xml/namespace/xpointer . It providesfor addressing XML subresources using a XPath 1.0 expressions.

127. How do I configure an XPointer processor?

There is no required configuration for the XPointer Framework. The uberjar command line utility provides someconfiguration options. Applications configure individual XPointer processors when they obtain an instance froman appropriate XPointerProcessor factory method.

128.How do integrate XPointer into my application?

There are several ways to do this. The easiest is to use the uberjar release, which can be directly executed onany Java enabled platform. This makes it trivial to test and develop XPointer support in your applications,including server-side XPointer. The uberjar release contains a Java classorg.CognitiveWeb.xpointer.XPointerDriver that provides a simple but flexible command line utility that exposesan XPointer processor. The XPointer is provided as a command line argument and the XML resource is readfrom stdin. The results are written on stdout by default as a set of null-terminated XML fragments. SeeXPointerDriver in the XPointer JavaDoc for more information.If you already have a Java application, then it is straight-forward to integrate XPointer support using:org.CognitiveWeb.xpointer.XPointerProcessor You can see an example integration by looking at theXPointerDriver in the source code release.

129. How do I implement an application-specific XPointer scheme?

Short answer: Implement org.CognitiveWeb.xpointer.ISchemeProcessorThe XPointer Framework is extensible. One of the very coolest things about this is that you can develop yourown XPointer schemes that expose your application using the data model that makes the most sense for yourapplication clients.

For example, let's say that you have a CRM application. The important logical addressing units probably dealwith concepts such as customers, channels, and products. You can directly expose these data using a logicaladdressing scheme independent of the actual XML data model. Not only does this let people directly addressthe relevant concepts using a purpose-built addressing vocabulary, but this means that your addressingscheme can remain valid even if you change or version your XML data model. What a bonus!The same approach is being used by the MindSwap laboratory at the University of Maryland to prototype avariety of XPointer schemes for addressing semantic web data.

130. How do I support very large resources?

You can only do this with server-side XPointer. Further, you need to use (or implement) XPointer schemes thatdo not depend on a parsed XML document model. Basically, you need to use an XPointer scheme thatinterfaces with an indexed persistence store (RDBMS, ODBMS, or XML DBMS) which exposes to yourISchemeProcessor the information that it needs to answer subresource addressing requests.You will also have to provide shorthand pointer support for your DBMS-based resource. The default shorthand

pointer processor assumes that it has access to a parsed XML document, so it can't be used when you have avery large XML resource.

131. How do I contribute?

The XPointer implementation is hosted as a SourceForge project. If you want to contribute send an email toone of the project administrators from the project home page.

220

Page 221: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 221/225

The XPointer module uses numerous tests to validate correct behavior of the XPointer processor. One valuableway to contribute is by developing new tests that demonstrate broken behavior. Patches that fix the problemsidentified by those tests are also valuable, but it is by the tests themselves that we can insure that eachrelease of the XPointer processor will continue to meet the requirements of the various XPointer specifications.

132. What's XLink?

This specification defines the XML Linking Language (XLink), which allows elements to be inserted into XMLdocuments in order to create and describe links between resources. It uses XML syntax to create structuresthat can describe links similar to the simple unidirectional hyperlinks of today's HTML, as well as moresophisticated links.Definition: An XLink link is an explicit relationship between resources or portions of resources.] [Definition: It ismade explicit by an XLink linking element, which is an XLink-conforming XML element that asserts theexistence of a link.] There are six XLink elements; only two of them are considered linking elements. Theothers provide various pieces of information that describe the characteristics of a link. (The term "link" as usedin this specification refers only to an XLink link, though nothing prevents non-XLink constructs from serving aslinks.)

133. What are the valid values for xlink:actuate and xlink:show?

Don't blame me to put such a simple question here. I saw a famous exam simulator gave wrong answer on thisone. Typing them out also help me to remember them. xlink:actuate onRequest, onLoad, other, nonexlink:show replace new embed other none

134. Mock question: What is the correct answer of the following question?Which of the following is true about XLink and HTML hyperlinks?

1. XLink can be attached with any element. Hyperlinks in HTML can be attached to only an ANCHOR <A>element.2. XLink can refer to a specific location in XML document by name or context with the help of XPointer. HTMLANCHOR<A> does not have capability to point to specific location within an html document.3. XLink / XML links can be multidirectional. HTML links are unidirectional.4. HTML links are activated when user clicks on them. XLink has option of activating automatically when XMLdocument is processed.

Only 2 is incorrect, since HTML ANCHOR does have capability to point to specific location within an htmldocument.

135. What three essential components of security does the XML Signatures provide?

authentication, message integrity, and non-repudiation. In addition to signature information, an XML Signaturecan also contain information describing the key used to sign the content.

136. XLink Processing and Conformance

Processing Dependencies: XLink processing depends on [XML], [XML Names], [XML Base], and [IETF RFC2396]Markup Conformance:An XML element conforms to XLink if:it has a type attribute from the XLink namespace whose value is one of "simple", "extended", "locator", "arc","resource", "title", or "none", andit adheres to the conformance constraints imposed by the chosen XLink element type, as prescribed in thisspecification.This specification imposes no particular constraints on DTDs; conformance applies only to elements andattributes.Application Conformance:An XLink application is any software module that interprets well-formed XML documents containing XLinkelements and attributes, or XML information sets [XIS] containing information items and propertiescorresponding to XLink elements and attributes. (This document refers to elements and attributes, but allspecifications herein apply to their information set equivalents as well.) Such an application is conforming if:

it observes the mandatory conditions for applications ("must") set forth in this specification, andfor any optional conditions ("should" and "may") it chooses to observe, it observes them in the way prescribed,andit performs markup conformance testing according to all the conformance constraints appearing in thisspecification.

137. XLink Markup Design

Link markup needs to be recognized reliably by XLink applications in order to be traversed and handledproperly. XLink uses the mechanism described in the Namespaces in XML Recommendation [XML Names] to

accomplish recognition of the constructs in the XLink vocabulary.

TCS Client Interview

1. How do you handle exception handling?

221

Page 222: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 222/225

Exception handling is done in Java using try catch block. The exception is traced using printStackTrace().

2. When do you go for Hash map & Hash Table?Hash map allows one null Key and multiple null values. But in case of the hash table it is not permitted to havenull values as well as the keys. Hash table is synchronized whereas a hash map is not synchronized.

3. What is the difference between abstract class and interface?A class can implement any no. of interfaces but a class can't extend more than one abstract classes. No

method can be implemented in an interface, they are only defined while in an abstract class methods may be

implemented.

An interface doesn’t have instance variables while an abstract class may have. Variables declared inside an

interface declaration are implicitly final and static while nothing such in abstract class. All methods of an

interface are by default abstract while in an abstract class methods are not abstract by default moreover

concrete methods may also be present.

Since by default the variables of an interface are final they must be initialized with a constant value while this

is not mandatory in case of abstract class.

4. What is Multiple Inheritances?

Some object oriented languages, notably C++, allow a class to inherit from more than one unrelated class.

This is called multiple inheritance and is different from the multi-level inheritance. Most of the things that canbe accomplished via multiple inheritances in C++ can be handled by interfaces in Java.

5. What is Joins -- inner join and outer joins?

Inner Join: An inner join lists the common rows between two tables.

Table A Table B

Outer Join: Left Outer Join: A Left Outer Join lists all the common rows plus the rows from the Table A.

Table A Table B

Outer Join: Right Outer Join: A Right Outer Join lists all the common rows plus the rows from the Table B.

Table A Table B

6. What do you mean by CSS?

Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, and spacing) to Webdocuments. Tutorials, books, mailing lists for users, etc. Change the appearance of hundreds of Web pages bychanging just one file.

7. How do you create a thread?There are two methods

• By extending the Thread class.• By implementing the Runnable interface.

8. How will you declare constant in Java?

Using public static final.

9. what is the Difference between Overloading and Overriding?An overrided method redefines an existing method in a super class to specify a new behavior. Overloadingmeans that you have multiple methods with the same name but with a different parameter list.

10. How will you transfer a request from one servlet to another?

222

Page 223: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 223/225

Transferring a request is done through forward() and sendRedirect() methods of RequestDispatcher class.

11. What is the difference between forward and sendRedirect?When a request is forwarded to a JSP the same request is sent to the JSP, i.e. the values contained in therequest will not be lost.When a request is redirected to a JSP the existing request is lost and a new request is generated and sent tothe JSP. The new request is generated by the Web Browser.

12. How do you validate in Struts?Validation in struts is achieved using the validator framework which provides two xml files namely validator-rules.xml and validations.xml

13. How do you configure a validation in struts?The validator plug-in is configured in struts-config.xml.

14. What is the difference between servletContext and servletConfig?servletContext defines a set of methods that a servlet uses to communicate with its Servlet Container, e.g. toget the MIME (Multipurpose Internet Mail Extension) type of a file, dispatch requests or write to a log file. It iscontained within the servletConfig.

servletConfig is the one which the web server provides the servlet when the servlet is initialized.

15. what is the difference between SAX and DOM Parser?SAX DOM

It presents the document as a serialized “eventstream”.

It presents the document as a tree structure.

Does not support random access manipulation. It supports random access manipulation.Less Memory and high performance. More Memory and low performance.Used when data is stored directly to the DB or a file. Used when some utilities has to modify the XML

itself.

16. How will you call stored procedure from Java?Using CallableStatement.

17. How did you connect to your oracle database?Using JDBC Drivers. There are four types of JDBC Drivers namely,

Type 1 : JDBC-ODBC Bridge DriverType 2 : Native API partly Java DriverType 3 : Network Protocol DriverType 4 : JDBC Net Pure Java Driver

Syntax for getting a connection using Type 4 Driver:

Class.forName(“oracle.jdbc.driver.OracleDriver”);Connection con =DriverManager.getConnection(“jdbc:oracle:thin:@ip:port:db_name”,”username”,”password”);

18. What design tool did you use?Rational Rose.

19. what source control tools did you use?Any one of the following,

• Rational Clear Case• Merant’s PVCS (Product Version Control System)• Microsoft VSS (Visual Source Safe)

20. Explain life cycle of Servlet?init(),service() and destroy() methods.

21. what is the difference between prepared statement and regular sql statement?Prepared Statements are precompiled whereas normal statements are compiled at run time.

22. Where will you use synchronized methods?When ever a method is liable to be accessed by more than one Thread then that method is made synchronized.

23. What is the difference between stateful and stateless session beans?

Stateful Session Bean Stateless Session BeanThis bean maintains the conversation state betweenmethod calls or remembers the actions done by aparticular user.

This Bean does not maintain theconversation state between method calls.

Stateful session beans are specific to a particularclient.

Stateless Session Beans are not specific to aparticular client.

There is no pooling concept in Stateful session Here the beans are kept in a pool and

223

Page 224: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 224/225

bean. activated when ever a client requests.

EJB Activation and Passivation takes place There is no EJB Activation and Passivation.

24. what is jsp include directive? How does it differ from regular include?<%jsp:include page=”test.jsp”> - Used to include dynamic or static resources during translationtime.

<%@include file=”test.jsp”> - Used to include static content at runtime.

25. what are the different types of jsp bean scope?The different type of bean scopes is,Page, request, session and application.

26. what are the different types of EJB?The different types EJB are,

• Session Beans (Stateful and Stateless)• Entity Beans (BMP - Bean Managed Persistent and CMP – Container Managed Persistent)• Message Driven Beans

27. How to prevent JSP Cache?JSP Cache can be prevented by including one of the following,

<%response.setHeader(“Cache-Control”,”no-store”);%> //Http 1.1

<%response.setHeader(“Pragma”,”no-cache”);%> //Http 1.0<%response.setDataHeader(“Expires”,0);%> //Prevents caching at the proxy server.

28. Explain Self Join?A join made using a single table is called a self join.

29. What is shallow copy and Deep Copy?A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it tothe objects found in the original. deep copy constructs a new compound object and then, recursively, insertscopies into it of the objects found in the original.

30. What are the different session Tracking mechanisms?The different Session tracking Mechanisms are,

• URL rewriting.• Hidden Form fields.• Cookies.

31. What are the largest Object type in ORACLE?blob and clob objects are the largest objects in Oracle.

32. What is static and its scope? When does it get initialized?A static is a Keyword to make variable and methods as static and local to the block where it is declared. Copyof the initialized value same to all the objects, if any changes made will effect to all the objects.

33. How will you invalidate the session?session.invalidate();

34. Can you implement interface in JSP?No. can’t implement interface in JSP.

35. How do you view a large file in UNIX?Either by using less filename or tail –f filename.

36. How do you kill a process in UNIX?A kill pid or kill -9 pid

• pid is the process id to kill the process• -9 is for forcible killing

37. What is difference between Marshalling & unmarshalling?The process of transforming an Object into a stream of bytes, so that it can be transmitted through thenetwork is called Marshalling.

The process of transforming a stream of bytes back into Objects is called Unmarshalling.

-------------------1. what is the Session object attributes?2. What is the design pattern of Action class?3. How do you store values (servlet) for the lifetime of the application? How do you handle user data?4. hat is the diff between doGet & doPost?5. what is dynaform? How is it differ from normal action class?

224

Page 225: JAVA_FULL-Technical Questions and Answers

7/18/2019 JAVA_FULL-Technical Questions and Answers

http://slidepdf.com/reader/full/javafull-technical-questions-and-answers 225/225

6. what is database Trigger?7. How will you make a cookie secured?

225