Showing posts with label JAVA / J2EE. Show all posts
Showing posts with label JAVA / J2EE. Show all posts

Wednesday, August 11, 2010

About innerclasses ?

There are several types of inner classes.

Inner classes
method-inner classes
Anonymus inner classes
static nexted inner classes


The usage of each inner class has shown below :


Inner class:


class Outer
{
class Inner
{
public void innerClassMethod()
{
System.out.println("You are in the method of inner class");
}
}
public void outerClassMethod()
{
Inner i=new Inner();
i.innerClassMethod();
}
}

The above represents the how to create a inner classes and how to use them. As you know when we compile a java file there will be a class files will be generated for all the classes defined in the java file. For inner classes also it will generate the class file as Outer$Inner.class.(But we can not run using Outer$Inner directly).

We can also use the innerClassMethod() in the main also (not only in outerClassMethod()) by creating the object of inner class in the main as below

Outer.Inner innerInstance= new Outer.new Inner()
innerInstance.innerClassMethod();

method-inner classes:
class Outer
{

public void outerClassMethod()
{
class Inner
{
public void innerClassMethod()
{
System.out.println("You are in the method of inner class");
}
}
Inner i=new Inner();
i.innerClassMethod();
}
}

Creating object for method inner classes:

We can only create the object of method-inner classes only in the methods in which the inner class is defined like above.

Anonymous Inner Classes :
class A{
public void sampleMethod() {
System.out.println("Sample Method");
}
}
class B{
A p = new A() {
public void sampleMethod() {
System.out.println("anonymous Sample Method");
}
};
}


If you observe class B, there is class defined with the name outer method A. We can consider that method subclass of class A. But without name. Thats why it is called as Anonymous inner classes.

Static inner classes:
class BigOuter {
static class Nest {void go() { System.out.println("hi"); } }
}
class Broom {
static class B2 {void goB2() { System.out.println("hi 2"); } }
public static void main(String[] args) {
BigOuter.Nest n = new BigOuter.Nest(); // both class names
n.go();
B2 b2 = new B2(); // access the enclosed class
b2.goB2();
}
}

Above i have defined two types of using static inner classes.

Friday, August 6, 2010

Differences between jar, war, ear files ?

jar - java archive,These files are with the .jar extension. The .jar files contain the libraries, resources and accessories files like property files.

war - web archive : These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications.

EAR - enterprise archive, These files are with the .ear extension.
All .jar and .war are packaged as JAR file with .ear extension and deployed into Application Server.

we can say EAR= WAR+JAR.

These three types of files called as jar files with different extensions. If we want to generate these files we will use JAR as a command in the command prompt.

OOPs Concepts ?

Object oriented Programming includes

Objects
Classes
Data abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing

Tuesday, August 3, 2010

Default values of a instance variables ?

The default values of INSTANCE variables are

Object reference - NULL
byte, short, int, long - 0
float, double - 0.0
boolean - false
char - '\uooo' // Unicode character

How to Sort a Collection ? or About Comparable,Comparator interface ?

Here is the example of a sorting a collection ArrayList of String objects.

ArrayList stringList=new ArrayList();
stringList.add("world");
stringList.add("hello");

Collections.sort(stringList); //Collections is a utility class using that we can sort.
After this method the resultant list contains 2 strings with sorted. That means we are able to sort the ArrayList (collection) successfully.

Similarly, If we try to sort a user defined class objects instead of String objects like..
ArrayList dvdList=new ArrayList();
.........
.........
Collections.sort(dvdList); // It will not sort like Sting objects collection.
Because compiler does not know on which basis it has to sort. So, we have to tell programatically to sort the collection by implementing DVDInfo class to Comparable interface. For your information, String objects are implementing Comparable interface internally.

If we implement Comparable interface to our class DVDInfo, we have to implement or override the one of following method.
public int compareTo(Object obj) { .......} or
public int compareTo(DVDInfo obj){ .......}.

Using compareTo() we can have only one sort sequence. To want many sort sequences we use Comaparator and its method compare(). compare() method takes 2 arguments. First argument is which class is to be sorted, second is as which basis the class is to be sorted which should implement Comparator and override the method compare().

String, Wrapperclasses, Date, Calender classes are implicitly implement the Comparable interface.

Monday, August 2, 2010

Difference between String, StringBuffer, StringBuilder ?

String Objects are immutable. That means we can not change the value of a String Object. For example,

String s="Hello"; // A object creates in the heap memory and 's' refers to it.
String s2=s.concat("World");// A new object creates with the "Hello World" and s2 refers to it instead of using the same memory for "Hello" Object

So, Here there is a wastage of memory for 's' object.

Unlike Strings, StringBuffer and StringBuilder are mutable. We can change the value in these objects.
The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Friday, July 30, 2010

About java finalize() method ?

Its a method defined in Object(Which is a base class of all the classes) class. Java dont have destructors instead it uses finalize() method. finalize() method not guarantee to run. For any given object finalize() method will be called only once by the garbage collector. Calling finalize() method can actually result in saving an object from deletion. If finalize() method contains the code of assigning a reference so that the object is not eligible for Garbage Collector. The second time the garbage collector will delete it. Because finalize() method run only one time for a given object.

Thursday, July 29, 2010

The list of interfaces we use in javax.servlet.http package ?

The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between Servlet class running under a HTTP Potocol and the runtime environment provided for an instance of such a class by a conforming Servlet container.

The List of interfaces and classes in javax.servlet.http package are as follows.

HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpServlet
Cookie

The list of interfaces we use in javax.servlet package ?

The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between Servlet class and the runtime environment provided for an instance of such a class by a conforming Servlet container.

The List of interfaces and classes in javax.servlet package are as follows.

Servlet
ServletConfig
ServletRequest
ServletResponse
RequestDispatcher
Filter
FilterConfig
FilterChain
GenericFilter
ServletOutputStream
ServletInputStream
ServletException

Wednesday, July 28, 2010

What is a Java Thread and How to create them ?

Threads are lightweight processes that appear to run in parallel with your main program. Unlike a process a thread shares memory and data with the rest of the program. The word thread is a contraction of "thread of execution".An example of where threads can be useful is in printing. When you click on a print button you probably don't want the main program to stop responding until printing has finished. What would be nice is that the printing process started running "in the background" and allowed you to continue using the main portion of the program.

There are 2 ways to create a java thread.
1. By extending the class with the Thread class.
2. By implementing the Runnable interface.

In both the cases we have to implement run() method.

The best way to create the thread is to implement Runnable interface. Because, As you know java will not support multiple inheritance so, if we extend the class with the Thread class we cant extend with any other class. If we implement the class with Runnable interface, we can extend any other class

Tuesday, July 27, 2010

Calling Java Garbage Collector ?

We can request (not demand) the java garbage collector to run by using 2 ways.

1. Runtime rt = Runtime.getRuntime();
rt.gc();

2. System.gc();

Using Runtime object rt you can call more methods to know JVM memory. Examples,

rt.totalMemory(), Will return the total memory of JVM.
rt.freeMemory(), will return the free memory of JVM.

Which Objects eligible for Garbage Collection in Java ?

The Objects which are eligible for garbage collection are

1. StringBuffer sb=new stringBuffer("Hello");
System.out.println(sb); // "Hello" is NOT ELIGIBLE here for Garbage Collection.
sb=null; //"Hello" is ELIGIBLE here for Garbage Collection.


2. StringBuffer sb1=new stringBuffer("Hello");
StringBuffer sb2=new stringBuffer("goodbye");
s1=s2; //"Hello" is ELIGIBLE here for Garbage Collection.

3. Public static Date getDate(){
Date d2=new Date();
StringBuffer now=new StringBuffer(d2.toString());
System.out.println(now);
return d2;// Here d2 is NOT ELIGIBLE for Garbage Collection. But now is
ELIGIBLE for Garbage Collection
}

Wednesday, July 14, 2010

Advantages of struts2 over struts1.0

• Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle, Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.Struts 1 integrates with JSTL, so it uses the JSTL EL, Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).(Object graph navigation language)( It is aimed to be used in J2EE applications with taglibs as expression language.)
• Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps.
• Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
• Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces. Struts 2 , we can use interfaces.
3. Interceptors
• These are request pre-processors or post processors
• Examples create-session, params, prepare, validation, exception and logger.
o Create-session, which creates HTTPSession.
o Prepare, to run prepare() method.
o Fileupload, to validate a file object
o Exception, handling exceptions.
o Roles, It checks the allowed roles and disallowed roles using intercept() method.
o Servlet-config sets the action properties, based on the different interface implemented.
o Validation, checks the action against all validation rules.

Monday, July 12, 2010

What is JDK, JRE, JVM ?

JDK (Java Development Kit)

Java Development Kit contains tools needed to develop the Java programs, and JRE to run the programs. The tools include compiler (javac.exe), Java application launcher (java.exe), Appletviewer, etc…

Compiler converts java code into byte code. Java application launcher opens a JRE, loads the class, and invokes its main method.

You need JDK, if at all you want to write your own programs, and to compile the m. For running java programs, JRE is sufficient.

JRE is targeted for execution of Java files

i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.

JDK is mainly targeted for java development. I.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file
JRE (Java Runtime Environment)

Java Runtime Environment contains JVM, class libraries, and other supporting files. It does not contain any development tools such as compiler, debugger, etc. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE. If you want to run any java program, you need to have JRE installed in the system

The Java Virtual Machine provides a platform-independent way of executing code; programmers can concentrate on writing software, without having to be concerned with how or where it will run.

If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be installed on the machine.
JVM (Java Virtual Machine)

As we all aware when we compile a Java file, output is not an 'exe' but it's a '.class' file. '.class' file consists of Java byte codes which are understandable by JVM. Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.

The JVM is called "virtual" because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs.

There are different JVM implementations are there. These may differ in things like performance, reliability, speed, etc. These implementations will differ in those areas where Java specification doesn’t mention how to implement the features, like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.

Wednesday, June 30, 2010

Describe HashMap, Hashtable, LinkedHashMap, TreeMap ?

HashMap: It is unordered, unsorted map. HashMap allows one 'null' values in a collection.
Hashtable: It is same as HashMap but it does not allow null either in keys and values.
LinkedHashMap: It takes insertion order. It is slower than HashMap for adding,deleting but faster iteration
TreeMap: It is a SortedMap. Like TreeSet, TreeMap can define a custom Sort using Comparator or Comparator

Tuesday, June 29, 2010

Describe HashSet, LinkedHashSet, TreeSet ?

HashSet: This is unordered, unsorted set. When we dont want to care about the order and no duplicate it is better to use.

LinkedHashSet: It is unorder version of HashSet. It maintains doubly linkedlist across all elements. It is better to use than HashSet, because HashSet order is unpredictable.
-> This elements is stored in which they are inserted.
->When using HashSet and LinkedHashSet the objects you add to them must override hascode() method, if they dont override it allows duplicates.

TreeSet:
->it uses Red-Black tree structure.
->the elements will be in the ascending order according natural order.
-> we can construct a constructor your own rules for what the order should be using a comparable or comparator.

Describe ArrayList, Vector, LinkedList?

ArrayList:it is ordered but not sorted.it gives fast iteration and fast RandomAccess. it implements RandomAccess interface. choose this over a LinkedList when you need fast iteration. but use not as likely to be doing a lot of insertion,deletion.

Vector:Vector,HashTable were the two original collection in before java2..
->Vector methods are Synchronized for thread safety.
->Vector also implements RandomAccess
->if ArrayList wants to thread safety it can use Collection(class) utility methods.

LinkedList:
->it is ordered by index position
->it is doubly Linked to one another.
->LinkedList is implemented by queue so it now supports peck(),poll(),offer().

About Collection framework ?

In collection framework, The key interface we use are
Collection, Set, SortedSet, List, Map, SortedMap, Queue.

Classes are
Map : HashMap, Hashtable, TreeMap, LinkedHashMap
Set : HashSet, LinkedHashSet, TreeSet
List: ArrayList, Vector, LinkedList.
Queue : PriorityQueue

The Utility classes available are Collections, Arrays

Monday, June 28, 2010

About JSP implicit Objects

By default JSP creates some prebuild objects. These are request, response, session, application, page, out, exception, pageContext.
request is a HttpServletRequest Object.
response is a HttpServletResponse Object.
session is a HttpSession Object.
config is a ServletConfig Object.
application is a ServletContext Object.
page is a JspPage Object.
pageContext is a PageContext Object.
out is a JspWriter Object.
exception is a Throwable Object.

Monday, June 21, 2010

Tools to be used to run java Applications or Database ?

Eclipse or NetBeans : IDE for java
MySQL Query Browser : GUI tool for MySql
TOAD : GUI tool for Oracle
ANT : Tool for compiling, deploying, running java applications.
DBVisualizer : Provides relationship diagram for a database.
SOAPUI : Tool for calling a SOAP webservice. It acts like a SOAP Client.
Tomcat : Its a web server for running java web applications.
JBOSS : Its a application server running java Enterprise applications.