You are on page 1of 18

Table of Contents












Object Oriented Programming (OOP)
General Questions about Java
Java Threads
Java Collections
Garbage Collectors
Exception Handling
Java Applets
Swing
JDBC
Remote Method Invocation (RMI)
Servlets
JSP

Object Oriented Programming (OOP)
Java is a computer programming language that is concurrent, class-based and object-oriented.
The advantages of object oriented software development are shown below:

Modular development of code, which leads to easy maintenance and modification.

Reusability of code.

Improved reliability and flexibility of code.

Increased understanding of code.
Object-oriented programming contains many significant features, such
as encapsulation, inheritance, polymorphismand abstraction. We analyze each feature
separately in the following sections.
Encapsulation

Encapsulation provides objects with the ability to hide their internal characteristics and behavior.
Each object provides a number of methods, which can be accessed by other objects and change
its internal data. In Java, there are three access modifiers: public, private and protected. Each
modifier imposes different access rights to other classes, either in the same or in external
packages. Some of the advantages of using encapsulation are listed below:

The internal state of every objected is protected by hiding its attributes.

It increases usability and maintenance of code, because the behavior of an object can be
independently changed or extended.

It improves modularity by preventing objects to interact with each other, in an undesired
way.
You can refer to our tutorial here for more details and examples on encapsulation.
Polymorphism

wheel.. gearbox and engine” through composition. A polymorphic type is a type whose operations can also be applied to values of some other type. called base class. Java supports the creation and existence of abstract classes that expose interfaces. instead of their implementation details. Dynamic Binding is the process of linking a function call to code associated with it at runtime. develop classes in terms of their own functionality. Inheritance Inheritance provides an object with the ability to acquire the fields and methods of another class. Abstraction Abstraction is the process of separating ideas from specific instances and thus. it is important to note that both of these have the common advantage: reusability. However. Composition supports the has-a relationship among objects. The relation among the classes automobile. without including the actual implementation of all methods. What is the difference between object-based and object-oriented programming languages?  Object-based programming languages support encapsulation and object identity. seat. Differences between Abstraction and Encapsulation Abstraction and encapsulation are complementary concepts. without modifying it. Message communication is the process in which an object calls its function by sending arguments optionally to it. Inheritance provides re-usability of code and can be used to add additional features to an existing class.Polymorphism is the ability of programming languages to present the same interface for differing underlying data types. gearbox and engine is formed as “automobile is composed of (or has) wheel. can be seen as a strategy used in order to provide abstraction. Encapsulation is usually achieved by hiding information about the internal state of an object and thus. the relation between two classes vehicle and car is given as “car is a vehicle” through inheritance. abstraction focuses on the behavior of an object. Object-based language=Encapsulation+ Object Identity . steering wheel. On the other hand. steering wheel. seat. E. encapsulation focuses on the implementation of an object’s behavior. Difference between inheritance and composition: Inheritance supports the is-a relationship between two objects.g. The abstraction technique aims to separate the implementation details of a class from its behavior. On the one hand.

Java was designed to allow application programs to be built that could be run on any platform. the compiler will complain. Object-Oriented language=Object-based features+Inheritance+polymorphism Ex: C++. It also includes browser plugins for applet execution. A static variable is initialized when the class is loaded by the JVM. the compilers and tools (like JavaDoc. What are the Data Types supported by Java ? What is Autoboxing and Unboxing ? The eight primitive data types supported by the Java programming language are:  byte  short  int . including the JRE. 3. because those variables are not created yet and they are not associated with any instance. in order for a user to develop. without requiring an instantiation of the class to which it belongs. A static method is not associated with any instance of a class so the concept is not applicable. without having to be rewritten or recompiled by the programmer for each separate platform. because it is aware of the specific instruction lengths and other particularities of the underlying hardware platform. A Java virtual machine makes this possible. What is JVM ? Why is Java called the “Platform Independent Programming Language” ? A Java virtual machine (JVM) is a process virtual machine that can execute Java bytecode. which is executed by the JVM. Each Java source file is compiled into a bytecode file. Can you access non static variable in static context ? A static variable in Java belongs to its class and its value remains the same for all its instances. If your code tries to access a non-static variable. Java General Questions about Java 1. What is the Difference between JDK and JRE ? The Java Runtime Environment (JRE) is basically the Java Virtual Machine (JVM) where your Java programs are being executed. because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. 2. without any instance.Ex: Ada and Visual Basic  Object-oriented languages incorporate all the features of object-based programming languages along with inheritance and polymorphism. 4. 5. A user cannot override static methods in Java. and Java Debugger). compile and execute Java applications. The Java Development Kit (JDK) is the full featured Software Development Kit for Java. What does the “static” keyword mean ? Can you override private or static method in Java ? The static keyword denotes that a member variable or method can be accessed.

On the other hand. 9. even if changes are made to that object. a class may not implement all declared methods of an abstract class.  Variables declared in a Java interface is by default final. An abstract class also cannot be instantiated. On the other hand. Java does not support multiple inheritance. Different constructors can be created for a single class. What is a Constructor. Constructor Overloading in Java and Copy-Constructor ? A constructor gets invoked when a new object is created. However. Finally. it  .  In order for a class to implement an interface. An abstract class may contain non-final variables. this means that a copy of the object is passed. Also check out the Abstract class and Interface differences for JDK 8.  A class may implement a number of Interfaces.  Members of a Java interface are public by default. Overridden methods must have the same name. Each constructor must have its own unique parameter list. Every class has a constructor. the compiler converts an int to an Integer. and return type. Both implementations share some common characteristics. Each class is able to extend only on one class. 10. but can extend only one abstract class. Java does support copy constructors like C++.long  float  double  boolean  char Autoboxing is the automatic conversion made by the Java compiler between the primitive types and their corresponding object wrapper classes.  Abstract classes can implement interfaces without even providing the implementation of interface methods. What is the difference between an Interface and an Abstract class ? Java provides and supports the creation both of abstract classes and interfaces. a double to a Double. method overriding is defined as the case when a child class redefines the same method as a parent class. but the difference lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own. and so on. but can be invoked if it contains a main method. What are pass by reference and pass by value ? When an object is passed by value. 8. 6. but is able to implement more than one interfaces. Does Java support multiple inheritance ? No. Though. the sub-class must also be declared as abstract. Thus. it must implement all its declared methods. If the conversion goes the other way. in this case. the Java compiler (Javac) creates a default constructor for that class. A member of an abstract class can either be private. but different parameters.  An interface is absolutely abstract and cannot be instantiated. In case the programmer does not provide a constructor for a class. What is Function Overriding and Overloading in Java ? Method overloading in Java occurs when two or more methods in the same class have the exact same name. 7. but they differ in the following features:  All methods in an interface are implicitly abstract. this operation is called unboxing. The constructor overloading is similar to method overloading in Java. protected or public. argument list. For example. an abstract class may contain both abstract and non-abstract methods. The overriding method may not limit the access of the method it overrides.

 A class may implement the Runnable interface. When an object is passed by reference. Java Threads 11. How do you ensure that N threads can access N resources without deadlock ? A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering.  BLOCKED : The thread is in a blocked state while waiting for a monitor lock. The result is that both processes wait endlessly. Each monitor is associated with an object reference. Java Collections . this means that the actual object is not passed. Thus. rather a reference of the object is passed. Also. while aThread is a single execution sequence within a process. a thread can reside in one of the following states:  NEW: The thread becomes ready to run. but does not necessarily start running immediately.  TIMED_WAITING: The thread waits for another thread to perform a particular action up to a specified waiting time. the thread pool is very efficient and can be implemented and used very easily. any changes made by the external method. Which one would you prefer and why ? There are three ways that can be used in order for a Thread to be created:  A class may extend the Thread class. 16. as it does not require an object to inherit the Thread class. 12.  An application can use the Executor framework. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code.  RUNNABLE: The Java Virtual Machine (JVM) is actively executing the thread’s code. What’s a deadlock ? A condition that occurs when two processes are waiting for each other to complete. no deadlocks can arise. 15. only interfaces can help you.doesn’t affect the original value. Explain different ways of creating a thread. The Runnable interface is preferred. are also reflected in all places. in order to create a thread pool. each object has a lock. before proceeding. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock). How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply ? The JVM uses locks in conjunction with monitors. 17. A Thread is sometimes called a lightweight process. In case your application design requires multiple inheritance. What is the difference between a synchronized method and a synchronized block ? In Java programming. 13. if all threads lock and unlock the mutexes in the same order. A thread can acquire the lock for an object by using the synchronized keyword.  WAITING: The thread waits for another thread to perform a particular action. A process can contain multiple threads. During its execution. What is the difference between processes and threads ? A process is an execution of a program. Explain the available thread states in a high-level. 14. Thus.  TERMINATED: The thread has finished its execution. The thread is not allowed to execute the code until it obtains the lock.

the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection.  Map.concurrent are fail-safe. Each Java Collection contains the iterator method that returns an Iterator instance. Therefore.  List. 24. What are the basic interfaces of Java Collections Framework ? Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. Each concrete implementation of a Collection can choose its own way of how to maintain and order its elements. a HashMap uses the hashCode andequals methods to determine the index of the key-value pair and to detect duplicates. its value is updated with the new value. 20. If the key exists. while some other collections don’t. while the ListIterator can traverse a List in both directions. More specifically.  The Iterator can traverse a collection only in forward direction. Fail-fast iterators throw aConcurrentModificationException.  Set. replacing an element. What is the importance of hashCode() and equals() methods ? In Java. The semantics and the implications of either cloning or serialization come into play when dealing with actual implementations. its load factor and the threshold resizing. the hashCodemethod is used in order to determine where the specified key will be stored. 21. Some important characteristics of aHashMap are its capacity. Iterators arecapable of removing elements from the underlying collection during the iteration. which is an ordered collection and can contain duplicate elements. What is an Iterator ? The Iterator interface provides a number of methods that are able to iterate over anyCollection. . 19. the concrete implementations of collections should decide how they can be cloned or serialized. Some collections allow duplicate keys. What differences exist between Iterator and ListIterator ? The differences of these elements are listed below:  An Iterator can be used to traverse the Set and List collections. which is an object that maps keys to values and cannot contain duplicate keys. What is difference between fail-fast and fail-safe ? The Iterator's fail-safe property works with the clone of the underlying collection and thus. etc.18. Since different keys may produce the same hash value. while failsafe iterator never throws such an exception. Why Collection doesn’t extend Cloneable and Serializable interfaces ? The Collection interface specifies groups of objects known as elements. while the ListIterator can be used to iterate only over Lists.  The ListIterator implements the Iterator interface and contains extra functionality. The most basic interfaces that reside in the Java Collections Framework are:  Collection.util package are fail-fast. the equals method is used. When the put method is invoked. which is a collection that cannot contain duplicate elements. 23. in order to determine whether the specified key actually exists in the collection or not. 22. getting the index position for previous and next elements. while the collection classes in java. the implementation of both methods is crucial to the accuracy and efficiency of the HashMap. Thus. it is not affected by any modification in the collection. such as adding an element.util. The HashMap requires a hash function and uses hashCode and equals methods. How HashMap works in Java ? A HashMap in Java stores key-value pairs. All the collection classes in java. in order to put and retrieve elements to and from the collection respectively. which represents a group of objects known as its elements.

Check also our article ArrayList vs. in order to impose an order between them. 29.  A HashMap provides its set of keys and a Java application can iterate over them. based on a priority heap and its elements are ordered in their natural order. iterator. a Hashtable provides an Enumeration of its keys. What is difference between ArrayList and LinkedList ? Both the ArrayList and LinkedList classes implement the List interface. 26. addition and removal operations of an element are faster in a LinkedList compared to an ArrayList. The first method compares its two input arguments and imposes an order between them. or greater than the second. while a HashMap is not. only if the specified object is also a comparator and it imposes the same ordering as the comparator. Java provides the Comparator interface. However. the search operation for an element has execution time equal to O(n). or a positive integer to indicate that the first argument is less than.  An ArrayListprovides more methods and features. this approach makes them slower when working on fixed size primitive data types. while a Hashtable is suitable for multi-threaded environments. LinkedList.  For a list of primitive data types. called compareTo. while an ArrayList is dynamic. one for its previous element and one for its next element. nor null values. Java provides the Comparableinterface. because there is no need of resizing an array or updating the index when an element is added in some arbitrary position inside the collection.25. called compare and equals.  Arrays have fixed size. What differences exist between HashMap and Hashtable ? Both the HashMap and Hashtable classes implement the Map interface and thus. 27. In this case. Thus. On the other hand.  The Hashtable class is considered to be a legacy class. it returns a negative integer. while a Hashtable doesn’t allow neither null keys. It provides random access to its elements with a performance equal to O(1). we can provide a Comparator that is responsible for ordering the elements of the PriorityQueue. It returns a negative integer. which contains two methods. On the other hand. 28. but they differ on the following features:  An ArrayList is an index based data structure backed by an Array. The method returns true. equal to. which contains only one method. However. they differ in the following features:  A HashMap allows the existence of null keys and values. equal or greater than the existing object. Specifically. have very similar characteristics.  A Hashtable is synchronized. while an ArrayList can contain only objects. or a positive integer to indicate that the input object is less than. or . removeAll. Thus. What is Comparable and Comparator interface ? List their differences. The second method requires an object as a parameter and aims to decide whether the input object is equal to the comparator. HashMap is preferred in singlethreaded environments. What is Java Priority Queue ? The PriorityQueue is an unbounded queue. because every node in a LinkedList stores two references. This method compares two objects. At the time of its creation. etc.  A LinkedList consumes more memory than an ArrayList. the collections use autoboxing to reduce the coding effort. those objects that doesn’t provide natural ordering. What is difference between Array and ArrayList ? When will you use Array over ArrayList ? The Arrayand ArrayList classes differ on the following features:  Arrays can contain primitive or objects. a LinkedList stores its data as list of elements and every element is linked to its previous and next element. such as addAll. zero. a HashMap is fail-fast. zero. A PriorityQueue doesn’t allow null values.  The Insertion.

compared to that of an unordered array. 30. Instead. Also. instead of an ArrayList. its elements are not ordered.those objects that don’t have any comparator associated with them. For example if the size of the elements is fixed and know a priori. something which is not possible withEnumerations. The elements in a TreeSet are sorted. the add. a TreeSet is implemented using a tree structure. by using Generics you avoid theClassCastException during runtime. remove. the Iterator is much safer compared to Enumeration. and contains methods of a HashSet have constant time complexity O(1). based on time.  Program in terms of interface not implementation. What’s the difference between Enumeration and Iterator interfaces ? Enumeration is twice as fast as compared to an Iterator and uses very less memory. and robustness.  Always use Generics for type-safety. The Big-O notation can also be used to describe other behavior such as memory consumption. Big-O notation can give a good indication about performance for large amounts of data. the Java PriorityQueue is not thread-safe and it requires O(log(n)) time for its enqueing and dequeing operations. 31. What is the difference between HashSet and TreeSet ? The HashSet is Implemented using a hash table and thus. we can use it to avoid rehashing or resizing. the insertion operation for an unordered array takes constant time of O(1). is very crucial for its performance. in order to avoid the implementation of the hashCode and equals methods for our custom class. What are some of the best practices relating to the Java Collection framework ?  Choosing the right type of the collection to use. The add. and thus. and contains methods have time complexity of O(logn). Thus.  Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map. because other threads are not able to modify the collection object that is currently traversed by the iterator. we shall use an Array. based on the application’s needs. The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n). 33. What do you know about the big-O notation and can you give some examples with respect to different data structures ? The Big-O notation simply describes how well an algorithm scales or performs in the worst case scenario as the number of elements in a data structure increases. On the other hand. Also. However. because the elements with higher values must be moved to make room for the new element. we usually use the Big-O notation to chose the best implementation to use.  Some collection classes allow us to specify their initial capacity. 32. which is O (n). Finally. 34. memory and performance. What is the tradeoff between using an unordered array versus an ordered array ? The major advantage of an ordered array is that the search times have time complexity of O(log n). Since the collection classes are actually data structures.Iteratorsallow the caller to remove elements from the underlying collection. remove. Garbage Collectors .  Return zero-length collections or arrays as opposed to returning a null in case the underlying collection is actually empty. if we have an estimation on the number of elements that will be stored. readability.

It is normally advised to release resources held by the object inside the finalize method. you will find that PermGen space is also garbage collected. this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time. See here for tips on Java exception handling. 40. Unchecked exceptions do not need to be declared in a method or a constructor’s throws clause. if they can be thrown by the execution of the method or the constructor. Does Garbage collection occur in permanent generation space in JVM ? Garbage Collection does occur in PermGen space and if PermGen space is full or cross a threshold. Dead objects are those which will never be accessible by the application. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector.gc() and Runtime. What does System. Such objects occupy the heap memory space until they are eventually collected by the garbage collector. 42.35. Also check our article Java 8: PermGen to Metaspace. What is structure of Java Heap ? What is Perm Gen space in Heap ? The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. 39. Exception Handling 43. in order to start a garbage collection. 41. and propagate outside the method or constructor boundary. If you look carefully at the output of the garbage collector. just before releasing the object’s memory. When is the finalize() called ? What is the purpose of finalization ? The finalize method is called by the garbage collector. the object will be available for garbage collection in the next cycle of the garbage collector. If an object reference is set to null. and when is it used ? The purpose of garbage collection is to identify and discard those objects that are no longer needed by the application. 44. but have not been collected by the garbage collector yet. What is the difference between Serial and Throughput Garbage collector ? The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. What is the difference between Exception and Error in java ? Exception and Error classes are both subclasses of the Throwable class. checked exceptions must be declared in a method or a constructor’s throws clause. This is the reason why correct sizing of PermGen space is important to avoid frequent full garbage collections.gc() methods do ? These methods can be used as a hint to the JVM. 36. in order for the resources to be reclaimed and reused. On the other hand. Heap memory consists of live and dead objects. 38. On the other hand. the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors). What is the purpose of garbage collection in Java. it can trigger a full garbage collection. The Exception class is used for exceptional conditions that a . What are the two types of Exceptions in Java ? Which are the differences between them ? Java has two types of exceptions: checked exceptions and unchecked exceptions. will the Garbage Collector immediately free the memory held by that object ? No. 37. Live objects are accessible by the application and will not be a subject of garbage collection. When does an Object becomes eligible for Garbage collection in Java ? A Java object is subject to garbage collection when it becomes unreachable to the program in which it is currently used. However.

 An applet cannot start any program on the host that’s executing it. it starts running.  An applet cannot read certain system properties. 45. . whether or not an exception is actually thrown. Finally. the following restrictions are imposed on Java applets:  An applet cannot load libraries or define native methods. in order to start its execution. 52. so the callers of that method can guard against possible exceptions. What is the difference between an Applet and a Java Application ? Applets are executed within a java enabled browser.  An applet cannot make network connections except to the host that it came from. database connections. What happens when an applet is loaded ? First of all.user’s program should catch.  An applet cannot ordinarily read or write files on the execution host. However. 47. Java applets typically use a restrictive security policy. What will happen to the Exception object after exception handling ? The Exception object will be garbage collected in the next garbage collection. Applets are used for creating dynamic and interactive web applications. Then. Explain the life cycle of an Applet. Even in the case where the catch statement is missing and an exception is thrown. 45. An applet may undergo the following states:  Init: An applet is initialized each time is loaded. an instance of the applet’s controlling class is created. which is called by the Java Virtual Machine (JVM) just before an object is garbage collected. 51. Java Applets 48. On the contrary. the throws clause is used to indicate those exceptions that are not handled by a method. before unloading the applet. 49. The Error class defines exceptions that are not excepted to be caught by the user program. Each method must explicitly specify which exceptions does not handle. 50.  Start: Begin the execution of an applet. Finally. the finally block will still be executed. multiple exceptions are separated by a comma. etc. but a Java application is a standalone Java program that can be executed outside of a browser. Furthermore. How does finally block differ from finalize() method ? A finally block will be executed whether or not an exception is thrown and is used to release those resources held by the application. Finalize is a protected method of the Object class. 46. the applet initializes itself and finally. What is an Applet ? A java applet is program that can be included in a HTML page and be executed in a java enabled client browser. What is the importance of finally block in exception handling ? A finally block will always be executed.  Destroy: Perform a final cleanup.  Stop: Stop the execution of an applet. What are the restrictions imposed on Java applets ? Mostly due to security reasons. they both require the existence of a Java Virtual Machine (JVM). What is the difference between throw and throws ? The throw keyword is used to explicitly raise a exception within the program. a Java application requires a main method with a specific signature. Java applets don’t need such a method to start their execution. Last thing to mention is that the finally block is used to release resources like I/O buffers. while Java applications usually use more relaxed security policies.

and what does it provide ? The applet security manager is a mechanism to impose restrictions on Java applets. revalidate. 55. the class loader guarantees that a unique namespace exists for classes that come from the local file system. A List supports the selection of one or more List items. those classes loaded by the class loader are passed through the verifier. all downloaded applets are considered as untrusted. What are untrusted applets ? Untrusted applets are those Java applets that cannot access or execute local system files. or extended. and it cannot thereafter be replaced. 64. overridden. the applet is loaded by the applet classloader. The security manager is established at startup. What is the applet security manager. A browser may only have one security manager. 61. Swing 57. By default. What is clipping ? Clipping is defined as the process of confining paint operations to a limited area or shape. 62. Frame. A ScrollPane handles its own events and performs its own scrolling. and Applet classes support painting. 58. South.53. What is the difference between a MenuItem and a CheckboxMenuItem ? The CheckboxMenuItem class extends the MenuItem class and supports a menu item that may be either checked or unchecked. What is the difference between applets loaded over the internet and applets loaded via the file system ?Regarding the case where an applet is loaded over the internet. 63. The class loader enforces the Java name space hierarchy. applets loaded via the file system are not passed through the byte code verifier. . and invalidate. What is the difference between a Choice and a List ? A Choice is displayed in a compact form that must be pulled down. Name three Component subclasses that support painting. 54. What is the difference between a Scrollbar and a JScrollPane ? A Scrollbar is a Component. in order for a user to be able to see the list of all available choices. 56. Then. Also. When a browser loads an applet over the net. East.The verifier checks that the class file conforms to the Java language specification . that applet’s classes are placed in a private namespace associated with the applet’s origin. Among other things. and West) and the center of a container. the verifier ensures that there are no stack overflows or underflows and that the parameters to all bytecode instructions are correct. Regarding the case where an applet is loaded from the client’s local disk. What is the applet class loader. overloaded. and that a unique namespace exists for each network source. What is a layout manager ? A layout manager is the used to organize the components in a container. write files and to load libraries on the client. 59. the applet is loaded by the applet classloader and is subject to the restrictions enforced by the applet security manager. applets loaded via the file system are allowed to execute processes and finally. A ScrollPane is a Container. Applets loaded via the file system are allowed to read files. 60. The Canvas. and what does it provide ? When an applet is loaded over the internet. Which Swing methods are thread-safe ? There are only three thread-safe methods: repaint. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. Panel. the applet is loaded by the file system loader. Also. How are the elements of a BorderLayout organized ? The elements of a BorderLayout are organized at the borders (North. but not aContainer.

forName method ? This method is used to method is used to load the driver that will establish a connection to the database.sql package:Connection. 67. across all windowing platforms.A CallableStatement is used to execute stored procedures. PreparedStatement. Also. What is JDBC ? JDBC is an abstraction layer that allows users to choose between databases. 74. ResultSet and Driver. What is the difference between a Window and a Frame ? The Frame class extends the Window class and defines a main application window that can have a menu bar. Thus. 73. How can a GUI component handle its own events ? A GUI component can handle its own events. Statement. Each driver must provide implementations for the following classes of the java. Especially. because it offers security and modularity. this cost is very high and a large number of resources is consumed.their performance is much better. What does Connection pooling mean ? The interaction with a database can be costly. JDBC 72. An event adapter provides a default implementation of an eventlistener interface. without having to concern themselves with the underlying details of a particular database. Since layout managers aren’t tied to absolute sizing and positioning.A pool of database connections is obtained at start up by the application server and is maintained in . the rows and columns may have different sizes. What is the purpose Class. 66. regarding the opening and closing of database connections. 69. they are able to accomodate platform-specific differences among windowing systems. The elements are of different sizes and may occupy more than one row or column of the grid. What advantage do Java’s layout managers provide over traditional windowing systems ? Java uses layout managers to lay out components in a consistent manner. 70. The usage of stored procedures is highly encouraged. it sets the clipping regions to the area of the window that requires repainting. 68. JDBC enables developers to write database applications in Java. What is the advantage of PreparedStatement over Statement ? PreparedStatements are precompiled and thus. which is used to prepare a CallableStatement. by implementing the corresponding event-listener interface and adding itself as its own event listener. Explain the role of Driver in JDBC. 75. What is the design pattern that Java uses for all Swing components ? The design pattern used by Java for all Swing components is the Model View Controller (MVC) pattern. PreparedStatement objects can be reused with different input values to their queries. when the number of database clients increases. How are the elements of a GridBagLayout organized ? The elements of a GridBagLayout are organized according to a grid.The method that prepares a CallableStatement is the following: 1 CallableStament. What is the relationship between clipping and repainting ? When a window is repainted by the AWT painting thread. CallableStatement. What is the use of CallableStatement ? Name the method. 71. The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API.65.prepareCall(). 77. Stored procedures are stored and offered by a database. What is the relationship between an event-listener interface and an event-adapter class ? An event-listener interface defines the methods that must be implemented by an event handler for a particular event. Stored procedures may take input values from the user and may return a result. 76.

Naming class provides methods for storing and obtaining references to remote objects in the remote object registry. This layer is responsible for intercepting method calls made by the client to the interface and redirect these calls to a remote RMI Service. 84. Any object that is a remote object must directly or indirectly implement this interface. . with support for direct transfer of serialized Java classes and distributed garbage collection. What is the basic principle of RMI architecture ? The RMI architecture is based on a very important principle which states that the definition of the behavior and the implementation of that behavior. This layer interprets and manages references made from clients to the remote service objects. Check some RMI Tips here. while the rebind method is responsible for rebinding the specified name to a new remote object. In case a binding exists for that name. 80. are separate concepts.Naming Class ? The java. 83. What is the role of the java. What is the role of Remote Interface in RMI ? The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. 82. What is meant by binding in RMI ? Binding is the process of associating or registering a name for a remote object. 81.  Remote Reference Layer: The second layer of the RMI architecture deals with the interpretation of references made from the client to the server’s remote objects. define the constructor for each remote object and provide an implementation for each remote method in all remote interfaces. A request for a connection is served by a connection residing in the pool. in order to look up that remote object. A remote object can be associated with a name using the bind or rebind methods of the Naming class. The connection is a oneto-one (unicast) link.  Transport layer: This layer is responsible for connecting the two JVM participating in the service.a pool.rmi. What is the difference between using bind() and rebind() methods of Naming Class ? The bind method bind is responsible for binding the specified name to a remote object. A class that implements a remote interface should declare the remote interfaces being implemented. It provides basic connectivity. Remote Method Invocation (RMI) 78. as well as some firewall penetration strategies. the binding is replaced. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs. What are the layers of RMI Architecture ? The RMI architecture consists of the following layers:  Stub and Skeleton layer: This layer lies just beneath the view of the developer. the request is returned to the pool and can be used to satisfy future requests. Each method of the Naming class takes as one of its arguments a name that is a String in URL format. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object. What is RMI ? The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC). In the end of the connection.rmi. which can be used at a later time. This layer is based on TCP/IP connections between machines in a network. 79.

What are the steps involved to make work a RMI program ? The following steps must be involved in order for a RMI program to work properly:  Compilation of all source files. Explain Marshalling and demarshalling. provide dynamic content and manage state information that does not exist in the stateless HTTP protocol. Explain Serialization and Deserialization. called object serialization where an object can be represented as a sequence of bytes and includes the object’s data. When an application wants to pass its memory objects across a network to another host or persist it to storage.  It marshals the parameters to the remote JVM. What is the role of stub in RMI ? A stub for a remote object acts as a client’s local representative or proxy for the remote object.  It unmarshals the return value or an exception if the method has not been successfully executed. serialization can be seen as a way of flattening objects. 87. it undergoes the following steps:  It initiates a connection to the remote JVM containing the remote object.  It returns the value to the caller. Servlets are mostly used to process or store data submitted by an HTML form. the in-memory representation must be converted to a suitable format. What is a Servlet ? The servlet is a Java programming language class used to process client requests and generate dynamic web content. This process is called marshalling and the revert operation is called demarshalling. What is the purpose of using RMISecurityManager in RMI ? RMISecurityManager provides a security manager that can be used by RMI applications. When a stub’s method is invoked. as well as information about the object’s type. if the security manager has not been set. read back and reconstituted.  Run the client program. Thus. 88. in order to be stored on disk. The caller invokes a method on the local stub. 89. Servlets 91. The class loader of RMI will not download any classes from remote locations. Java provides a mechanism.  It waits for the result of the method invocation and execution. DGC uses a reference counting algorithm to provide automatic memory management for remote objects. Since RMI involves remote object references across JVM’s. 86. and later. which is responsible for executing the method on the remote object.85. Deserialisation is the reverse process of converting an object from its flattened state to a live object.  Generatation of the stubs using rmic. garbage collection can be quite difficult.  Start the rmiregistry. which use downloaded code. Remote Method Invocation (RMI) uses DGC for automatic garbage collection.  Start the RMIServer. What is DGC ? And how does it work ? DGC stands for Distributed Garbage Collection. . and the types of data stored in the object. 90.

by invoking the service method for each request separately. your servlet must extend the HttpServlet instead. Furthermore. When a Web page is accessed by a browser. There are two types of web applications: presentation-oriented and serviceoriented. Instead. the Web server replaces the servlet tag in that Web page with the hyper text generated by the corresponding servlet. In general. doPOST: The POST method overcomes the limit imposed by the GET request. by sending the values of the request inside its body. and is embedded with a servlet tag. a Web application can be seen as a collection of servlets installed under a specific subset of the server’s URL namespace.servlet. What is the structure of the HTTP response ? The HTTP response consists of three parts: . What is the difference between doGet() and doPost() ? doGET: The GET method appends the name-value pairs on the request’s URL. there is no limitations on the number of values to be sent across. On the other hand.92. the values of the request are made visible and thus. Those servlets extending the GenericServlet class shall override the service method. What is meant by a Web Application ? A Web application is a dynamic extension of a Web or application server. 99.servlet. a servlet waits for client’s HTTP requests and generates a response in every request. 95. in order for the servlet to be initialized. Finally. Each servlet must implement it either directly or indirectly. The most frequent use of SSI is to include the contents of one or more files into a Web page on a Web server. What is Servlet Chaining ? Servlet Chaining is the method where the output of one servlet is sent to a second servlet. Explain the life cycle of a Servlet. 101.servlet. 93. What is the difference between an Applet and a Servlet ? An Applet is a client side java program that runs within a Web browser on the client machine. the Servlet Engine loads the servlets and invokes its init methods. used almost exclusively for the Web. Check Servlet examples here. Also. and so on. 100. See example here. either by extending javax. a service-oriented web application implements the endpoint of a web service. sensitive information must not be passed in that way. each servlet is able to serve multiple requests in parallel using multithreading. Explain the architechure of a Servlet. What is the difference between GenericServlet and HttpServlet ? GenericServlet is a generalized and protocol-independent servlet that implements the Servlet and ServletConfig interfaces. On the other hand.GenericServlet or javax. in order to develop an HTTP servlet for use on the Web that serves requests using the HTTP protocol. which contain various types of markup language and dynamic content in response to requests. A presentation-oriented Web application generates interactive web pages. Finally. the servlet is removed by calling the server’s destroy method. What is a Server Side Include (SSI) ? Server Side Includes (SSI) is a simple interpreted server-side scripting language. Then. 98. The core abstraction that must be implemented by all servlets is the javax.HTTPServlet. while a servlet does not have a user interface.An applet can use the user interface classes. the sensitive information passed through a POST request is not visible to an external client.http. 94. Finally.Servlet interface. a servlet is a server side component that runs on the web server. 96. On every client’s request. 97. The last servlet in the chain is responsible for sending the response to the client. getRemoteAddr() gets the IP address of the client machine and getRemoteHost() gets the host name of the client machine. the Servlet object handles all subsequent requests coming from that client. there is a limit on the number of characters and subsequently on the number of values that can be used in a client’s request. The output of the second servlet can be sent to a third servlet. How do you find out what client machine is making a request to your servlet ? The ServletRequest class has functions for finding out the IP address or host name of the client machine. Finally. Thus.

See how to retrieve headers in Servlet here. What is URL Encoding and URL Decoding ? The URL encoding procedure is responsible for replacing all the spaces and every other extra special character of a URL. What is HTTP Tunneling ? HTTP Tunneling is a technique by which. What is a cookie ? What is the difference between session and cookie ? A cookie is a bit of information that the Web server sends to the browser. while the forward method just forwards a request to a new target. The masking of other protocol requests as HTTP requests is HTTP Tunneling. The HTTP session is capable of storing any Java object.SC_OK. What is a JSP Page ? A Java Server Page (JSP) is a text document that contains two types of text: static data and JSP elements. FInally.The differences between session and a cookie are the following:  The session should work. or the form of encoding used to safely transfer the entity to the user. URL decoding is the exact opposite procedure. HttpServletResponse. What’s the difference between sendRedirect and forward methods ? The sendRedirect method creates a new request. JSP is a technology that mixes static content with dynamically-generated content. The HTTP protocol therefore acts as a wrapper for a channel that the network protocol being tunneled uses to communicate. into their corresponding Hex representation. the browser. If your servlet does not return a status code. the sessions still work.  HTTP Headers: they contain more information about the response. The body may contain HTML code. Which protocol will be used by browser and servlet to communicate ? The browser communicates with a servlet by using the HTTP protocol. etc. 104. It can be used to check if the request has been successfully completed. The previous request scope objects are not available after a redirect. For example. 106. However. as the client has no ability to disable them in the server side. The browser stores the cookies for each Web server in a local file. In correspondence. sends all stored cookies for that specific Web server. the sendRedirect method is considered to be slower compare to the forward method. 102. The body consists of the data bytes transmitted in an HTTP transaction message immediately following the headers.  JSP 107. See JSP example here. such as HTML or XML. along with the request.  Body: it contains the content of the response. in general. an image. Static data can be expressed in any text-based format. regardless of the settings on the client browser. the headers may specify the date/time after which the response is considered stale. the previous request scope objects are available after forwarding. communications performed using various network protocols are encapsulated using the HTTP or HTTPS protocols. because it results in a new request.  The session and cookies also differ in the amount of information the can store. . is returned by default. while a cookie can only store String objects. the status code can be used to find out the reason behind the failure. the success status code. The client may have chosen to disable cookies.Status Code: describes the status of the response. 105. 103. On the other hand. In a future request. In case the request failed.

109. JSP actions are executed when a JSP page is requested. when the page is compiled to a servlet.108. Directives are used to set page-level instructions. when the JSP page is requested. Then.  Page directive : it is used to define specific attributes in the JSP page. What are Scriptlets ? In Java Server Pages (JSP) technology.  jsp:forward – forwards the requester to a new page. Notice that the JSP file is compiled only on the first request of the page. or if the JSP file has changed.  jsp:setProperty – sets the property of a JavaBean.The different types of directives are shown below:  Include directive: it is used to include a file and merges the content of the file with the current page. 113. insert data from external files. 110. Directives are defined between < %@ and % >. the servlet sends a response back to the client. the browser first requests a page with a . or generate HTML for the Java plugin. 111.  jsp:useBean – finds or instantiates a JavaBean. What are the advantages of JSP ? The advantages of using the JSP technology are shown below:  JSP pages are dynamically compiled into servlets and thus. 112. re-use JavaBeans components. Between these tags. .  Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax. a user can add any valid scriplet. Once the execution of the request is over.  JSP pages can be pre-compiled. What are JSP actions ? JSP actions use constructs in XML syntax to control the behavior of the servlet engine. The scriptlet is everything inside the tags. How are the JSP requests handled ? On the arrival of a JSP request. without editing the individual pages that use the application’s logic.  jsp:plugin – generates browser-specific code. including HTML or XML fragments. Declarations are used to declare variables for subsequent use in expressions or scriptlets. the developers can easily make updates to presentation code. with code that generates dynamic content. What are Decalarations ? Declarations are similar to variable declarations in Java. To add a declaration. in order to handle the browser’s request. the Web server converts the JSP page into a servlet class.  JSP pages can be easily combined to static templates. They can be dynamically inserted into a file.The generated servlet class is invoked. the Web server reads the request and using the JSP compiler. and specify custom tag libraries. you must use the sequences to enclose your declarations. What are Directives ? What are the different types of Directives available in JSP ? Directives are instructions that are processed by the JSP engine.Some of the available actions are listed below:  jsp:include – includes a file.jsp extension. like error page and buffer. See how to get Request parameters in a JSP.  Developers can make logic changes at the component level.  jsp:getProperty – gets the property of a JavaBean. forward the user to another page. a scriptlet is a piece of Javacode embedded in a JSP page.  Taglib: it is used to declare a custom tag library which is used in the page.

114.The following objects are considered implicit in a JSP page:          application page request response session exception out config pageContext Still with us? Wow. that was a huge article about different types of questions that can be used in a Java interview. If you enjoyed this. What are Expressions ? A JSP expression is used to insert the value of a scripting language expression. then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers! Also. check outJCG Academy for more advanced training! So. 115. Expressions are defined between <% = and %>tags. into the data stream returned to the client. A developer can call them directly. by the web server. What is meant by implicit objects and what are they ? JSP implicit objects are those Java objects that the JSP Container makes available to developers in each page. JSP Implicit Objects are also called pre-defined variables. without being explicitly declared. what other Java interview questions are there? Let us know in the comments and we will include them in the article! Happy coding! . converted into a string.