Thursday, February 27, 2014

Where is primitive data stored in java memory?

It does not depend on whether it is a primitive data type or not, It depends on whether it is an Instance variable or a local variable.
All local variables are stored in the stack along with their methods within which they are declared.
All instance variables/objects which contain primitive types are stored on the heap even if they are declared inside a method.Only their references stay in the stack if declared inside a method.

Tuesday, February 25, 2014

Out put of the below program

public class SetExample {
    public static void main(String[] args) {
        Set s = new HashSet();
        s.add(1);
        s.add(2);
        s.add(3);
        s.add(new Integer("1"));
      
        Iterator iter = s.iterator();
        while (iter.hasNext()) {
          System.out.println(iter.next());
        }
    }
}

O/P :  1 2 3

public class SetExample {
    public static void main(String[] args) {
        Set s = new HashSet();
        s.add(1);
        s.add(2);
        s.add(3);
        s.add("1");
       
        Iterator iter = s.iterator();
        while (iter.hasNext()) {
          System.out.println(iter.next());
        }
    }
}

O/P :  1  1 2 3

"ravikiran@is%good*person", split the string with special charecters.

import java.util.StringTokenizer;


public class StringTokenizerTest {
    public static void main(String[] args) {
       
        String str = "ravikiran@is%good*person";
       
        System.out.println("---- Split by Special chars ------");
        StringTokenizer st2 = new StringTokenizer(str, "@%*");

        while (st2.hasMoreElements()) {
            System.out.println(st2.nextElement());
        }
    }
}

O/p:

---- Split by Special chars ------
ravikiran
is
good
person


Out out of below program.

public class ConvertStringToInt {
    public static void main(String[] args) {
        int a = Integer.parseInt("ravikiran");
        System.out.println("value of a="+a);
    }
}

O/P: Run time error

Exception in thread "main" java.lang.NumberFormatException: For input string: "ravikiran"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at ConvertNumbers.main(ConvertNumbers.java:4)



Write a program Missing 1-10 numbers in a List

import java.util.ArrayList;


public class MissingNumbers {
    public static void main(String[] args) {
        ArrayList ar = new ArrayList();
        ar.add(1);
        ar.add(2);
        ar.add(3);
        ar.add(4);
        ar.add(8);
        ar.add(6);
        for(int i=0; i<10; i++){
            if(!ar.contains(i)){
                System.out.println("missing number=="+i);
            }
        }
    }
}
O/p:
missing number==0
missing number==5
missing number==7
missing number==9

Out put of the below program.

public class NumbersTest {
    public static void main(String[] args) {

        add(5);
    }

    public static void add(int s) {
        System.out.println("int");
    }

    public static void add(Integer s) {
        System.out.println("Integer");
    }

    public static void add(long s) {
        System.out.println("long");
    }

    public static void add(Long s) {
        System.out.println("Long");
    }

    public static void add(double s) {
        System.out.println("double");
    }

    public static void add(Double s) {
        System.out.println("Double");
    }

    public static void add(String s) {
        System.out.println("String : I am in add method");
    }

    public static void add(StringBuffer s) {
        System.out.println("StringBuffer : I am in add method");
    }
}
Out put : int

Output of the below program

public class StringTest {
    public static void main(String args[]){
        add(null);
    }
  
    public static void add(String s){
        System.out.println("String : I am in add method");
    }
    public static void add(StringBuffer s){
        System.out.println("StringBuffer : I am in add method");
    }
}

O/P : compile time error - The method add(String) is ambiguous for the type
     StringTest

What is the difference between static binding and dynamic binding?


Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is done at runtime only
Dynamic Binding:
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
superClass1.someMethod(); // SuperClass version is called
superClass2.someMethod(); // SubClass version is called
Static Binding:
Class SubClass extends SuperClass{
public String someVariable = "Some Variable in SubClass";
}
SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();
System.out.println(superClass1.someVariable);
System.out.println(superClass2.someVariable);
Output:-
Some Variable in SuperClass
Some Variable in SuperClass



Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.
There are two types of binding
  1. static binding (also known as early binding).
  2. dynamic binding (also known as late binding).

Understanding Type

Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.
  1. int data=30;  
Here data variable is a type of int.

2) References have a type

  1. class Dog{  
  2.  public static void main(String args[]){  
  3.   Dog d1;//Here d1 is a type of Dog  
  4.  }  
  5. }  

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.
  1. class Animal{}  
  2.   
  3. class Dog extends Animal{  
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.  }  
  7. }  
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.

Example of static binding

  1. class Dog{  
  2.  private void eat(){System.out.println("dog is eating...");}  
  3.   
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.   d1.eat();  
  7.  }  
  8. }  

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

  1. class Animal{  
  2.  void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6.  void eat(){System.out.println("dog is eating...");}  
  7.   
  8.  public static void main(String args[]){  
  9.   Animal a=new Dog();  
  10.   a.eat();  
  11.  }  
  12. }  
Output:dog is eating...

Thursday, February 13, 2014

JSP Exception Handling

JSP Exception Handling:

Exception Handling is a process of handling exceptional condition that might occur in your application. Exception Handling in JSP is much easier than Java Technology exception handling. Although JSP Technology also uses the same exception class object.

It is quite obvious that you dont want to show error stack trace to the guy surfing your website. You can't prevent all errors in your application but you can atleast give an user friendlier error response page.

Ways to perform exception handling in JSP:

JSP provide two different way to perform exception handling.

    Using isErrorPage and errorPage attribute of page directive.
    Using <error-page> tag in Deployment Descriptor.

Example of isErrorPage and errorPage attribute

isErrorPage attribute in page directive officially appoint a JSP page as an error page.

error.jsp:

<%@ page isErrorPage = "true" %>
<html>
     <body>
    //Error message
     </body>
</html>

Exception handling in Jsp:

errorPage attribute in page directive tells the Web Container that if an exception occur in this page, forward the request to an error page.

sum.jsp:

<%@ page errorPage = "error.jsp" %>
<html>
     <body>
    <% int x =20/0; %>
    the Sum is <%= x %>
     </body>
</html>

Exception handling in Jsp:

Declaring error page in Deployment Descriptor

You can also declare error pages in the DD for the entire Web Apllication.Using <error-page> tag in Deployment Descriptor you can even configure different error pages for different exception types, or HTTP error code type(400,500 etc.).

Declaring an error page for all type of exception

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>

Declaring an error page for more detailed exception

<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/error.jsp</location>
</error-page>

Declaring an error page based on HTTP Status code

<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

 

Detecting memory leaks:

Detecting memory leaks:
Use tools like JProbe, OptimizeIt etc to detect memory leaks. 
Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on UNIX systems.
Write your own utility class with the help of totalMemory() and freeMemory() methods in the Java Runtime class. Place these calls in your code strategically for pre and post memory recording where you suspect to be causing memory leaks. An even better approach than a utility class is using dynamic proxies or Aspect Oriented Programming (AOP) for pre and post memory recording where you have the control of activating memory measurement only when needed.
Minimising memory leaks:
In Java, typically memory leak occurs when an object of a longer lifecycle has a reference to objects of a short life cycle. This prevents the objects with short life cycle being garbage collected. The developer must remember to remove the references to the short-lived objects from the long-lived objects. Objects with the same life cycle do not cause any issues because the garbage collector is smart enough to deal with the circular references.
JVM Architecture: - JVM 1.4.1 version developed by Hotspot. 
  
Class loader subsystem does the following things: -
1. It will load .class file into memory (RAM)
2. It will verify byte code of that .class file.
3. It will allot the required memory for the program.
            This memory is divided into five parts; they are called runtime data areas.
1. Method area: - It stores class code, static variables, static blocks and method code.
2. Heap area: - Objects are created on Heap. JVM creates objects on Heap.
3. Java Stacks: - Java stacks are used to execute the java methods. Java stacks will have frames. On each frame a separate method is executed.
4. PC Registers: - These registers contain the address of that instruction to be executed by the processor.
5. Native method stacks: - It is a method is written in a language other than java. Native method stacks places when native methods are executed.
Note: - Native method interface links header files to a native method while it is being executing.
r  Execution engine contains interpreter & JIT compiler, which translates byte code into machine language.
How JIT compiles converts byte codes.
For Interpreter
 
Ex: -     print a; 2sec
            print b; 2sec
memory
 
JIT Compiler Processor
 
            Repeat the loop 10times;
            print a; 2 + 2 


r  Hotspot is the block code of given to JIT compiler for execution.
10. Multithread: - Thread means an execution or processing group of statements. Executing different parts of a program simultaneously at a time by using more than one thread is called Multithreading. This is an essential feature of to design server side programs.
11. Dynamic: - It means at runtime, we can develop programs in java, which dynamically change on Internet. (Ex: Applets).
r  In java entire memory will be dynamic memory.

What design patterns are used in EJB?


1. Factory Method:
Define a interface for creating classes, let a subclass (or a helper class) decide which class to    instantiate.This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject implementations. They are actually created by a generated container class. See InitialContextFactory interface that returns an InitialContext based on a properties hashtable.
2.Singleton:
Ensure a class has only one instance, and provide a global point of access to it.
There are many such classes. One example is javax.naming.NamingManager
3. Abstract Factory: 

Provide an interface for creating families of relegated or dependent objects without specifying their concrete classes.
We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has methods to get InitialContext.
4.Builder:
Separate the construction of a complex factory from its representation so that the same construction process can create different representations.
InitialContextFactoryBuilder can create a InitialContextFactory.
5. Adapter:
Convert the interface of a class into another interface clients expect.
In the EJB implementation model, we implement an EJB in a class that extends SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces. EJB container generates a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class and provides declarative transaction, persistence support.
6. Proxy:
Provide a surrogate for other object to control access to it.
We have remote RMI-CORBA proxies for the EJB's.
7. Memento:
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

Inheritance levels of Hibernate?

Single Table per class hierarchy – Single table has all properties of every class in the hierarchy.
Table per concrete class – Each subclass has a table having all the properties of super class also.
Table per subclass – Each class is mapped in its own table. There is separate table for super class and subclass.Table

    Tuesday, February 11, 2014

    Write a program to convert string to number without using Parse method?

    public class MyStringToNumber {

        public static int convert_String_To_Number(String numStr){
            
            char ch[] = numStr.toCharArray();
            int sum = 0;
            int zeroAscii = (int)'0';
            for(char c:ch){
                int tmpAscii = (int)c;
                sum = (sum*10)+(tmpAscii-zeroAscii);
            }
            return sum;
        }
        
        public static void main(String[] args){
            System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
        }
    }

    Difference between RANK() and DENSE_RANK() functions?

    RANK(): Returns the rank of each row in the result set of partitioned column

    select Name,Subject,Marks,
    RANK() over(partition by name order by Marks desc)Rank
    From ExamResult
    order by name,subject
    
    
    
    DENSE_RANK() This is same as RANK() function. Only differencec is returns rank with out gaps.
    select  Name,Subject,Marks,
    DENSE_RANK() over(partition by name order by Marks desc)Rank
    From ExamResult
    order by name
    
    
    
    in RANK() result set screeshot, you can notice that there is gap in Rank(2) for the name Sam and same gap is removed in DENSE_RANK().

    Monday, February 10, 2014

    hibernate different fetch strategy

    Fetching Strategies

    There are four fetching strategies
    1. fetch-”join” = Disable the lazy loading, always load all the collections and entities.
    2. fetch-”select” (default) = Lazy load all the collections and entities.
    3. batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
    4. fetch-”subselect” = Group its collection into a sub select statement.

    Hibernate - Difference between session.Merge and session.SaveOrUpdate?

    saveOrUpdate() does the following:
    • if the object is already persistent in this session, do nothing
    • if another object associated with the session has the same identifier, throw an exception
    • if the object has no identifier property, save() it
    • if the object's identifier has the value assigned to a newly instantiated object, save() it
    • if the object is versioned (by a <version> or <timestamp>), and the version property value is the same value assigned to a newly instantiated object, save() it
    • otherwise update() the object
    and merge() is very different:
    • if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
    • if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
    • the persistent instance is returned
    • the given instance does not become associated with the session, it remains detached

    How to Identify and Resolve Hibernate N+1 Problem?

    Let’s assume that you’re writing code that’d track the price of mobile phones. Now, let’s say you have a collection of objects representing different Mobile phone vendors (MobileVendor), and each vendor has a collection of objects representing the PhoneModels they offer.
    To put it simple, there’s exists a one-to-many relationship between MobileVendor:PhoneModel.
    MobileVendor Class
    1.Class MobileVendor{
    2.long vendor_id;
    3.PhoneModel[] phoneModels;
    4....
    5.}
    Okay, so you want to print out all the details of phone models. A naive O/R implementation would SELECT all mobile vendors and then do N additional SELECTs for getting the information of PhoneModel for each vendor.
    1.-- Get all Mobile Vendors
    2.SELECT * FROM MobileVendor;
    3. 
    4.-- For each MobileVendor, get PhoneModel details
    5.SELECT * FROM PhoneModel WHERE MobileVendor.vendorId=?
    As you see, the N+1 problem can happen if the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.
    Resolve N+1 SELECTs problem
    (i) HQL fetch join
    1."from MobileVendor mobileVendor join fetch mobileVendor.phoneModel PhoneModels"
    Corresponding SQL would be (assuming tables as follows: t_mobile_vendor for MobileVendor and t_phone_model for PhoneModel)
    1.SELECT * FROM t_mobile_vendor vendor LEFT OUTER JOIN t_phone_model model ON model.vendor_id=vendor.vendor_id
    (ii) Criteria query
    1.Criteria criteria = session.createCriteria(MobileVendor.class);
    2.criteria.setFetchMode("phoneModels", FetchMode.EAGER);

    Thursday, February 6, 2014

    What’s the difference between load() and get()?

    load()  get() 
    Only use the load() method if you are sure that the object exists.  If you are not sure that the object exists, then use one of the get() methods. 
    load() method will throw an exception if the unique id is not found in the database.  get() method will return null if the unique id is not found in the database. 
    load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.   get() will hit the database immediately. 

    S.O.L.I.D. Principles

    The S.O.L.I.D. Principles of Class Design

    The S.O.L.I.D. principles seem to be the least common denominator of creating great classes; even before Design Patterns. I recommend taking some time to really think about each of them and how you can apply them. Let's dive in, one by one.

    The Single Responsibility Principle

    There should never be more than one reason for a class to change. Basically, this means that your classes should exist for one purpose only. For example, let's say you are creating a class to represent a SalesOrder. You would not want that class to save to the database, as well as export an XML-based receipt. Why? Well if later on down the road, you want to change database type (or if you want to change your XML schema), you're allowing one responsibility's changes to possibly alter another. Responsibility is the heart of this principle, so to rephrase there should never be more than one responsibility per class.

    The Open Closed Principle

    Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. At first, this seems to be contradictory: how can you make an object behave differently without modifying it? The answer: by using abstractions, or by placing behavior(responsibility) in derivative classes. In other words, by creating base classes with override-able functions, we are able to create new classes that do the same thing differently without changing the base functionality. Further, if properties of the abstracted class need to be compared or organized together, another abstraction should handle this. This is the basis of the "keep all object variables private" argument.

    The Liskov Substitution Principle

    Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. In other words, if you are calling a method defined at a base class upon an abstracted class, the function must be implemented properly on the subtype class. Or, "when using an object through its base class interface, [the] derived object must not expect such users to obey preconditions that are stronger than those required by the base class." The ever-popular illustration of this is the square-rectangle example. Turns out a square is not a rectangle, at least behavior-wise.

    The Dependency Inversion Principle

    Depend on abstractions, not on concretions or High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. (I like the first explanation the best.) This is very closely related to the open closed principle we discussed earlier. By passing dependencies (such as connectors to devices, storage) to classes as abstractions, you remove the need to program dependency specific. Here's an example: an Employee class that needs to be able to be persisted to XML and a database. If we placed ToXML() and ToDB() functions in the class, we'd be violating the single responsibility principle. If we created a function that took a value that represented whether to print to XML or to DB, we'd be hard-coding a set of devices and thus be violating the open closed principle. The best way to do this would be to:
    1. Create an abstract class (named DataWriter, perhaps) that can be inherited from for XML (XMLDataWriter) or DB (DbDataWriter) Saving, and then
    2. Create a class (named EmployeeWriter) that would expose an Output(DataWriter saveMethod) that accepts a dependency as an argument. See how the Output method is dependent upon the abstractions just as the output types are? The dependencies have been inverted. Now we can create new types of ways for Employee data to be written, perhaps via HTTP/HTTPS by creating abstractions, and without modifying any of our previous code! No rigidity--the desired outcome.

    The Interface Segregation Principle

    Clients should not be forced to depend upon interfaces that they do not use. My favorite version of this is written as "when a client depends upon a class that contains interfaces that the client does not use, but that other clients do use, then that client will be affected by the changes that those other clients force upon the class." Kinda sounds like the inheritance specific single responsibility principle.

    How will you create custom tags for JSP?

    A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.
    JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page just as you would the built-in tags you learned about in earlier chapter. The JSP 2.0 specification introduced Simple Tag Handlers for writing these custom tags.
    To write a customer tab you can simply extend SimpleTagSupport class and override the doTag() method, where you can place your code to generate content for the tag.

    Create "Hello" Tag:

    Consider you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion without a body:
    <ex:Hello />
    To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let us create HelloTag class as follows:
    package com.tutorialspoint;
    
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.*;
    import java.io.*;
    
    public class HelloTag extends SimpleTagSupport {
    
      public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();
        out.println("Hello Custom Tag!");
      }
    }
    Above code has simple coding where doTag() method takes the current JspContext object using getJspContext() method and uses it to send "Hello Custom Tag!" to the current JspWriter object.
    Let us compile above class and copy it in a directory available in environment variable CLASSPATH. Finally create following tag library file: <Tomcat-Installation-Directory>webapps\ROOT\WEB-INF\custom.tld.
    <taglib>
      <tlib-version>1.0</tlib-version>
      <jsp-version>2.0</jsp-version>
      <short-name>Example TLD</short-name>
      <tag>
        <name>Hello</name>
        <tag-class>com.tutorialspoint.HelloTag</tag-class>
        <body-content>empty</body-content>
      </tag>
    </taglib>
    Now it's time to use above defined custom tag Hello in our JSP program as follows:
    <%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
    <html>
      <head>
        <title>A sample custom tag</title>
      </head>
      <body>
        <ex:Hello/>
      </body>
    </html>
    Try to call above JSP and this should produce following result:
    Hello Custom Tag!

    Efficient way to implement Singleton Design pattern in java.

    Singleton pattern is a design solution where an application wants to have one and only one instance of any class.It saves memory because object is not created with each request. Only single instance is reused again and again.
    But how to make any class singleton is not so easy task, because there are several way in which singleton can break.
    Steps:
    1.      Make constructor private, so not directly instantiated class
    2.      Make a static method which produce existing instance if one available else new
    3.      Override clone() method. One cannot create a cloned object which also violates singleton pattern.
    4.      If Singleton is class is serializable then once it serialized again deserialized it, but it will not return singleton object.
    Example:
    public class MyUser implements Cloneable{
        private String name = null;
        private static MyUser user = null;
        private MyUser() {
        }
        public static MyUser getInstance() {
            if (user == null) {
                user = new MyUser();
            }                                               
            return user;
        }
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return null;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    Now, make modification in above example- if Serializable, you need to override readResolve() method that violate singleton.
    public class MyUser implements Cloneable, Serializable{
        private String name = null;
        private static MyUser user = null;
        private MyUser() {
        }
        public static MyUser getInstance() {
            if (user == null) {
                user = new MyUser();
            }
            return user;
        }
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return null;
        }
        protected Object readResolve(){
            return getInstance();
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    In multithreading environment may be a problem?
    Suppose there are two threads T1 and T2. Both comes to create instance and execute “user==null”, now both threads have identified instance variable to null thus assume they must create an instance.
    So, why not make getInstance() method Synchronized.
    public synchronized static MyUser getInstance() {
            if (user == null) {
                user = new MyUser();
            }
            return user;
        }
    “Instance of Singleton class can be created per classloader, If singleton class loaded by two classloader then two instance are created.”

    Final Example:

    import java.io.Serializable;

    public class Singleton implements Cloneable, Serializable {

        private String name = null;
        private static Singleton user = null;

        private Singleton() {
        }

        public synchronized  static Singleton getInstance() {
            if (user == null) {
                user = new Singleton();
            }
            return user;
        }

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return null;
        }

        protected Object readResolve() {
            return getInstance();
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }