[Tech.][Struts.][Servlet.][JSP.][EJB.][JNDI-JMS][SQL.][JDBC.]
CORE-JAVA: [OOP][CLASS][ABSTRACT][EXCEPTIONS][THREADS][UTILS][PACKAGES][JVM][CASTING][NETWORKING][RMI-XML]
* What is the purpose of garbage collection in Java, and when is it used? (garbage)
A: Garbage collection is known for Automatic Memory Management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the existing objects. In Java, it is good idea to explicitly assign null value to a variable, thus by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee as to when all the objects will be garbage collected. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes "UnReachable" to the program in which it is used. (GC Tuning.) (Reducing GC time.)
Can an object be garbage collected while it is still reachable? (garbage)
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.
Can an object’s finalize() method be invoked while it is reachable? (garbage)
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
* Can an unreachable object become reachable again? (garbage)
A: An unreachable object may become reachable again when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. The finalize method may take any action, including making this object available again to other threads. The purpose of finalize, is to perform cleanup actions before the object is discarded.
If an object is garbage collected, can it become reachable again? (garbage)
Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
* Does garbage collection guarantee that a program will not run out of memory? (garbage)
A: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.
What is the purpose of finalization? (garbage)
The purpose of finalization is to give an unreachable object the opportunity to perform any "cleanup processing" before the object is garbage collected.
How many times may an object's finalize() method be invoked by the garbage collector? (garbage)
An object's finalize() method may only be invoked once by the garbage collector.
* What are Checked and UnChecked Exceptions? (exception)
A: A checked exception is a SUBCLASS of EXCEPTION (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be THROWN. eg, IOException thrown by java.io.FileInputStream's read() method. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. (different exceptions)
* Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses are also unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.
Checked exceptions must be caught at compile time. UnChecked Runtime exceptions do not need to be. Note: THROWABLE is the super class of ERROR and EXCEPTION. RUNTIMEEXCEPTION is a subclass of Exception.
* ERROR is a third kind of UnChecked exception. In case of ERROR the application usually prints a stack trace and exits. Errors often CANNOT be caught. (download java examples)
* What are runtime exceptions? (unchecked exception)
A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
What class of exceptions are generated by the Java run-time system? (unchecked exception)
The Java runtime system generates RuntimeException and Error exceptions.
What happens if an exception is not caught? (checked exception)
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. It is called by the JVM when a thread in this thread group stops because of an uncaught exception.
Which arithmetic operations can result in the throwing of an ArithmeticException? (exception)
Integer "divide by zero" that is, "/" and "%" can result in the throwing of an ArithmeticException.
What is user defined exception? (checked exception)
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending the "Exception" class.
* How to create custom exceptions? (checked exception)
A: Our class should extend the class Exception, or some more specific type there of. EXCEPTION is a subclass of THROWABLE.
* What is the catch or declare rule for method declarations? (checked exception)
A: If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
* What are checked exceptions? (exception)
A: Checked exception are those which the Java compiler forces us to CATCH. e.g. IOException are checked Exceptions.
* What is the difference between Error and an Exception? (exception)
A: An Error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These are JVM errors and we can not repair them at runtime.
While Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
* If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object? (exception)
A: One can not do anything in this scenario. Because Java does not allow multiple inheritance and does NOT provide any exception INTERFACE as well.
* How does an exception permeate through the code? (exception)
A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.
* What are the different ways to handle checked exceptions? (exception)
A: There are two ways to handle exceptions, (1) By wrapping the desired code in a TRY block followed by a CATCH block to catch the exceptions. (2) List the desired exceptions in the THROWS clause of the method and let the caller of the method handle those exceptions.
* What is the basic difference between the 2 approaches to exception handling:
(1) TRY-CATCH block and (2) specifying the candidate exceptions in the THROWS clause? Which approach should be used when? (checked exception)
A: In the first approach as a programmer of the method, we are dealing with the exception. This is fine if you are in a best position to decide what should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
Can an exception be rethrown? (exception)
Yes, an exception can be rethrown.
What is the relationship between a method's throws clause and the exceptions that can be thrown during the method's execution? (checked exception)
A method's throws clause must declare any checked exceptions that are not caught within the body of the method.
How to Retrieve Warnings? (exception)
SQLWarning objects are a subclass of SQLException that deal with database connection warnings. Warnings do not stop the execution of an application, as exceptions happen they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, or to a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which must be invoked in order to see the first warning reported on the calling object.
SQLWarning warning = stmt.getWarnings();
-if (warning != null) {
--while (warning != null) {
--System.out.println("Message: " + warning.getMessage());
--System.out.println("SQLState: " + warning.getSQLState());
--System.out.print("Vendor error code: ");
--system.out.println(warning.getErrorCode());
--warning = warning.getNextWarning(); } } (compile online)
* What should we do, if we want an object of our class to be thrown as an exception object? (checked exception)
A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
Only objects that are instances of this class can be thrown by the throw statement or can be the argument type in a catch clause. throw MUST be declared in a try block.
(Ex:) public class Exp {
--public static void main(String[] args) { new Exp(); }
--public Exp() {
---try { int size=0; System.out.println("In TRY");
---cantBeZero(0); }
---catch (MyError t1) { System.out.println("In CATCH 1"); } }
--public void cantBeZero(int i) throws MyError { if (i == 0) { throw new MyError(); } } }
Below is the subclass of Throwable class.
class MyError extends Throwable { // it can extend either Exception or Error also.
--MyError() { System.out.println("In MyError"); } } (compile online)
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? (catch)
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
The catch blocks catches the exceptions of try block and thus allows the program to continue its execution.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. When closing a file or otherwise recovering resources, place the code in a finally block to insure that resource is always recovered.
Can try statements be nested? (catch)
Yes it can be. Nested try-catch statements are compiled very much like a try statement with multiple catch clauses:
--void nestedCatch() {
---try {
----try { tryItOut(); } // try within try
----catch (TestExc1 e) { handleExc1(e); }
---} catch (TestExc2 e) { handleExc2(e); }
--} (compile online)
How does a try statement determine which catch clause should be used to handle an exception? (try-catch)
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 is executed. The remaining catch clauses are ignored.
Each catch block is an exception handler and handles the type of exception indicated by its argument. Appropriate catch block will be called depending on the exception thrown. Checked exceptions can be thrown within the try statement.
try { }
catch (ExceptionType1 name1) { }
catch (ExceptionType2 name2) { }
What classes of exceptions may be caught by a catch clause? (try-catch)
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. (checked and unchecked)
The Throwable class is the superclass of all errors and exceptions. Only objects that are instances of this class can be thrown by the throw statement or can be the argument type in a catch clause. ERROR and EXCEPTIONS classes are the subclasses of THROWABLE class.
* Is it necessary that each try block must be followed by a catch block? (try-catch)
A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
* If I write return at the end of the try block, will the finally block still execute? (try-catch)
A: Yes even if we write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
* What is the difference between final, finally and finalize? (try-catch)
FINAL - keyword used to declare constants.
FINALLY - keyword handles exception.
FINALIZE - helps in garbage collection. (Examples)
Finalize method is called by the garbage collector on an object. The call System.gc() is effectively equivalent to the call: Runtime.getRuntime().gc()
* If I write System.exit (0); at the end of the try block, will the finally block still execute? (try-catch)
A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n)
Is it true that the code in a finally clause will never fail to execute? (try-catch)
Using System.exit(1); in try block will NOT allow finally code to execute.
System.exit(n) processes return zero(0) if there is NO error and any other value if there is an error. The parameter tells why the program is being terminated.
What is the purpose of the finally clause of a try-catch-finally statement? (try-catch)
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
Realizations. Realizations In Real Life. Amazing Constructive Vibrations. Astrology. Creating Leaders. How ideas are concluded and decisions are materialized. Relationships & Partnerships. The path of victory. An attempt for definition. Speak with a heart. These are contagious. Happy kingdom. MIRACLES. Better to create one ! Cast, God and religion ! Things become inevitable ! We are all looking for! Phase of Life. Destiny, Karma and God. Struggle, perfection and Money. Independence and Freedom. Relationships and Happiness.
No comments:
Post a Comment