Friday, May 24, 2013

Export/Import reports using js-import in JasperServer

The Repository Export utility writes out all of the JasperServer Repository objects to a set of XML and binary format files.
The output of the export operation is known as an export catalog.
To create the export catalog,
enter these commands: cd <js-install>/scripts
js-export.bat --everything --output-dir js-backup-catalog 
OR

Exporting Everything......

C:\Program Files\jasperserver-3.1\scripts> js-export.bat --everything --output-dir js-backup-catalog


Export /Reports Folder Contents

C:\Program Files\jasperserver-3.1\scripts>js-export --uris /Reports --output-dir js-backup-catalog 
The import utility reloads all of your repository data. As the data is being saved to the repository,
To import your backup catalog to the repository,
change directory to:
cd <js-install>/scripts
Enter these commands: js-import.bat --input-dir js-backup-catalog
Copy & paste  the exported folder(js-backup-catalog) into the following path(new system) C:\Program Files\jasperserver-3.1\scripts>

Importing Files to jasper server.........
C:\Program Files\jasperserver-3.1\scripts>js-import.bat --input-dir js-backup-catalog
Works Only in Windows XP not in Windows 2000
 Examples: 
·         Import the myDir catalog folder, prepending /importDir to all repository URIs:
js-import --input-dir myDir --prepend-path /importDir

·         Import the myExport.zip catalog archive file:
js-import --input-zip myExport.zip

Examples: 
·
               Export the /reports/samples/AllAccounts resource to a catalog folder:
js-export --uris /reports/samples/AllAccounts --output-dir myExport

·               Export the /images and /fonts folders:
js-export --uris /images,/fonts --output-dir myExport

·               Export all the resources with permissions to a zip catalog:
js-export --uris / --repository-permissions --output-zip myExport.zip

·               Export all the resource and all the report jobs:
js-export --uris / --report-jobs / --output-dir myExport

·               Export the report jobs of the /reports/samples/AllAccounts report unit
js-export --report-jobs /reports/samples/AllAccounts --output-dir myExport

·               Export all the roles and users:
js-export --roles --users --output-dir myExport

·               Export the ROLE_USER and ROLE_ADMINISTRATOR roles along with all  users belonging to one of these roles:
js-export --roles ROLE_USER, ROLE_ADMINISTRATOR --role-users --output- dir myExport
 Export two users:
js-export --users jasperadmin, joeuser--output-dir myExport

 It could be useful a option like "--delete" for the command "js-import" to remove useless resources  from repository:
js-import --delete --input-zip=myReports.zip

Monday, January 14, 2013

Application Server vs Web Server

Application Server vs Web Server

1. Application Server supports distributed transaction and EJB. While Web Server only supports Servlets and JSP.
2. Application Server can contain web server in them. most of App server e.g. JBoss or WAS has Servlet and JSP container.

3. Though its not limited to Application Server but they used to provide services like Connection pooling, Transaction management, messaging, clustering, load balancing and persistence. Now Apache tomcat also provides connection pooling.

4. In terms of logical difference between web server and application server. web server is supposed to provide http protocol level service while application server provides support to web service and expose business level service e.g. EJB.

5. Application server are more heavy than web server in terms of resource utilization.

6. In order to run EJB or host enterprise Java application (.ear) file you need an application server like JBoss, WebLogic, WebSphere or Glassfish, while you can still run your servlet and JSP or java web application (.war) file inside any web server like Tomcat or Jetty.

7. The basic difference between a web server and an application server is
Webserver can execute only web applications i,e servlets and JSPs and has only a single container known as Web container which is used to interpret/execute web applications
Application server can execute Enterprise application, i,e (servlets, jsps, and EJBs) it is having two containers 1. Web Container(for interpreting/executing servlets and jsps) 2. EJB container(for executing EJBs). it can perform operations like load balancing , transaction demarcation etc etc

Following are some of the key differences in features of Web Server and Application Server:
    Web Server is designed to serve HTTP Content. App Server can also serve HTTP Content but is not limited to just HTTP. It can be provided other protocol support such as RMI/RPC
    Web Server is mostly designed to serve static content. Though most of the Web Servers are having plugins to support scripting languages like Perl, PHP, ASP, JSP etc. through which these servers can generate dynamic HTTP content.
    Most of the application servers have Web Server as integral part of them, that means App Server can do whatever Web Server is capable of. Additionally App Server have components and features to support Application level services such as Connection Pooling, Object Pooling, Transaction Support, Messaging services etc.
    As web servers are well suited for static content and app servers for dynamic content, most of the production environments have web server acting as reverse proxy to app server. That means while service a page request, static contents such as images/Static html is served by web server that interprets the request. Using some kind of filtering technique (mostly extension of requested resource) web server identifies dynamic content request and transparently forwards to app server

Example of such configuration is Apache HTTP Server and BEA WebLogic Server. Apache HTTP Server is Web Server and BEA WebLogic is Application Server.

Webserver:
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.

Application Server:
As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application program can use this logic just as it would call a method on an object


Wednesday, January 9, 2013

Java Exceptions question answer



1. What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
2. What is error?
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
3. Which is superclass of Exception?
"Throwable", the parent class of all exception related classes.
4. What are the advantages of using exception handling?
Exception handling provides the following advantages over "traditional" error management techniques:
  • Separating Error Handling Code from "Regular" Code.
  • Propagating Errors Up the Call Stack.
  • Grouping Error Types and Error Differentiation.
5. What are the types of Exceptions in Java
There are two types of exceptions in Java, unchecked exceptions and checked exceptions.
  • Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception.
  • Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.
6. Why Errors are Not Checked?
A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly.

7. Why Runtime Exceptions are Not Checked?
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers.

8. Explain the significance of try-catch blocks?
Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. One or more catch clauses match a specific exception to a block of code that handles it.
try
{
…//Code block for which we want to catch some exceptions
}
catch(SomeException e1)
{
\\ each catch deals with a class of exceptions, determined by
}
catch(AnotherException e1)
{
\\ the run-time system based on the type of the argument
}
finally
{
//The code in finally is executed always after leaving the try –block
}


9. What is the use of finally block?
The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires.
Note: If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes

10. What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes.



11.Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the try block.
Note: It is not valid to use a try clause without either a catch clause or a finally clause.

12.What is the difference throw and throws?
throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions, then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.

A method that does not handle an exception it throws has to announce this:
  public void myfunc(int arg) throws MyException {

        …

    }
throw: Used to trigger an exception. The exception will be caught by the nearest try-catch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

To throw an user-defined exception within a block, we use the throw command:
  throw new MyException("I always wanted to throw an exception!");

13. How to create custom exceptions?
A. By extending the Exception class or one of its subclasses.
Example:
class MyException extends Exception {

  public MyException() { super(); }

  public MyException(String s) { super(s); }

  }

14. What are the different ways to handle exceptions?
There are two ways to handle exceptions:
  • Wrapping the desired code in a try block followed by a catch block to catch the exceptions.
  • List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.
 

Java multithreading Questions and Answer



What is synchronization in respect to multi-threading in Java?

With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program.

Explain different way of using thread?

A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.

What is the difference between Thread.start() & Thread.run() method?

Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.

Why do we need run() & start() method both. Can we achieve it with only run method?

We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.

What is ThreadLocal class? How can it be used?

Below are some key points about ThreadLocal variables
  • A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
  • ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
  • In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
  • Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)

When InvalidMonitorStateException is thrown? Why?

This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.

What is the difference between sleep(), suspend() and wait() ?

Thread.sleep() takes the current thread to a "Not Runnable" state for specified amount of time. The thread holds the monitors it has acquired. For example, if a thread is running a synchronized block or method and sleep method is called then no other thread will be able to enter this block or method. The sleeping thread can wake up when some other thread calls t.interrupt on it. Note that sleep is a static method, that means it always affects the current thread (the one executing sleep method). A common mistake is trying to call t2.sleep() where t2 is a different thread; even then, it is the current thread that will sleep, not the t2 thread. thread.suspend() is deprecated method. Its possible to send other threads into suspended state by making a suspend method call. In suspended state a thread keeps all its monitors and can not be interrupted. This may cause deadlocks therefore it has been deprecated. object.wait() call also takes the current thread into a "Not Runnable" state, just like sleep(), but with a slight change. Wait method is invoked on a lock object, not thread.

Here is the sequence of operations you can think

  • A thread T1 is already running a synchronized block with a lock on object - lets say "lockObject"
  • Another thread T2 comes to execute the synchronized block and find that its already acquired.
  • Now T2 calls lockObject.wait() method for waiting on lock to be release by T1 thread.
  • T1 thread finishes all its synchronized block work.
  • T1 thread calls lockObject.notifyAll() to notify all waiting threads that its done using the lock.
  • Since T2 thread is first in the queue of waiting it acquires the lock and starts processing.

What happens when I make a static method as synchronized?

Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.

Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?

Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized. Below is the example which demonstrates this, The Common class has two methods synchronizedMethod1() and method1() MyThread class is calling both the methods in separate threads,

  1. public class Common {  
  2.   
  3. public synchronized void synchronizedMethod1() {  
  4. System.out.println("synchronizedMethod1 called");  
  5. try {  
  6. Thread.sleep(1000);  
  7. catch (InterruptedException e) {  
  8. e.printStackTrace();  
  9. }  
  10. System.out.println("synchronizedMethod1 done");  
  11. }  
  12. public void method1() {  
  13. System.out.println("Method 1 called");  
  14. try {  
  15. Thread.sleep(1000);  
  16. catch (InterruptedException e) {  
  17. e.printStackTrace();  
  18. }  
  19. System.out.println("Method 1 done");  
  20. }  
  21. }  
  1. public class MyThread extends Thread {  
  2. private int id = 0;  
  3. private Common common;  
  4.   
  5. public MyThread(String name, int no, Common object) {  
  6. super(name);  
  7. common = object;  
  8. id = no;  
  9. }  
  10.   
  11. public void run() {  
  12. System.out.println("Running Thread" + this.getName());  
  13. try {  
  14. if (id == 0) {  
  15. common.synchronizedMethod1();  
  16. else {  
  17. common.method1();  
  18. }  
  19. catch (Exception e) {  
  20. e.printStackTrace();  
  21. }  
  22. }  
  23.   
  24. public static void main(String[] args) {  
  25. Common c = new Common();  
  26. MyThread t1 = new MyThread("MyThread-1"0, c);  
  27. MyThread t2 = new MyThread("MyThread-2"1, c);  
  28. t1.start();  
  29. t2.start();  
  30. }  
  31. }  
Here is the output of the program
  1. Running ThreadMyThread-1  
  2. synchronizedMethod1 called  
  3. Running ThreadMyThread-2  
  4. Method 1 called  
  5. synchronizedMethod1 done  
  6. Method 1 done  
This shows that method1() - is called even though the synchronizedMethod1() was in execution.

Can two threads call two different synchronized instance methods of an Object?

No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed. See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods
  1. public class Common {  
  2. public synchronized void synchronizedMethod1() {  
  3. System.out.println("synchronizedMethod1 called");  
  4. try {  
  5. Thread.sleep(1000);  
  6. catch (InterruptedException e) {  
  7. e.printStackTrace();  
  8. }  
  9. System.out.println("synchronizedMethod1 done");  
  10. }  
  11.   
  12. public synchronized void synchronizedMethod2() {  
  13. System.out.println("synchronizedMethod2 called");  
  14. try {  
  15. Thread.sleep(1000);  
  16. catch (InterruptedException e) {  
  17. e.printStackTrace();  
  18. }  
  19. System.out.println("synchronizedMethod2 done");  
  20. }  
  21. }  
  1. public class MyThread extends Thread {  
  2. private int id = 0;  
  3. private Common common;  
  4.   
  5. public MyThread(String name, int no, Common object) {  
  6. super(name);  
  7. common = object;  
  8. id = no;  
  9. }  
  10.   
  11. public void run() {  
  12. System.out.println("Running Thread" + this.getName());  
  13. try {  
  14. if (id == 0) {  
  15. common.synchronizedMethod1();  
  16. else {  
  17. common.synchronizedMethod2();  
  18. }  
  19. catch (Exception e) {  
  20. e.printStackTrace();  
  21. }  
  22. }  
  23.   
  24. public static void main(String[] args) {  
  25. Common c = new Common();  
  26. MyThread t1 = new MyThread("MyThread-1"0, c);  
  27. MyThread t2 = new MyThread("MyThread-2"1, c);  
  28. t1.start();  
  29. t2.start();  
  30. }  
  31. }  

What is a deadlock?

Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions:
  • When two threads call Thread.join() on each other.
  • When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.

What is Starvation? and What is a Livelock?

Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.

LiveLock

Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
  • When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
  • When all the threads in a program are stuck in infinite loops.

Starvation

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.

How to find a deadlock has occurred in Java? How to detect a Deadlock in Java?

Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.
  • findMonitorDeadlockedThreads() - This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor.
  • findDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.

What is immutable object? How does it help in writing concurrent application?

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer. Immutable objects greatly simplify your multi threaded program, since they are
  • Simple to construct, test, and use.
  • Automatically thread-safe and have no synchronization issues.
To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

How will you take thread dump in Java? How will you analyze Thread dump?

A Thread Dump is a complete list of active threads. A java thread dump is a way of finding out what each thread in the JVM is doing at a particular point of time. This is especially useful when your java application seems to have some performance issues. Thread dump will help you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump and analyze the results based on it. Follow below steps to take thread dump of a java process
  • Step 1
    On UNIX, Linux and Mac OSX Environment run below command:
    ps -el | grep java

    On Windows:
    Press Ctrl+Shift+Esc to open the task manager and find the PID of the java process
  • Step 2:
    Use jstack command to print the Java stack traces for a given Java process PID
    jstack [PID]


What is a thread leak? What does it mean in Java?

Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang.

How can I trace whether the application has a thread leak?

If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways
  • Give unique and descriptive names to the threads created in application. - Add log entry in all thread at various entry and exit points in threads.
  • Change debugging config levels (debug, info, error etc) and analyze log messages.
  • When you find the class that is leaking out threads check how new threads are instantiated and how they're closed.
  • Make sure the thread is Guaranteed to close properly by doing following - Handling all Exceptions properly.
  • Make sure the thread is Guaranteed to close properly by doing following
    • Handling all Exceptions properly.
    • releasing all resources (e.g. connections, files etc) before it closes.

What is thread pool? Why should we use thread pools?

A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Below are key reasons to use a Thread Pool
  • Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.
  • You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).
Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.

Can we synchronize the run method? If yes then what will be the behavior?

Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object

Can we synchronize the constructor of a Java Class?

As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish

This is not an exhaustive list of questions and I am sure I have missed many important questions from Multi-threading area. Can you think of a question which should be included in this list? Please feel free to share any question/suggestion in the comments section.

What is difference between Checked Exception and Unchecked Exception?

Checked Exceptions:
  1. A checked exception is any subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
  2. You should compulsorily handle the checked exceptions in your code, otherwise your code will not be compiled. i.e you should put the code which may cause checked exception in try block. "checked" means they will be checked at compiletime itself.
  3. There are two ways to handle checked exceptions. You may declare the exception using a throws clause or you may use the try..catch block.
  4. The most perfect example of Checked Exceptions is IOException which should be handled in your code Compulsorily or else your Code will throw a Compilation Error.


Unchecked Exceptions :
  1. Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked.
  2. Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time.
  3. With an unchecked exception, however, compiler doesn't force client programmers either to catch the exception or declare it in a throws clause.
  4. The most Common examples are ArrayIndexOutOfBoundException, NUllPointerException ,ClassCastException

Different ways to create objects in Java



There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
 3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject(); 
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
MyObject object = (MyObject) inStream.readObject();
5. getInstance()
getInstance can be use for creating a object;
eg-
Calendar c=Calendar.getInstance();
 

Advance Java Blogging

Java New Articles

Javas Latest News

Java Web Services and XML

Ajax Latest News

Mac OS Java Features

Advance Spotlights

Patterns Features