What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitier, 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 component deployment 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 its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
* Application clients and applets are client components.
* Java Servlet and JavaServer Pages (JSP) technology components are web components.
* Enterprise JavaBeans (EJB) components are business components.
* Resource adapter components provided by EIS and tool vendors.
4. 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.
5. 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.
6. What are the differences between Ear, Jar and War files? Under what circumstances should we use each one?
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 are intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
*War files are intended to contain complete Web applications.
*Ear files are intended to contain complete enterprise applications.
Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.
7. What is an applet?
A J2EE component that typically executes in a Web browser but can execute in a variety of other applications or devices that support the applet programming model.
8. What is applet container?
A container that includes support for the applet programming model.
9. What is application assembler?
A person who combines J2EE components and modules into deployable application units
10. What is application client?
A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.
11. What is application client container?
A container that supports application client components.
12. What is application client module?
A software unit that consists of one or more classes and an application client deployment descriptor.
13. What is application component provider?
A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors.
14. What is application configuration resource file?
An XML file used to configure resources for a Java Server Faces application, to define navigation rules for the application, and to register converters, Validator, listeners, renders, and components with the application.
15. What is build file?
The XML file that contains one or more ant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project's default target is executed.
ant - is a tool that is used to build web applications
16. What is deployment?
The process whereby software is installed into an operational environment. For ex: deploying an EAR file into a Weblogic Server.
17. What is deployment descriptor?
An XML file provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.
18. What is HTML?
Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic text formatting.
19. What is HTTP?
Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTP messages consist of requests from client to server and responses from server to client.
20. What is HTTPS?
HTTP layered over the SSL protocol. It is the secure version of the HTTP protocol
21. 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.
22. What is JDBC?
An JDBC for database-independent connectivity between the J2EE platform and a wide range of data sources.
23. What is JNDI?
Abbreviate of Java Naming and Directory Interface. It is used as part of JDBC
24. 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
25. What is resource adapter?
A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by the adapter) or tool-generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.
26. What is Secure Socket Layer (SSL)?
A technology that allows Web browsers and Web servers to communicate over a secured connection.
27. 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.
28. What is URL?
Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the World Wide Web. A URL looks like this:
protocol://host/local info
where protocol specifies a protocol for fetching the object (such as http or ftp), host specifies the Internet name of the targeted host, and local info is a string (often a file name) passed to the protocol handler on the remote host.
29. 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 the servlet 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 end with a / character. Servlet path is the path section that directly corresponds to the mapping that activated this request. This path starts with a / character. Path info is the part of the request path that is not part of the context path or the servlet path
30. What is URN?
Uniform resource name. A unique identifier that identifies an entity but doesn't tell where it is located. A system can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Web location to change, while still allowing the entity to be found.
I created this blog for programming in Java related technologies to sharpen my skills and to obtain feedback from others. Whenever I see interesting thing regarding technology, I plan to code it and put it here. I hope this will benefit people out there and help me learn from others. Hope you will enjoy the posts in my blog
Friday, December 28, 2012
Threads
Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
2. What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread to sleep (Or prevent the thread from executing) for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call.
The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
3. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
4. What is Runnable interface ? Are there any other ways to make a multithreaded java program?
There are two ways to create new threads:
- Define a new class that extends the Thread class
- Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor.
The advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.
5. How can I tell what state a thread is in ?
Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.
Starting with the release of Java Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.
New, Runnable, Blocked, Waiting, Timed_waiting and Terminated
6. What is the difference between notify and notify All methods ?
A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notifyAll
so, sometimes it is better to use notify than notifyAll.
7. What is synchronized keyword? In what situations you will Use it?
Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. It helps prevent dirty read/write and helps keep thread execution clean and seperate. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.
8. Why do threads block on I/O?
Threads block on i/o (i.e., Thread enters the waiting state) so that other threads may execute while the i/o Operation is performed. This is done to ensure that one thread does not hold on to resources while it is waiting for some user input - like entering a password.
9. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.
10. 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.
11. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
Actually there is nothing new about these methods. The stop(), suspend() and resume() methods have been deprecated as of JDK 1.2.
12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
13. How do you make threads to wait for one another to complete execution as a group?
We can use the join() method to make threads wait for one another
14. 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.
15. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and many other factors. You can refer to articles on Operating Systems and processor scheduling for more details on the same.
16. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
17. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
18. 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.
19. What invokes a thread's run() method?
After a thread is started, via its start() method, the JVM invokes the thread's run() method when the thread needs to be executed.
20. 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.
21. 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 a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.
22. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
23. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
24. What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
25. 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 between executing tasks, it creates the impression that tasks execute sequentially.
26. 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 enters the running state, an InterruptedException is thrown.
27. How can a dead thread be restarted?
A dead thread cannot be restarted. Once a thread is dead, it stays dead and there is no way to revive it.
28. 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 unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
29. 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 Runnable interface. Without a run() method, a thread cannot execute.
30. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
A synchronized statement can be inside a regular method and vice versa.
31. What are volatile variables
It indicates that these variables can be modified asynchronously. i.e., there is no need for synchronzing these variables in a multi-threaded environment.
32. Where does java thread support reside
It resides in three distinct places
The java.lang.Thread class (Most of the support resides here)
The java.lang.Object class
The java language and virtual machine
33. What is the difference between Thread and a Process
Threads run inside process and they share data.
One process can have multiple threads, if the process is killed all the threads inside it are killed
34. What happens when you call the start() method of the thread
This registers the thread with a piece of system code called thread scheduler. The schedulers is the entity that determines which thread is actually running. When the start() method is invoked, the thread becomes ready for running and will be executed when the processor allots CPU time to execute it.
35. Does calling start () method of the thread causes it to run
No it just makes the thread eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run
36. When the thread gets to execute, what does it execute
It executes all the code that is placed inside the run() method.
37. How many methods are declared in the interface runnable
The runnable method declares only one method : public void run();
38. Which way would you prefer to implement threading - by extending Thread class or implementing Runnable interface
The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class in Java.
39. What happens when the run() method returns
When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread.
40. What are the different states of the thread
The different states of Threads are:
New: Just created Thraed
Running: The state that all threads want to be
Various waiting states : Waiting, Sleeping, Suspended and Blocked
Ready : Waiting only for the CPU
Dead : Story Over
41. What is Thread priority
Every thread has a priority, the higher priority thread gets preference over the lower priority thread by the thread scheduler
42. What is the range of priority integer that can be set for Threads?
It is from 1 to 10. 10 beings the highest priority and 1 being the lowest
43. What is the default priority of the thread
The default priority is 5. It is also called the Normal Priority.
44. What happens when you call Thread.yield()
It causes the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread
45. What is the advantage of yielding
It allows a time consuming thread to permit other threads to execute
46. What happens when you call Thread.sleep()
It causes the thread to while away time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time as mentioned in the argument to the sleep method.
47. Does the thread method start executing as soon as the sleep time is over
No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so. There is no guarantee that the thread will start running as soon as its sleep time is over.
48. What do you mean by thread blocking
If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked.
49. What threading related methods are there in object class
wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only
50. What is preemptive scheduling
Preemptive scheduing is a scheduling mechanism wherein, the scheduler puts a lower priority thread on hold when a higher priority thread comes into the waiting queue. The arrival of a higher priority thread always preempts the execution of the lower priority threads. The problem with this system is - a low priority thread might remain waiting for ever.
51. What is non-preemptive or Time sliced or round robin scheduling
With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must wait along with all the other ready threads. This method ensures that all threads get some CPU time to execute.
52. What are the two ways of synchronizing the code
Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method.
Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code
53. What happens when the wait() method is called
The following things happen:
The calling thread gives up CPU
The calling thread gives up the lock
The calling thread goes into the monitor's waiting pool
54. What happens when the notify() method is called
One thread gets moved out of monitors waiting pool and into the ready state and The thread that was notified must reacquire the monitors lock before it can proceed execution
55. Using notify () method how you can specify which thread should be notified
You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method
Questions Contributed by our Blog Readers:
Contributed by Sweta Pawar:
Which statement at line 17 will ensure that j=10 at line 18
1 class A implements runaible (
2 int i;
3 public void run () (
4 try (
5 thread.sleep(5000);
6 i= 10;
7 ) catch(InterruptedException e) {}
8 )
9 )
10
11 public class Test {
12 public static void main (string args[]) (
13 try (
14 A a = new A ();
15 Thread t = new Thread (a);
16 t.start();
17 ** HERE**
18 int j= a.i;
19
20 ) catch (Exception e) {}
21 )
22 )
Answer: t.join();
Synchronized blocks place locks for shorter periods than synchronized methods.
2. What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread to sleep (Or prevent the thread from executing) for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call.
The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
3. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
4. What is Runnable interface ? Are there any other ways to make a multithreaded java program?
There are two ways to create new threads:
- Define a new class that extends the Thread class
- Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor.
The advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.
5. How can I tell what state a thread is in ?
Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.
Starting with the release of Java Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.
New, Runnable, Blocked, Waiting, Timed_waiting and Terminated
6. What is the difference between notify and notify All methods ?
A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notifyAll
so, sometimes it is better to use notify than notifyAll.
7. What is synchronized keyword? In what situations you will Use it?
Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. It helps prevent dirty read/write and helps keep thread execution clean and seperate. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.
8. Why do threads block on I/O?
Threads block on i/o (i.e., Thread enters the waiting state) so that other threads may execute while the i/o Operation is performed. This is done to ensure that one thread does not hold on to resources while it is waiting for some user input - like entering a password.
9. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.
10. 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.
11. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
Actually there is nothing new about these methods. The stop(), suspend() and resume() methods have been deprecated as of JDK 1.2.
12. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
13. How do you make threads to wait for one another to complete execution as a group?
We can use the join() method to make threads wait for one another
14. 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.
15. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and many other factors. You can refer to articles on Operating Systems and processor scheduling for more details on the same.
16. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
17. What is a task's priority and how is it used in scheduling?
A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
18. 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.
19. What invokes a thread's run() method?
After a thread is started, via its start() method, the JVM invokes the thread's run() method when the thread needs to be executed.
20. 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.
21. 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 a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.
22. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
23. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
24. What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
25. 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 between executing tasks, it creates the impression that tasks execute sequentially.
26. 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 enters the running state, an InterruptedException is thrown.
27. How can a dead thread be restarted?
A dead thread cannot be restarted. Once a thread is dead, it stays dead and there is no way to revive it.
28. 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 unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
29. 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 Runnable interface. Without a run() method, a thread cannot execute.
30. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
A synchronized statement can be inside a regular method and vice versa.
31. What are volatile variables
It indicates that these variables can be modified asynchronously. i.e., there is no need for synchronzing these variables in a multi-threaded environment.
32. Where does java thread support reside
It resides in three distinct places
The java.lang.Thread class (Most of the support resides here)
The java.lang.Object class
The java language and virtual machine
33. What is the difference between Thread and a Process
Threads run inside process and they share data.
One process can have multiple threads, if the process is killed all the threads inside it are killed
34. What happens when you call the start() method of the thread
This registers the thread with a piece of system code called thread scheduler. The schedulers is the entity that determines which thread is actually running. When the start() method is invoked, the thread becomes ready for running and will be executed when the processor allots CPU time to execute it.
35. Does calling start () method of the thread causes it to run
No it just makes the thread eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run
36. When the thread gets to execute, what does it execute
It executes all the code that is placed inside the run() method.
37. How many methods are declared in the interface runnable
The runnable method declares only one method : public void run();
38. Which way would you prefer to implement threading - by extending Thread class or implementing Runnable interface
The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class in Java.
39. What happens when the run() method returns
When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread.
40. What are the different states of the thread
The different states of Threads are:
New: Just created Thraed
Running: The state that all threads want to be
Various waiting states : Waiting, Sleeping, Suspended and Blocked
Ready : Waiting only for the CPU
Dead : Story Over
41. What is Thread priority
Every thread has a priority, the higher priority thread gets preference over the lower priority thread by the thread scheduler
42. What is the range of priority integer that can be set for Threads?
It is from 1 to 10. 10 beings the highest priority and 1 being the lowest
43. What is the default priority of the thread
The default priority is 5. It is also called the Normal Priority.
44. What happens when you call Thread.yield()
It causes the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread
45. What is the advantage of yielding
It allows a time consuming thread to permit other threads to execute
46. What happens when you call Thread.sleep()
It causes the thread to while away time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time as mentioned in the argument to the sleep method.
47. Does the thread method start executing as soon as the sleep time is over
No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so. There is no guarantee that the thread will start running as soon as its sleep time is over.
48. What do you mean by thread blocking
If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked.
49. What threading related methods are there in object class
wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only
50. What is preemptive scheduling
Preemptive scheduing is a scheduling mechanism wherein, the scheduler puts a lower priority thread on hold when a higher priority thread comes into the waiting queue. The arrival of a higher priority thread always preempts the execution of the lower priority threads. The problem with this system is - a low priority thread might remain waiting for ever.
51. What is non-preemptive or Time sliced or round robin scheduling
With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must wait along with all the other ready threads. This method ensures that all threads get some CPU time to execute.
52. What are the two ways of synchronizing the code
Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method.
Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code
53. What happens when the wait() method is called
The following things happen:
The calling thread gives up CPU
The calling thread gives up the lock
The calling thread goes into the monitor's waiting pool
54. What happens when the notify() method is called
One thread gets moved out of monitors waiting pool and into the ready state and The thread that was notified must reacquire the monitors lock before it can proceed execution
55. Using notify () method how you can specify which thread should be notified
You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method
Questions Contributed by our Blog Readers:
Contributed by Sweta Pawar:
Which statement at line 17 will ensure that j=10 at line 18
1 class A implements runaible (
2 int i;
3 public void run () (
4 try (
5 thread.sleep(5000);
6 i= 10;
7 ) catch(InterruptedException e) {}
8 )
9 )
10
11 public class Test {
12 public static void main (string args[]) (
13 try (
14 A a = new A ();
15 Thread t = new Thread (a);
16 t.start();
17 ** HERE**
18 int j= a.i;
19
20 ) catch (Exception e) {}
21 )
22 )
Answer: t.join();
Collections
What's the main difference between a Vector and an ArrayList
Java Vector class is internally synchronized and ArrayList is not. Hence, Vectors are thread-safe while ArrayLists are not. On the Contrary, ArrayLists are faster and Vectors are not. ArrayList has no default size while vector has a default size of 10.
2. What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the first-in-first-out (FIFO) rule
3. what is a collection?
Collection is a group of objects.
There are two fundamental types of collections they are Collection and Map.
Collections just hold a bunch of objects one after the other while Maps hold values in a key-value pair.
Collections Ex: ArrayList, Vector etc.
Map Ex: HashMap, Hashtable etc
4. What is the Collections API?
The Collections API is a set of classes and interfaces that support operation on collections of objects. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming using the collections.
The purpose of the Collection API is to:
o Reduces programming efforts. - Increases program speed and quality.
o Allows interoperability among unrelated APIs.
o Reduces effort to learn and to use new APIs.
o Reduces effort to design new APIs.
o Encourages & Fosters software reuse.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
5. What is the List interface?
The List interface provides support for ordered collections of objects. Ex: ArrayList
6. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects that is synchronzied and thread-safe.
7. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection one by one. It is an easier way to loop through the contents of a collection when you do not know, how many objects are present in it. Also, it is a cleaner way to access the contents of a collection when compared to using a for loop and accessing entries using get(index) method.
Remember that, when using Iterators they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
8. What is the Map interface?
A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot.
9. What is the Collection interface?
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
10. What is the Set interface?
• The Set interface provides methods for accessing the elements of a finite mathematical set
• Sets do not allow duplicate elements
• Contains no methods other than those inherited from Collection
• It adds the restriction that duplicate elements are prohibited
• Two Set objects are equal if they contain the same elements
11. What are different types of collections?
* A regular collection has no special order and does not reject duplicates
* A list is ordered and does not reject duplicates
* A set has no special order but rejects duplicates
* A map supports storing data as key-value pairs
12. Difference between Hashtable and HashMap?
* Hashtable does not store null value, while HashMap does
* Hashtable is synchronized, while HashMap is not
* Hashtables are slower because of the synchronization overhead while HashMaps are faster
13.What are the main Implementations of the Set interface ?
The main implementations of the List interface are as follows:
HashSet
TreeSet
LinkedHashSet
EnumSet
14.What is a HashSet ?
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted to access the object. So, the more efficient your hashcode() implementation the better access performance you’ll get. Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.
15.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.
16.Difference between HashSet and TreeSet ?
HashSet does not store data in any Order while the TreeSet stores data in order. Also, you can elements of any type to the hash set while you can only add similar types of elements into a tree set.
17.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
HashMap
HashTable
TreeMap
EnumMap
18.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
19.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
20. Can I store multiple keys or values that are null in a HashMap?
You can store only one key that has a value null. But, as long as your keys are unique, you can store as many nulls as you want in an HashMap
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Collections that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.
Java Vector class is internally synchronized and ArrayList is not. Hence, Vectors are thread-safe while ArrayLists are not. On the Contrary, ArrayLists are faster and Vectors are not. ArrayList has no default size while vector has a default size of 10.
2. What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the first-in-first-out (FIFO) rule
3. what is a collection?
Collection is a group of objects.
There are two fundamental types of collections they are Collection and Map.
Collections just hold a bunch of objects one after the other while Maps hold values in a key-value pair.
Collections Ex: ArrayList, Vector etc.
Map Ex: HashMap, Hashtable etc
4. What is the Collections API?
The Collections API is a set of classes and interfaces that support operation on collections of objects. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming using the collections.
The purpose of the Collection API is to:
o Reduces programming efforts. - Increases program speed and quality.
o Allows interoperability among unrelated APIs.
o Reduces effort to learn and to use new APIs.
o Reduces effort to design new APIs.
o Encourages & Fosters software reuse.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
5. What is the List interface?
The List interface provides support for ordered collections of objects. Ex: ArrayList
6. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects that is synchronzied and thread-safe.
7. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection one by one. It is an easier way to loop through the contents of a collection when you do not know, how many objects are present in it. Also, it is a cleaner way to access the contents of a collection when compared to using a for loop and accessing entries using get(index) method.
Remember that, when using Iterators they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
8. What is the Map interface?
A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot.
9. What is the Collection interface?
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
10. What is the Set interface?
• The Set interface provides methods for accessing the elements of a finite mathematical set
• Sets do not allow duplicate elements
• Contains no methods other than those inherited from Collection
• It adds the restriction that duplicate elements are prohibited
• Two Set objects are equal if they contain the same elements
11. What are different types of collections?
* A regular collection has no special order and does not reject duplicates
* A list is ordered and does not reject duplicates
* A set has no special order but rejects duplicates
* A map supports storing data as key-value pairs
12. Difference between Hashtable and HashMap?
* Hashtable does not store null value, while HashMap does
* Hashtable is synchronized, while HashMap is not
* Hashtables are slower because of the synchronization overhead while HashMaps are faster
13.What are the main Implementations of the Set interface ?
The main implementations of the List interface are as follows:
HashSet
TreeSet
LinkedHashSet
EnumSet
14.What is a HashSet ?
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted to access the object. So, the more efficient your hashcode() implementation the better access performance you’ll get. Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.
15.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.
16.Difference between HashSet and TreeSet ?
HashSet does not store data in any Order while the TreeSet stores data in order. Also, you can elements of any type to the hash set while you can only add similar types of elements into a tree set.
17.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
HashMap
HashTable
TreeMap
EnumMap
18.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
19.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
20. Can I store multiple keys or values that are null in a HashMap?
You can store only one key that has a value null. But, as long as your keys are unique, you can store as many nulls as you want in an HashMap
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Collections that you have faced during your interviews and wish to add them to this collection - pls drop a note to anandvijayakumar007@gmail.com and I shall be glad to add them to this list.
Strings Interview Questions
The following are some questions you might encounter with respect to Strings in any Java Interview. Strings are very powerful and frankly speaking, there can be no Java based application that does not use Strings.
Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Strings that you might find useful. You can use them to revise/review your understanding of Strings.
They are:
Java String Class
StringBuffer & StringBuilder
Questions:
1. What would you use to compare two String variables - the operator == or the equals() method?
I would personally prefer/use the equals() method to compare two Strings if I want to check the value of the Strings and the == operator if I want to check if the two variables point to the same instance of the String object.
2. For concatenation of strings, which method is good, StringBuffer or String ?
StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings.
3. As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation?
As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.
4. To what value is a variable of the String type automatically initialized?
The default value of String variable is null.
5. What is the difference between the String and StringBuffer classes?
String objects are constants or in other words immutable while StringBuffer objects are not.
6. What happens when you add a double value to a String?
The result is a String object. For that matter, if you add anything to a String, you will end up with a String.
7. What will be the result if you compare StringBuffer with String if both have same values?
It will return false as you cannot compare String with StringBuffer directly. If you really want to compare the contents of the String & the StringBuffer you would have to invoke the equals method with the String and the toString() output of the StringBuffer.
8. What is difference between String, StringBuffer and StringBuilder? When to use them?
For all practical understanding purposes, all these 3 classes are used to handle/manipulate Strings. The main difference between these 3 classes is:
* Strings are immutable while StringBuffer & StringBuilder objects are mutable (can be modified)
* StringBuffer is synchronized (thread safe) while StringBuilder is not.
9. When to use Strings or StringBuffer or StringBuilder? What will drive this decision?
The type of objects you need to create and how they will be used will drive this decision. So,
* If the object value is not going to change, use the String class
* If the object value will be changed frequently we must choose either the StringBuffer or the StringBuilder.
* Here, if your object will be accessed only by a single thread use StringBuilder because it is faster
* If your object may be accessed my multiple threads use the StringBuffer because it is thread safe
Note: Thread safety is not free and comes at the expense of performance. So, if your system is not multi-threaded then use the StringBuilder which will be much faster than the StringBuffer.
10. Why String class is final or immutable?
The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason.
If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different.
Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it?
MyString str1 = "Rocky";
YourString str2 = "Rocky";
This is why String class is final.
Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Strings that you might find useful. You can use them to revise/review your understanding of Strings.
They are:
Java String Class
StringBuffer & StringBuilder
Questions:
1. What would you use to compare two String variables - the operator == or the equals() method?
I would personally prefer/use the equals() method to compare two Strings if I want to check the value of the Strings and the == operator if I want to check if the two variables point to the same instance of the String object.
2. For concatenation of strings, which method is good, StringBuffer or String ?
StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings.
3. As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation?
As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.
4. To what value is a variable of the String type automatically initialized?
The default value of String variable is null.
5. What is the difference between the String and StringBuffer classes?
String objects are constants or in other words immutable while StringBuffer objects are not.
6. What happens when you add a double value to a String?
The result is a String object. For that matter, if you add anything to a String, you will end up with a String.
7. What will be the result if you compare StringBuffer with String if both have same values?
It will return false as you cannot compare String with StringBuffer directly. If you really want to compare the contents of the String & the StringBuffer you would have to invoke the equals method with the String and the toString() output of the StringBuffer.
8. What is difference between String, StringBuffer and StringBuilder? When to use them?
For all practical understanding purposes, all these 3 classes are used to handle/manipulate Strings. The main difference between these 3 classes is:
* Strings are immutable while StringBuffer & StringBuilder objects are mutable (can be modified)
* StringBuffer is synchronized (thread safe) while StringBuilder is not.
9. When to use Strings or StringBuffer or StringBuilder? What will drive this decision?
The type of objects you need to create and how they will be used will drive this decision. So,
* If the object value is not going to change, use the String class
* If the object value will be changed frequently we must choose either the StringBuffer or the StringBuilder.
* Here, if your object will be accessed only by a single thread use StringBuilder because it is faster
* If your object may be accessed my multiple threads use the StringBuffer because it is thread safe
Note: Thread safety is not free and comes at the expense of performance. So, if your system is not multi-threaded then use the StringBuilder which will be much faster than the StringBuffer.
10. Why String class is final or immutable?
The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason.
If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different.
Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it?
MyString str1 = "Rocky";
YourString str2 = "Rocky";
This is why String class is final.
Serialization
1. Explain the usage of the keyword transient?
The transient keyword indicates that the value of this variable need not be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (ex: 0 for integers).
2. What are the uses of Serialization?
Serialization is widely used to:
* To persist data for future use.
* To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
* To "flatten" an object into array of bytes in memory.
* To exchange data between applets and servlets.
* To store user session in Web applications.
* To activate/passivate enterprise java beans.
* To send objects between the servers in a cluster.
3. What is serialization ?
Serialization is the process of writing the complete state of java object into an output stream. This stream can be file or byte array or stream associated with a TCP/IP socket.
4. What does the Serializable interface do ?
Serializable is a tagging interface which declares/describes no methods. It is just used to signify the fact that, the current class can be serialized. ObjectOutputStream serializes only those objects which implement this interface.
5. How do I serialize an object to a file ?
To serialize an object into a stream perform the following steps:
1. Open one of the output streams, for exaample FileOutputStream
2. Chain it with the ObjectOutputStream - Call the method writeObject() providing the instance of a Serializable object as an argument.
3. Close the streams
6. How do I deserilaize an Object?
To deserialize an object, perform the following steps:
1. Open an input stream
2. Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned object to the class that is being deserialized.
3. Close the streams
7. What is Externalizable Interface ?
Externalizable interface is a subclass of Serializable. Java provides Externalizable interface so as to give you more control over what is being serialized and what is not. Using this interface, you can Serialize only the fields of the class you want serialize and ignore the rest.
This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you'll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.
8. What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
9. What are the rules of serialization
Some rules of Serialization are:
1. Static fileds are not serialized because they are not part of any one particular object
2. Fileds from the base class are handled only if the parent class itself is serializable
3. Transient fileds are not serialized
The transient keyword indicates that the value of this variable need not be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (ex: 0 for integers).
2. What are the uses of Serialization?
Serialization is widely used to:
* To persist data for future use.
* To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
* To "flatten" an object into array of bytes in memory.
* To exchange data between applets and servlets.
* To store user session in Web applications.
* To activate/passivate enterprise java beans.
* To send objects between the servers in a cluster.
3. What is serialization ?
Serialization is the process of writing the complete state of java object into an output stream. This stream can be file or byte array or stream associated with a TCP/IP socket.
4. What does the Serializable interface do ?
Serializable is a tagging interface which declares/describes no methods. It is just used to signify the fact that, the current class can be serialized. ObjectOutputStream serializes only those objects which implement this interface.
5. How do I serialize an object to a file ?
To serialize an object into a stream perform the following steps:
1. Open one of the output streams, for exaample FileOutputStream
2. Chain it with the ObjectOutputStream - Call the method writeObject() providing the instance of a Serializable object as an argument.
3. Close the streams
6. How do I deserilaize an Object?
To deserialize an object, perform the following steps:
1. Open an input stream
2. Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned object to the class that is being deserialized.
3. Close the streams
7. What is Externalizable Interface ?
Externalizable interface is a subclass of Serializable. Java provides Externalizable interface so as to give you more control over what is being serialized and what is not. Using this interface, you can Serialize only the fields of the class you want serialize and ignore the rest.
This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you'll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.
8. What interface must an object implement before it can be written to a stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
9. What are the rules of serialization
Some rules of Serialization are:
1. Static fileds are not serialized because they are not part of any one particular object
2. Fileds from the base class are handled only if the parent class itself is serializable
3. Transient fileds are not serialized
Core Java Interview Questions - Classes & Interfaces
1. What's the difference between an interface and an abstract class?
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.
2. Can an inner class declared inside of a method access local variables of this method?
Yes, it is possible if the variables are declared as final.
3. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option because Java does not support multiple inheritance.
4. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level. A class with default access will be accessible only to other classes that are declared in the same directory/package.
5. When you declare a method as abstract method ?
We declare a method as abstract, When we want child class to implement the behavior of the method.
6. Can I call a abstract method from a non abstract method ?
Yes, We can call a abstract method from a Non abstract method in a Java abstract class
7. What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ?
Abstract classes let you define some behavior while forcing your subclasses to provide the rest. These abstract classes will provide the basic funcationality of your application, child class which inherit this class will provide the funtionality of the abstract methods in abstract class.
Whereas, An Interface can only declare constants and instance methods, but cannot implement any default behavior.
If you want your class to extend some other class but at the same time re-use some features outlined in a parent class/interface - Interfaces are your only option because Java does not allow multiple inheritance and once you extend an abstract class, you cannot extend any other class. But, if you implement an interface, you are free to extend any other concrete class as per your wish.
Also, Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.
8. What are different types of inner classes ?
Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes are of four types
1. Static member classes
2. Member classes
3. Local classes
4. Anonymous classes
9. What are the field/method access levels (specifiers) and class access levels ?
Each field and method has an access level corresponding to it:
private: accessible only in this class
package: accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available
Similarly, each class has one of two possible access levels:
package: class objects can only be declared and manipulated by code in this package
public: class objects can be declared and manipulated by code in any package
10. 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.
11. 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.
12. What must a class do to implement an interface?
It must provide implementation to all of the methods in the interface and identify the interface in its implements clause in the class declaration line of code.
13. 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.
14. 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.
15. 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 default or package level access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
16. 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.
17. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.
18. Is a class a subclass of itself?
Yes, a class is a subclass of itself.
19. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
20. Can an abstract class be final?
An abstract class may not be declared as final. Abstract and Final are two keywords that carry totally opposite meanings and they cannot be used together.
21. 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.
22. What modifiers may be used with a top-level class?
A top-level class may be public, abstract, or final.
23. 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.
24. Can you make an instance of abstract class
No you cannot create an instance of abstract class. If you use new keyword to instantiate an abstract class, you will get a compilation error.
25. Describe what happens when an object is created in Java
Several things happen in a particular order to ensure the object is created properly:
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the
object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the
consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
26. What is the purpose of System Class
The purpose of the system class is to provide the access to the System reources
27. What is instanceOf operator used for
It is used to check if an object can be cast into a specific type without throwing Class cast exception
28. Why we should not have instance variable in an interface?
Since all data fields and methods in an Interface are public by default, when we implement that interface in our class, we have public members in our class and this class will expose these data members and this is violation of encapsulation as now the data is not secure
29. What is a singleton class
A singleton is an object that cannot be instantiated more than once. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy. We accomplish this by declaring the constructor private and having a public static instance variable of the class's type that can be accessed using a getInstance() method in the class.
30. Can an abstract class have final method
Yes, you can have a final method in an Abstract class.
31. Can a final class have an abstract method
No, a Final class cannot have an Abstract method.
32. When does the compiler insist that the class must be abstract
The compiler insists that your class be made abstract under the following circumstances:
1. If one or more methods of the class are abstract.
2. If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
3. If class implements an interface and provides no implementation for some methods
33. How is abstract class different from final class
Abstract class must be subclassed and an implementation has to be provided by the child class whereas final class cannot be subclassed
34. What is an inner class
An inner class is same as any other class, just that, is declared inside some other class
35. How will you reference the inner class
To reference an inner class you will have to use the following syntax: OuterClass$InnerClass
36. Can objects that are instances of inner class access the members of the outer class
Yes they can access the members of the outer class
37. Can inner classes be static
Yes inner classes can be static, but they cannot access the non static data of the outer classes, though they can access the static data
38. Can an inner class be defined inside a method
Yes it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final
39. What is an anonymous class
Some classes defined inside a method do not need a name, such classes are called anonymous classes
40. What are access modifiers
These public, protected and private, these can be applied to class, variables, constructors and methods. But if you don't specify an access modifier then it is considered as Friendly. They determine the accessibility or visibility of the entities to which they are applied.
41. Can protected or friendly features be accessed from different packages
No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package
42. How can you access protected features from another package
You can access protected features from other classes by subclassing the that class in another package, but this cannot be done for friendly features
An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.
2. Can an inner class declared inside of a method access local variables of this method?
Yes, it is possible if the variables are declared as final.
3. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option because Java does not support multiple inheritance.
4. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level. A class with default access will be accessible only to other classes that are declared in the same directory/package.
5. When you declare a method as abstract method ?
We declare a method as abstract, When we want child class to implement the behavior of the method.
6. Can I call a abstract method from a non abstract method ?
Yes, We can call a abstract method from a Non abstract method in a Java abstract class
7. What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ?
Abstract classes let you define some behavior while forcing your subclasses to provide the rest. These abstract classes will provide the basic funcationality of your application, child class which inherit this class will provide the funtionality of the abstract methods in abstract class.
Whereas, An Interface can only declare constants and instance methods, but cannot implement any default behavior.
If you want your class to extend some other class but at the same time re-use some features outlined in a parent class/interface - Interfaces are your only option because Java does not allow multiple inheritance and once you extend an abstract class, you cannot extend any other class. But, if you implement an interface, you are free to extend any other concrete class as per your wish.
Also, Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.
8. What are different types of inner classes ?
Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes are of four types
1. Static member classes
2. Member classes
3. Local classes
4. Anonymous classes
9. What are the field/method access levels (specifiers) and class access levels ?
Each field and method has an access level corresponding to it:
private: accessible only in this class
package: accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available
Similarly, each class has one of two possible access levels:
package: class objects can only be declared and manipulated by code in this package
public: class objects can be declared and manipulated by code in any package
10. 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.
11. 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.
12. What must a class do to implement an interface?
It must provide implementation to all of the methods in the interface and identify the interface in its implements clause in the class declaration line of code.
13. 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.
14. 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.
15. 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 default or package level access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
16. 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.
17. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.
18. Is a class a subclass of itself?
Yes, a class is a subclass of itself.
19. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
20. Can an abstract class be final?
An abstract class may not be declared as final. Abstract and Final are two keywords that carry totally opposite meanings and they cannot be used together.
21. 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.
22. What modifiers may be used with a top-level class?
A top-level class may be public, abstract, or final.
23. 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.
24. Can you make an instance of abstract class
No you cannot create an instance of abstract class. If you use new keyword to instantiate an abstract class, you will get a compilation error.
25. Describe what happens when an object is created in Java
Several things happen in a particular order to ensure the object is created properly:
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the
object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the
consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
26. What is the purpose of System Class
The purpose of the system class is to provide the access to the System reources
27. What is instanceOf operator used for
It is used to check if an object can be cast into a specific type without throwing Class cast exception
28. Why we should not have instance variable in an interface?
Since all data fields and methods in an Interface are public by default, when we implement that interface in our class, we have public members in our class and this class will expose these data members and this is violation of encapsulation as now the data is not secure
29. What is a singleton class
A singleton is an object that cannot be instantiated more than once. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy. We accomplish this by declaring the constructor private and having a public static instance variable of the class's type that can be accessed using a getInstance() method in the class.
30. Can an abstract class have final method
Yes, you can have a final method in an Abstract class.
31. Can a final class have an abstract method
No, a Final class cannot have an Abstract method.
32. When does the compiler insist that the class must be abstract
The compiler insists that your class be made abstract under the following circumstances:
1. If one or more methods of the class are abstract.
2. If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
3. If class implements an interface and provides no implementation for some methods
33. How is abstract class different from final class
Abstract class must be subclassed and an implementation has to be provided by the child class whereas final class cannot be subclassed
34. What is an inner class
An inner class is same as any other class, just that, is declared inside some other class
35. How will you reference the inner class
To reference an inner class you will have to use the following syntax: OuterClass$InnerClass
36. Can objects that are instances of inner class access the members of the outer class
Yes they can access the members of the outer class
37. Can inner classes be static
Yes inner classes can be static, but they cannot access the non static data of the outer classes, though they can access the static data
38. Can an inner class be defined inside a method
Yes it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final
39. What is an anonymous class
Some classes defined inside a method do not need a name, such classes are called anonymous classes
40. What are access modifiers
These public, protected and private, these can be applied to class, variables, constructors and methods. But if you don't specify an access modifier then it is considered as Friendly. They determine the accessibility or visibility of the entities to which they are applied.
41. Can protected or friendly features be accessed from different packages
No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package
42. How can you access protected features from another package
You can access protected features from other classes by subclassing the that class in another package, but this cannot be done for friendly features
Core Java Interview Questions - Exception handling
Exception Handling
1. How could Java classes direct messages to a file instead of the Console?
The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both point at the system console.
The standard output could be re-directed to a file as follows:
Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);
2. Does it matter in what order catch statements for FileNotFoundException and IOException are written?
Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last.
3. What is user-defined exception in java ?
User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions.
4. What is the difference between checked and Unchecked Exceptions in Java ?
Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions.
5. 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 that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method.
6. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception.
7. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
8. Can an exception be rethrown?
Yes, an exception can be rethrown any number of times.
9. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
10. 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.
11. 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.
12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown 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's termination.
13. Can try statements be nested?
Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max.
14. 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 are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored.
15. What is difference between error and exception
Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions
16. What is the base class from which all exceptions are subclasses
All exceptions are subclasses of a class called java.lang.Throwable
17. How do you intercept and control exceptions
We can intercept and control exceptions by using try/catch/finally blocks.
You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block
18. When do we say an exception is handled
When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled.
19. When do we say an exception is not handled
There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed
20. In what sequence does the finally block gets executed
If you put finally after a try block without a matching catch block then it will be executed after the try block
If it is placed after the catch block and there is no exception then also it will be executed after the try block
If there is an exception and it is handled by the catch block then it will be executed after the catch block
21. What can prevent the execution of the code in finally block
Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block.
* The death of thread
* Use of system.exit()
* Turning off the power to CPU
* An exception arising in the finally block itself
22. What are the rules for catching multiple exceptions?
A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks.
23. What does throws statement declaration in a method indicate?
This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block.
24. What are checked exceptions?
Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen.
25. What are runtime exceptions
Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions.
26. What is difference between Exception and errors
Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors.
27. How will you handle the checked exceptions
You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it.
28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method?
No it cannot throw, except for the subclasses of the exceptions thrown by the parent class's method.
29. Is it legal for the extending class which overrides a method which throws an exception, not to throw in the overridden class?
Yes, it is perfectly legal
1. How could Java classes direct messages to a file instead of the Console?
The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both point at the system console.
The standard output could be re-directed to a file as follows:
Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);
2. Does it matter in what order catch statements for FileNotFoundException and IOException are written?
Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last.
3. What is user-defined exception in java ?
User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions.
4. What is the difference between checked and Unchecked Exceptions in Java ?
Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions.
5. 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 that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method.
6. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception.
7. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
8. Can an exception be rethrown?
Yes, an exception can be rethrown any number of times.
9. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
10. 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.
11. 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.
12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown 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's termination.
13. Can try statements be nested?
Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max.
14. 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 are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored.
15. What is difference between error and exception
Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions
16. What is the base class from which all exceptions are subclasses
All exceptions are subclasses of a class called java.lang.Throwable
17. How do you intercept and control exceptions
We can intercept and control exceptions by using try/catch/finally blocks.
You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block
18. When do we say an exception is handled
When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled.
19. When do we say an exception is not handled
There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed
20. In what sequence does the finally block gets executed
If you put finally after a try block without a matching catch block then it will be executed after the try block
If it is placed after the catch block and there is no exception then also it will be executed after the try block
If there is an exception and it is handled by the catch block then it will be executed after the catch block
21. What can prevent the execution of the code in finally block
Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block.
* The death of thread
* Use of system.exit()
* Turning off the power to CPU
* An exception arising in the finally block itself
22. What are the rules for catching multiple exceptions?
A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks.
23. What does throws statement declaration in a method indicate?
This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block.
24. What are checked exceptions?
Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen.
25. What are runtime exceptions
Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions.
26. What is difference between Exception and errors
Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors.
27. How will you handle the checked exceptions
You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it.
28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method?
No it cannot throw, except for the subclasses of the exceptions thrown by the parent class's method.
29. Is it legal for the extending class which overrides a method which throws an exception, not to throw in the overridden class?
Yes, it is perfectly legal
Struts Interview Questions
1. What is Struts framework?
Struts framework is an open-source framework use for developing the web applications in Java EE, based on the MVC-2 architecture. It uses and extends the Java Servlet API. Struts is a robust architecture and can be used for the development of applications of any size. Struts framework makes it much easier to design scalable and reliable Web applications with Java.
2. What design patterns are used in Struts?
Struts is based on model 2 MVC (Model-View-Controller) architecture.
Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern.
Struts also implement the following J2EE design patterns.
a. Service to Worker
b. Dispatcher View
c. Composite View (Struts Tiles)
d. Front Controller
e. View Helper
f. Synchronizer Token
An important point to note here is that, not all of these patterns may be used in every Struts based application and you may not require to remember all of these patterns. If you know that Struts is based on the MVC Framework, that is more than sufficient.
3. What is the MVC Framework?
MVC Stands for Model View Controller Framework
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.
Model - The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View - The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
Controller - The controller reacts to the user input. It creates and sets the model.
4. What are the components of a Struts based application?
Struts components can be categorize into Model, View and Controller:
Model - Components like business logic /business processes and data are the part of model.
View - HTML, JSP are the view components.
Controller - Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.
5. What is the ActionServlet?
The ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request.
It serves as an Action factory – creating specific Action classes based on user’s request.
6. What is the role of an ActionServlet?
ActionServlet performs the role of Controller. It does the following:
a. Process user requests
b. Determine what the user is trying to achieve according to the request
c. Pull data from the model (if necessary) to be given to the appropriate view,
d. Select the proper view to respond to the user
e. Delegates most of this grunt work to Action classes
f. Is responsible for initialization and clean-up of resources
7. What is the ActionForm?
ActionForm is a javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.
8. What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().
9. Describe the validate() and reset() methods of the ActionForm?
The validate() method is used to validate properties after they have been populated (In the JSP). It is called before FormBean is handed over to the Action. It returns a collection of ActionError objects as ActionErrors. Following is the method signature for the validate() method.
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)
The reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set. Following is the method signature of the reset() method.
public void reset() {}
10. What is ActionMapping?
The Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is over.
For ex: You enter your credentials in the login page of your bank's internet banking website and then hit the "Login" button. How would the system know what to do next? It refers to the ActionMappings to find out what to do next based on the action chosen by the user.
11. How is the Action Mapping specified ?
We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from
< action-mappings >
< action path="/submit" type="submit.SubmitAction" name="submitForm" input="/submit.jsp" scope="request" validate="true" >
< forward name="success" path="/success.jsp" / >
< forward name="failure" path="/error.jsp" / >
< / action >
< / action-mappings >
12. What is role of Action Class?
An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.
Practically speaking, this class contains all the logic of what to do in response to the user action. Remember the login to banks website example I gave a couple of questions back, the system actually goes to the Action class corresponding to your action (Login) to try to figure out what needs to be done next.
13. In which method of Action class the business logic is executed ?
In the execute() method of Action class the business logic is executed. It performs the processing required to deal with this request, updates the server-side objects (Scope variables) that will be used to create the next page of the user interface and returns an appropriate ActionForward object
14. Can you give me a sample code for this execute method's Signature?
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;
15. Can we have more than one struts-config.xml file for a single Struts application?
A lot of people think that having multiple struts config files isnt possible for a single application but the truth is, it is very well possible. Unfortunately, in most real life scenarios, we would be using only one struts config file even though we can have many.
16. How would you configure your application to have multiple struts config files?
They can be configured as follows in your web.xml file:
< servlet >
< servlet-name > action < / servlet-name >
< servlet-class >
org.apache.struts.action.ActionServlet
< / servlet-class >
< init-param >
< param-name > config < / param-name > < param-value > /WEB-INF/struts-config.xml, /WEB-INF/struts-admin.xml, /WEB-INF/struts-config-forms.xml < / param-value > < / init-param >
.....
< servlet >
17. What is the difference between session scope and request scope when saving the formbean in struts?
When the scope is request,the values of formbean would be available for the current request. Whereas, when the scope is session, the values of formbean would be available throughout the session.
18. What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
ForwardAction
IncludeAction
DispatchAction
LookupDispatchAction
SwitchAction
19. What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.
20. How will you use the DispatchAction?
To use the DispatchAction, follow these steps :
1. Create a class that extends DispatchAction (instead of Action)
2. In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
3. Do not override execute() method – Because DispatchAction class itself provides execute() method.
4. Add an entry to struts-config.xml
21. When would you use the ForwardAction?
The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.
22. When would you use the IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.
23. What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.
24. What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.
25. When would you use LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. This is typically useful when you create something that will be shared across different locales. For ex: The login page of an international banks website would look surprisingly similar in almost all countries. It does the same thing in all countries but what exactly happens after you finish the login depends on the country you are. So, this is the kind if scenario where LookupDispatchAction would come in handy.
26. What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.
27. What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application.
28. What if
element has
declaration with same name as global forward? In this case the global forward is not used. Instead the
element’s
takes precendence.29. What is DynaActionForm?
DynaActionForm is a specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean. Since the developer need not create actual bean java classes, a lot of developers prefer DynaActionForms.
30. What are the steps need to use DynaActionForm?
Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:
First in the struts-config.xml: change your
to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm. Example:
< form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >
< form-property name="userName" type="java.lang.String" / >
< form-property name="password" type="java.lang.String" / >
< / form-bean >
Second - In your Action subclass that uses your form bean:
1. import org.apache.struts.action.DynaActionForm
2. downcast the ActionForm parameter in execute() to a DynaActionForm
3. access the form fields with get(field) rather than getField()
Example:
......
public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
"error.userName.required"));
}
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(
"error.password.required"));
}
...........
31. How would you display validation errors on jsp page in a Struts Application?
tag displays all the errors.
iterates over ActionErrors request attribute. Remember the ActionErrors that get created while using the validate() method? See Question No. 9 if you dont remember... 32. What are the various Struts tag libraries?
The various Struts tag libraries are:
1. HTML Tags
2. Bean Tags
3. Logic Tags
4. Template Tags
5. Nested Tags
6. Tiles Tags
33. What is the use of
?
repeats the nested body content of this tag over a specified collection.example:
< table border=1 >
< logic:iterate id="customer" name="customers" >
< tr >
< td > < bean:write name="customer" property="firstName" / > < / td >
< td > < bean:write name="customer" property="lastName" / > < / td >
< td > < bean:write name="customer" property="address" / > < / td>
< / tr >
< / logic:iterate >
< / table>
34. What are differences between
< bean:message >
and < bean:write >
? < bean:message >
: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.
< bean:message key="prompt.customer.firstname" / >
< bean:write >
: is used to retrieve and print the value of the bean property. < bean:write > has no body.
< bean:write name="customer" property="firstName" / >
35. How the exceptions are handled in struts?
Exceptions in Struts are handled in two ways:
1. Programmatic exception handling - Using explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.
2. Declarative exception handling - You can either define
36. Can you give an example of Programmatic Exception Handling?
< global-exceptions >
< exception key="some.key" type="java.lang.NullPointerException" path="/WEB-INF/errors/null.jsp" / >
< / global-exceptions >
37. Can you give an example of declarative exception handling?
< exception key="some.key" type="package.SomeException" path="/WEB-INF/somepage.jsp" / >
38. What are some benefits of using DynaActionForm?
The biggest advantage is that - we need not create multiple classes to hold form information. We can just declare forms as and when required inside the struts-config.xml file and we are good to go.
39. Can you think of any drawbacks of the DynaActionForm?
Of Course. Every coin has two sides. Some drawbacks of using DynaActionForm could be:
1. The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger and the config file in itself could become unmanageable
2. The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
3. ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
40. How can we make message resources definitions file available to the Struts framework environment?
We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to struts-config.xml.
< message-resources parameter="com.login.struts.ApplicationResources" />
Hibernate Interview Questions
Does Hibernate implement its functionality using a minimal number of database queries to ensure optimal output?
Hibernate can make certain optimizations all the time:
• Caching objects - The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk.
• Executing SQL statements later, when needed - The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end).
• Never updating unmodified objects - It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
• Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
• Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
• Updating only the modified columns - Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
• Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
• Lazy collection initialization
• Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception injected through byte code instrumentation at build-time.
2. Why not implement instance-pooling in Hibernate?
Firstly, it would be pointless. There is a lower bound to the amount of garbage Hibernate creates every time it loads or updates and object - the garbage created by getting or setting the object's properties using reflection.
More importantly, the disadvantage of instance-pooling is developers who forget to reinitialize fields each time an instance is reused. We have seen very subtle bugs in EJBs that don't reinitialize all fields in ejbCreate.
On the other hand, if there is a particular application object that is extremely expensive to create, you can easily implement your own instance pool for that class and use the version of Session.load() that takes a class instance. Just remember to return the objects to the pool every time you close the session.
3. Does Hibernate use runtime reflection?
Many former C or C++ programmers prefer generated-code solutions to runtime reflection. This is usually justified by reference to the performance red-herring. However, modern JVMs implement reflection extremely efficiently and the overhead is minimal compared to the cost of disk access or IPC. Developers from other traditions (e.g. Smalltalk) have always relied upon reflection to do things that C/C++ needs code-generation for.
In the very latest versions of Hibernate, "reflection" is optimised via the CGLIB runtime byte code generation library. This means that "reflected" property get / set calls no longer carry the overhead of the Java reflection API and are actually just normal method calls. This results in a (very) small performance gain.
4. How do I use Hibernate in an EJB 2.1 session bean?
1. Look up the SessionFactory in JNDI.
2. Call getCurrentSession() to get a Session for the current transaction.
3. Do your work.
4. Don't commit or close anything, let the container manage the transaction.
5. What’s the easiest way to configure Hibernate in a plain Java application (without using JNDI)?
Build a SessionFactory from a Configuration object.
6. What is Middlegen?
Middlegen is an open source code generation framework that provides a general-purpose database-driven engine using various tools such as JDBC, Velocity, Ant and XDoclet.
7. How can I count the number of query results without actually returning them?
Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
8. How can I find the size of a collection without initializing it?
Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();
9. How can I order by the size of a collection?
Use a left join, together with group by
select user
from User user
left join user.messages msg
group by user
order by count(msg)
10. How can I place a condition upon a collection size?
If your database supports subselects:
from User user where size(user.messages) >= 1
or:
from User user where exists elements(user.messages)
If not, and in the case of a one-to-many or many-to-many association:
select user
from User user
join user.messages msg
group by user
having count(msg) >= 1
Because of the inner join, this form can't be used to return a User with zero messages, so the following form is also useful
select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0
11. How can I query for entities with empty collections?
from Box box
where box.balls is empty
Or, try this:
select box
from Box box
left join box.balls ball
where ball is null
12. How can I sort / order collection elements?
There are three different approaches:
1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or < set > or < map >. This solution does a sort in memory.
2. Specify an order-by attribute of < set >, < map > or < bag >, naming a list of table columns to sort by. This solution works only in JDK 1.4+.
3. Use a filter session.createFilter( collection, "order by ...." ).list()
13. Are collections pageable?
Query q = s.createFilter( collection, "" );
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();
I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bug-prone. Is there a better way?
< generator class="foreign" >
< param name="property" > parent < / param >
< / generator >
I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use?
Use a composite-element to model the association table. For example, given the following association table:
create table relationship (
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )
you could use this collection mapping (inside the mapping for class Foo):
< set name="relationship" >
< key column="fk_of_foo" / >
< composite-element class="Relationship" >
< property name="multiplicity" type="short" not-null="true" / >
< property name="created" type="date" not-null="true" / >
< many-to-one name="bar" class="Bar" not-null="true" / >
< / composite-element >
< / set >
You may also use anwith a surrogate key column for the collection table. This would allow you to have nullable columns.
An alternative approach is to simply map the association table as a normal entity class with two bidirectional one-to-many associations.
In an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a Servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.
Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.
14. How can I bind a dynamic list of values into an in query expression?
Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)");
q.setParameterList("id_list", fooIdList);
List foos = q.list();
15. How can I bind properties of a JavaBean to named query parameters?
Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();
16. Can I map an inner class?
You may persist any static inner class. You should specify the class name using the standard form i.e. eg.Foo$Bar
17. How can I assign a default value to a property when the database column is null?
Use a UserType.
18. How can I truncate String data?
Use a UserType.
19. How can I trim spaces from String data persisted to a CHAR column?
Use a UserType.
20. How can I convert the type of a property to/from the database column type?
Use a UserType.
21. How can I get access to O/R mapping information such as table and column names at runtime?
This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.
22. How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?
If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT statement:
Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);
23. How can I retrieve the identifier of an associated object, without fetching the association?
Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.
Long itemId = bid.getItem().getId();
This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called.
24. How can I manipulate mappings at runtime?
You can access (and modify) the Hibernate metamodel via the Configuration object, using getClassMapping(), getCollectionMapping(), etc.
Note that the SessionFactory is immutable and does not retain any reference to the Configuration instance, so you must re-build it if you wish to activate the modified mappings.
25. How can I avoid n+1 SQL SELECT queries when running a Hibernate query?
Follow the best practices guide! Ensure that alland mappings specify lazy="true" in Hibernate2 (this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations you need to be retrieved in the initial SQL SELECT.
A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3.
If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.
I have a collection with second-level cache enabled, and Hibernate retrieves the collection elements one at a time with a SQL query per element!
Enable second-level cache for the associated entity class. Don't cache collections of uncached entity types.
26. How can I insert XML data into Oracle using the xmltype() function?
Specify custom SQL INSERT (and UPDATE) statements usingand in Hibernate3, or using a custom persister in Hibernate 2.1.
You will also need to write a UserType to perform binding to/from the PreparedStatement.
27. How can I execute arbitrary SQL using Hibernate?
PreparedStatement ps = session.connection().prepareStatement(sqlString);
Or, if you wish to retrieve managed entity objects, use session.createSQLQuery().
Or, in Hibernate3, override generated SQL using, , and in the mapping document.
I want to call an SQL function from HQL, but the HQL parser does not recognize it!
Subclass your Dialect, and call registerFunction() from the constructor.
28. Why to use HQL?
• Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.
• Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This eliminates the need of creating the object and populate the data from result set.
• Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.
• Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.
• Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
• Database independent: Queries written in HQL are database independent (If database supports the underlying feature).
Hibernate can make certain optimizations all the time:
• Caching objects - The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk.
• Executing SQL statements later, when needed - The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end).
• Never updating unmodified objects - It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
• Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
• Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
• Updating only the modified columns - Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
• Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
• Lazy collection initialization
• Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception injected through byte code instrumentation at build-time.
2. Why not implement instance-pooling in Hibernate?
Firstly, it would be pointless. There is a lower bound to the amount of garbage Hibernate creates every time it loads or updates and object - the garbage created by getting or setting the object's properties using reflection.
More importantly, the disadvantage of instance-pooling is developers who forget to reinitialize fields each time an instance is reused. We have seen very subtle bugs in EJBs that don't reinitialize all fields in ejbCreate.
On the other hand, if there is a particular application object that is extremely expensive to create, you can easily implement your own instance pool for that class and use the version of Session.load() that takes a class instance. Just remember to return the objects to the pool every time you close the session.
3. Does Hibernate use runtime reflection?
Many former C or C++ programmers prefer generated-code solutions to runtime reflection. This is usually justified by reference to the performance red-herring. However, modern JVMs implement reflection extremely efficiently and the overhead is minimal compared to the cost of disk access or IPC. Developers from other traditions (e.g. Smalltalk) have always relied upon reflection to do things that C/C++ needs code-generation for.
In the very latest versions of Hibernate, "reflection" is optimised via the CGLIB runtime byte code generation library. This means that "reflected" property get / set calls no longer carry the overhead of the Java reflection API and are actually just normal method calls. This results in a (very) small performance gain.
4. How do I use Hibernate in an EJB 2.1 session bean?
1. Look up the SessionFactory in JNDI.
2. Call getCurrentSession() to get a Session for the current transaction.
3. Do your work.
4. Don't commit or close anything, let the container manage the transaction.
5. What’s the easiest way to configure Hibernate in a plain Java application (without using JNDI)?
Build a SessionFactory from a Configuration object.
6. What is Middlegen?
Middlegen is an open source code generation framework that provides a general-purpose database-driven engine using various tools such as JDBC, Velocity, Ant and XDoclet.
7. How can I count the number of query results without actually returning them?
Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
8. How can I find the size of a collection without initializing it?
Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();
9. How can I order by the size of a collection?
Use a left join, together with group by
select user
from User user
left join user.messages msg
group by user
order by count(msg)
10. How can I place a condition upon a collection size?
If your database supports subselects:
from User user where size(user.messages) >= 1
or:
from User user where exists elements(user.messages)
If not, and in the case of a one-to-many or many-to-many association:
select user
from User user
join user.messages msg
group by user
having count(msg) >= 1
Because of the inner join, this form can't be used to return a User with zero messages, so the following form is also useful
select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0
11. How can I query for entities with empty collections?
from Box box
where box.balls is empty
Or, try this:
select box
from Box box
left join box.balls ball
where ball is null
12. How can I sort / order collection elements?
There are three different approaches:
1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or < set > or < map >. This solution does a sort in memory.
2. Specify an order-by attribute of < set >, < map > or < bag >, naming a list of table columns to sort by. This solution works only in JDK 1.4+.
3. Use a filter session.createFilter( collection, "order by ...." ).list()
13. Are collections pageable?
Query q = s.createFilter( collection, "" );
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();
I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bug-prone. Is there a better way?
< generator class="foreign" >
< param name="property" > parent < / param >
< / generator >
I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use?
Use a composite-element to model the association table. For example, given the following association table:
create table relationship (
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )
you could use this collection mapping (inside the mapping for class Foo):
< set name="relationship" >
< key column="fk_of_foo" / >
< composite-element class="Relationship" >
< property name="multiplicity" type="short" not-null="true" / >
< property name="created" type="date" not-null="true" / >
< many-to-one name="bar" class="Bar" not-null="true" / >
< / composite-element >
< / set >
You may also use an
An alternative approach is to simply map the association table as a normal entity class with two bidirectional one-to-many associations.
In an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a Servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.
Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.
14. How can I bind a dynamic list of values into an in query expression?
Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)");
q.setParameterList("id_list", fooIdList);
List foos = q.list();
15. How can I bind properties of a JavaBean to named query parameters?
Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();
16. Can I map an inner class?
You may persist any static inner class. You should specify the class name using the standard form i.e. eg.Foo$Bar
17. How can I assign a default value to a property when the database column is null?
Use a UserType.
18. How can I truncate String data?
Use a UserType.
19. How can I trim spaces from String data persisted to a CHAR column?
Use a UserType.
20. How can I convert the type of a property to/from the database column type?
Use a UserType.
21. How can I get access to O/R mapping information such as table and column names at runtime?
This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.
22. How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?
If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT statement:
Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);
23. How can I retrieve the identifier of an associated object, without fetching the association?
Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.
Long itemId = bid.getItem().getId();
This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called.
24. How can I manipulate mappings at runtime?
You can access (and modify) the Hibernate metamodel via the Configuration object, using getClassMapping(), getCollectionMapping(), etc.
Note that the SessionFactory is immutable and does not retain any reference to the Configuration instance, so you must re-build it if you wish to activate the modified mappings.
25. How can I avoid n+1 SQL SELECT queries when running a Hibernate query?
Follow the best practices guide! Ensure that all
A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3.
If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.
I have a collection with second-level cache enabled, and Hibernate retrieves the collection elements one at a time with a SQL query per element!
Enable second-level cache for the associated entity class. Don't cache collections of uncached entity types.
26. How can I insert XML data into Oracle using the xmltype() function?
Specify custom SQL INSERT (and UPDATE) statements using
You will also need to write a UserType to perform binding to/from the PreparedStatement.
27. How can I execute arbitrary SQL using Hibernate?
PreparedStatement ps = session.connection().prepareStatement(sqlString);
Or, if you wish to retrieve managed entity objects, use session.createSQLQuery().
Or, in Hibernate3, override generated SQL using
I want to call an SQL function from HQL, but the HQL parser does not recognize it!
Subclass your Dialect, and call registerFunction() from the constructor.
28. Why to use HQL?
• Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.
• Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This eliminates the need of creating the object and populate the data from result set.
• Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.
• Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.
• Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
• Database independent: Queries written in HQL are database independent (If database supports the underlying feature).
Subscribe to:
Posts (Atom)