Skip to main content

A Complete Interview Question For Java Developer


Warm Up Questions

Introduce yourself?

https://www.facebook.com/photo.php?fbid=10205417759543525&set=pcb.986408768067530&type=3&theater
I am software developer....
Rate yourself in Java from 1 to 10.
7
With respect to Java on which frameworks you worked on? among all which one you think you are good?

Front controller Design Pattern
What was your current/last project and what was your role?
Software engineering in ipaas project
Which version of Java you recently used?
1.8
Java vs javaw vs javaws

java.exe is a Win32 console application. This is provided as a helper so that, instead of using jvm.dll we can execute java classes
javaw.exe is very similar to java.exe. It can be considered as a parallel twin. It is a Win32 GUI application. This is provided as a helper so that application launches its own GUI window and will not launch a console.
javaws.exe is used to launch a java application that is distributed through web. 
J2EE and JEE are same?
yes,J2EE refers to the first version of Java Enterprise Edition.j2ee is the old naming of the java enterprise edition, in the early history java was called simply java afterward sun created a new version of java called java 2 subsequent updates followed the theme OJ java 2 1.3 java 2 1.4 java 2 1.5 
sun realized that this naming is making confusion to people so it dropped the 2 
so j2ee became jee :) 



Difference Between J2SE and J2EE

J2SE is a collection of basic Java classes and APIs. It focuses on new specifications and APIs including XML, Web Services, JDBC version 4.0, programming based on Annotations, API’s for Java compiler and Application client GUI. This was on top of already existing features like Annotations, Generics and Autoboxing.

J2EE provides a server programming platform in Java. It includes JDBC (Java Database Connectivity), RMI (Remote Method Invocation), JMS (Java Message Service), web services and XML are some of the specifications offered by Java EE. Furthermore, specifications unique to Java EE such as Enterprise JavaBeans (EJB), Connecters, Servlets, portlets, Java Server Pages (JSP) are also offered.

Jar vs war vs ear


JAR:
EJB modules which contains enterprise java beans class files and EJB deployment descriptor are packed as JAR files with .jar extension
WAR:
Web modules which contains Servlet class files,JSP FIles,supporting files, GIF and HTML files are packaged as JAR file with .war (web archive) extension
EAR:
All above files (.jar and .war) are packaged as JAR file with .ear (enterprise archive) extension and deployed into Application Server.
Web app vs enterprise app
1.Web application is deployed in Web server which has web container Web application - JSP, Servlet, Java.Web apps are programs which created to run in a web browser. 
2.Enterprise App is deployed in Application server which has Web container, EJB container, set up for messaging services etc. EE app. - JSP, Servlet, Java, EJB, Web Services, JMS.
enterprise app is an integrated program which usually used in a large companies

Web servers vs application server



Application Server

Web Server

What is it?A server that exposes business logic to client applications through various protocols including HTTP.A server that handles HTTP protocol.
JobApplication server is used to serve web based applications and enterprise based applications(i.e servlets, jsps and ejbs...). Application servers may contain a web server internally.Web server is used to serve web based applications.(i.e servlets and jsps)
FunctionsTo deliver various applications to another device, it allows everyone in the network to run software off of the same machine.Keeping HTML, PHP, ASP, etc files available for the web browsers to view when a user accesses the site on the web, handles HTTP requests from clients.
Supportsdistributed transaction and EJB'sServlets and JSP
Jdk vs jre vs jvm?

JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

JRE

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
jre

JDK

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
jdk
Features of java7? Features of java 8? How you would take decision to choose technology?

What is your expected salary
Check salary depending on location:
http://swz.salary.com/SalaryWizard/Software-Developer-I-Salary-Details-Fairfield-IA.aspx

Java Core
Is  Empty .java file name a valid source file name?
Yes. We can create empty .java source file name and its valid source file and will be converted *.class file.

What is the default value of the local variables?
The local variiables will not have any default values.They must be explicitly provided with some value.Accessing an uninitialized local variable will result in a compile-time error.

What is final variable, final method, final class, blank final variable and static blank final variable?

Final Variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Final Method
If you make any method as final, you cannot override it.
Final Class
If you make any class as final, you cannot extend it.
Blank or uninitialized final variable
A final variable that is not initialized at the time of declaration is known as blank final variable.It can be initialized only in constructor.
Static Blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.
1.    class A{  
2.      static final int data;//static blank final variable  
3.      static{ data=50;}  
4.      public static void main(String args[]){  
5.        System.out.println(A.data);  
6.     }  
7.    }  


Data types and their default values?

In java, there are two types of data types
·         primitive data types
·         non-primitive data types
datatype in java
Data Type
Default Value
Default size
boolean
false
1 bit
char
'\u0000'
2 byte
byte
0
1 byte
short
0
2 byte
int
0
4 byte
long
0L
8 byte
float
0.0f
4 byte
double
0.0d
8 byte

Java Literals?
Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. 
Integer literals
Floating literals
Character literals
String literals
Boolean literals
examples:
char a = '\u0001';
String a = "\u0001";
byte a = 68;
char a = 'A' etc


Why  main method is public?
The Java® Language Specification says nothing about the type of the class which contains the main method. However, main method must be public. (See section 12.1 from the specification.)

Can we change the name of main method? if yes explain how? if no then  why?
. I think we cannot change the name of main method

How many ways  do we  have to declare main method?

Can we overload main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:
1.    class Overloading1{  
2.      public static void main(int a){  
3.      System.out.println(a);  
4.      }  
5.        
6.      public static void main(String args[]){  
7.      System.out.println("main() method invoked");  
8.      main(10);  
9.      }  
10. }  
can we declare main method as final?
Yes, main can be declared as final. Final means the method or variable cannot be modified in sub-class It does not have any impact on main because Static function is not a part of object instance.

Can we declare main method as synchronized?
A Java synchronized block marks a method or a block of code as synchronized. Java synchronized blocks can be used to avoid race conditions. since main method is static we can use synchronized for main method.

Can we declare main method private?
Yes, we can declare main method as private. It compiles without any errors, but in runtime, it says main method is not public. - See more at: http://www.java2novice.com/java_interview_questions/private-main-method/#sthash.IfdxhSBS.dpuf

Can we declare main method as strictfp?
can we change the order of public static void main to static public void main?
can  we  change the name of argument passed in main method?
how many  ways do we  have to declare the argument in main method?

public static synchronized strictfp void main(String args) will it  work  ?
System.out.printIn("subash"); What is System? what is out and its type?what is println  ?
What are access modifiers in Java?

Access Modifiers
Same Class
Same Package
Subclass
Other packages
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no access modifier
Y
Y
N
N
private
Y
N
N
N

Final, finally and finalize keywords in Java?
final: final is a keyword. The variable decleared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden. 
finally: finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. 
finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected.

Covarient return type? Example
The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type
1.    class A{  
2.    A get(){return this;}  
3.    }  
4.      
5.    class B1 extends A{  
6.    B1 get(){return this;}  
7.    void message(){System.out.println("welcome to covariant return type");}  
8.      
9.    public static void main(String args[]){  
10. new B1().get().message();  
11. }  
12. }  
13.Output:welcome to covariant return type
14. As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.

Marker interface..? When to use?
In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a class. For example, the Serializable Marker Interface lets the author of a class say that their class will behave correctly when serialized and deserialized.


In modern Java, marker interfaces have no place. They can be completely replaced by Annotations.
Java Marker Interface Examples
  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener

Java Serialization? When to use  ?  What is the advantage?
Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implementsjava.io.Serializable interface by default.
advantage
It is mainly used to travel object's state on the network (known as marshaling).

What is Comparator interface.? When to use?

What is Comparable interface.? When to use?


Difference between Extemalizable and Serializable in Java.
1) One of the obvious difference between Serializable and Externalizable is that Serializable is a marker interface i.e. does not contain any method but Externalizable interface contains two methods writeExternal() and readExternal().

2) Second difference between Serializable vs Externalizable is responsibility of Serialization. when a class implements Serializable interface, default Serialization process gets kicked of and that takes responsibility of serializing super class state. When any 
class in Java implement java.io.Externalizable than its your responsibility to implement Serialization process i.e. preserving all important information.

3) This difference between Serializable and Externalizable is performance. You can not do much to improve performance of default serialization process except reducing number of fields to be serialized by using 
transient and static keyword but with Externalizable interface you have full control over Serialization process.

4) Another important difference between Serializable and Externalizable 
interface is maintenance. When your Java class implements Serializable interface its tied with default representation which is fragile and easily breakable if structure of class changes e.g. adding or removing field. By using java.io.Externalizable interface you can create your own custom binary format for your object.

Read more: http://java67.blogspot.com/2012/10/difference-between-serializable-vs-externalizable-interface.html#ixzz3wlsaXHb1

Difference between transient and volatile variable
1) transient keyword is used along with instance variables to exclude them from serialization process. if a field is transient its value will not be persisted. 
volatile keyword can also be used in variables to indicate compiler and JVM that always read its value from main memory and follow happens-before relationship on visibility of volatile variable among multiple thread. 


2) transient keyword can not be used along with static keyword but volatile can be used along with static. 

volatile is a keyword in Java. You cannot use this as a variable or method name. We typically use volatile keyword when we share variables with more than one thread in a multi-threaded environment, and we want to avoid any memory inconsistency errors due to the caching of these variables in the CPU cache

Difference between Java Stack and Heap?

The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.
The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.


== operateor v/s .equal() method?
Let clear all these differences between equals and == operator using one Java example :

String s1=new String("hello");
String s2=new String
("hello");

Here we have created two string s1 and s2 now will use == and equals () method to compare these two String to check whether they are equal or not.

First we use equality operator  == for comparison  which only returns true if both reference variable are pointing to same object.

if(s1==s2) {
     System.
out.printlln("s1==s2 is TRUE");
} else{
     System.
out.println("s1==s2 is FALSE");
}

Output of this comparison is FALSE because we have created two objects which have different location in heap so == compare their reference or address location and return false. Now if we use equals method to check their equivalence what will be the output


if
(s1.equals(s2)) {
      System.
out.println("s1.equals(s2) is TRUE");
} else {
      System.
out.println("s1.equals(s2) is FALSE");
}

Output of this comparison is TRUE because java.lang.String class has already overridden the equals() method of Object class and check that contents are same or not because both have same value hello so they are equal according to String class equals() method .

Fail Fast and Fail Save?
http://javahungry.blogspot.com/2014/04/fail-fast-iterator-vs-fail-safe-iterator-difference-with-example-in-java.html


Local class vs Anonymous Class?


Checked and Unchecked Exceptions?
Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception usingthrows keyword.
Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

How to make java class immutable
1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
2) Make all fields final and private
3) Don’t allow subclasses to override methods: The simplest way to do this is to declare the class as final.
4) Special attention when having mutable instance variables
A more sophisticated approach is to make the constructor private and construct instances in factory methods

String
Is  String a data Type?
String isn't a primitive datatype - it's a class, a reference type

What is String Mutability and immutability?

Is String final?
yes, String is final to make it immutable.One advantage of immutable objects is that
You can share duplicates by pointing them to a single instance.

Immutable String in JAVA
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1.    class Testimmutablestring{  
2.     public static void main(String args[]){  
3.       String s="Sachin";  
4.       s.concat(" Tendulkar");//concat() method appends the string at the end  
5.       System.out.println(s);//will print Sachin because strings are immutable objects  
6.     }  
7.    }  
Output:Sachin
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:
1.    class Testimmutablestring1{  
2.     public static void main(String args[]){  
3.       String s="Sachin";  
4.       s=s.concat(" Tendulkar");  
5.       System.out.println(s);  
6.     }  
7.    }  
Output:Sachin Tendulkar
What is String pool?

Does String thread safe?
yes

String Literal v/s String as  new()?
String s="subash";
String s=new String("Subash")

String v/s StringBuffer v/s StringBuilder  ?

String


String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  . 
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed.


String  demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.




demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable            
 // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string  


StringBuffer


StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe . 


Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .


But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.


StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using 
toString() method.


StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer


StringBuilder


StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe .  




StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye"); 
// Above statement is right as it modifies the value which is allowed in the StringBuilder




----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                 
Storage Area | Constant String Pool           Heap                       Heap 
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------





Please mention in the comments in case you have any doubts related to the post: difference between string, stringbuffer  and stringbuilder.





Hibernate

What is hibernate?

Hibernate ORM (Hibernate in short) is an object-relational mapping framework for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.Hibernate's primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual result set handling and object conversion. Applications using Hibernate are portable to supported SQL databases with little performance 
https://en.wikipedia.org/wiki/Hibernate_(framework) 

What is ORM?

 With Object relational mapping, the objects involved will be translated into smaller forms so it could be properly stored on the database without losing some of its properties.
 Through ORM application will have access to the database through objects and ORM also involves less coding.
Connection connection = DriverManager.getConnection(url , user , password)
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE);
String SqlQuery="SELECT ... FROM persons WHERE id = 10"
ResultSet emps = statement.executeQuery(sqlQuery);
String name = emps[0]["FIRST_NAME"];

In contrast, the following makes use of an ORM API, allowing the writing of code which naturally makes use of the features of the language.
Person p = repository.GetPerson(10);
String name = p.getFirstName();
What is persistence?
Persistence simply means that we would like our application’s data to outlive the applications process. In Java terms, we would like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later.

What is Object-Relational Impedance Mismatch?
'Object-Relational Impedance Mismatch' (sometimes called the 'paradigm mismatch') is just a fancy way of saying that object models and relational models do not work very well together. RDBMSs represent data in a tabular format (a spreadsheet is a good visualization for those not familiar with RDBMSs), whereas object-oriented languages, such as Java, represent it as an interconnected graph of objects. Loading and storing graphs of objects using a tabular relational database exposes us to 5 mismatch problems
1. Association 2. Data Navigation 3. Granularity 4. Inheritence 5. Identity

hibernate architecture?

Hibernate Architecture
http://www.tutorialspoint.com/hibernate/hibernate_architecture.htm

Core interfaces of Hibernate?


A. Configuration Interface: 
1. Database Connection files are: hibernate.properties and hibernate.cfg.xml.
2.Class Mapping Setup

B.SessionFactory Interface: You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.

C. Session Interface: Persistent objects are saved and retrieved through a Session object.

D. Transaction Interface:Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

E. Query Interface:Query Interface uses SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects.

F.Criteria Interface:Criteria Interface are used to create and execute object oriented criteria queries to retrieve objects.

example code:
http://www.tutorialspoint.com/hibernate/hibernate_examples.htm

SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee); 
 // or List employees = session.createQuery("FROM Employee").list(); 
 String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();
//criteria
 Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();
tx.commit();
session.close(); 

SessionFactory?
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.
Is  SessionFactory a thread -safe object?
The SessionFactory is a thread safe object and used by all the threads of an application.
What  is  Session?
he Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
Is  Session a thread -safe object?
Session are not usually thread safe and they should be created and destroyed them as needed.
difference between session.save() and session.persist() method? Est I
session.persist() : Does the same like session.save(). 
But session.save() return Serializable object but session.persist() return void. 
session.save() returns the generated identifier (Serializable object) and session.persist() doesn't. 

it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with session and transcation .
difference between get and load method?

example:

http://www.journaldev.com/3472/hibernate-session-get-vs-load-difference-with-examples

 SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
         
        //Get Example
        Employee emp = (Employee) session.get(Employee.class, new Long(2));
        System.out.println("Employee get called");
        System.out.println("Employee ID= "+emp.getId());
        System.out.println("Employee Get Details:: "+emp+"\n");
         
        //load Example
        Employee emp1 = (Employee) session.load(Employee.class, new Long(1));
        System.out.println("Employee load called");
        System.out.println("Employee ID= "+emp1.getId());
        System.out.println("Employee load Details:: "+emp1+"\n");
         
        //Close resources
        tx.commit();
        sessionFactory.close();

The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial:
If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns null if the object can’t be found.
The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder that triggers the loading of the real object when it’s accessed for the first time; On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null

difference between update and merge method?
update updates an object in the session. So if the object is in the session it will update. If the object is not in the session, you should call merge. I believe callingupdate for a detached instance will result in an exception.
http://stackoverflow.com/questions/7475363/differences-among-save-update-saveorupdate-merge-methods-in-session
http://www.journaldev.com/3481/hibernate-save-vs-saveorupdate-vs-persist-vs-merge-vs-update-explanation-with-examples

States of object in hibernate?


What are the inheritance mapping strategies?


There are three inheritance mapping strategies defined in the hibernate:
  1. Table Per Hierarchy:    @Inheritance(strategy=InheritanceType.SINGLE_TABLE), @DiscriminatorColumn and @DiscriminatorValue annotations for mapping table per hierarchy strategy.In case of table per hierarchy, only one table is required to map the inheritance hierarchy. Here, an extra column (also known as discriminator column) is created in the table to identify the class.  http://www.javatpoint.com/hibernate-table-per-hierarchy-using-annotation-tutorial-example
  2. Table Per Concrete class : we need to use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) annotation in the parent class and @AttributeOverrides annotation in the subclasses which defines that parent class attributes will be overriden in this class. In table structure, parent class table columns will be added in the subclass table. http://www.javatpoint.com/hibernate-table-per-concrete-class-using-annotation-tutorial-example
  3. Table Per Subclass; We need to specify @Inheritance(strategy=InheritanceType.JOINED) in the parent class and @PrimaryKeyJoinColumnannotation in the subclasses. http://www.javatpoint.com/hibernate-table-per-subclass-using-annotation-tutorial-example
How to make a immutable  class  in hibernate?

http://www.concretepage.com/hibernate/immutable_hibernate_annotation
In Hibernate Annotation if we want to make an entity immutable, @Immutable can help. @Immutable will now allow the entity to be modified. We can initialize an immutable entity one time but onwards it will not be modified. If we will try to modify, hibernate will not throw error. It will silently be discarded. In the example we have an immutable entity. We will initialize our entity then we will update. And it will not be updated.

What  is  automatic dirty checking in hibernate?

Dirty Checking  is one of the features of hibernate. In dirty checking, hibernate automatically detects whether    an object is modified (or) not and need to be updated. As long as the object is in persistent state i.e., bound to a particular Session(org.hibernate.Session). Hibernate monitors any changes to the objects and executes sql.
http://javabrowsers.blogspot.com/2012/07/dirty-checking-in-hibernate.html

Association mapping are possible in hibernate?
Yes, see blog
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/associations.html

Is it possible to perform collection mapping with One -to -One and  Many  -to -One?
yes


@Entity
@Table(name="DEPARTMENT")
public class Department {
    @Id
    @GeneratedValue
    @Column(name="DEPARTMENT_ID")
    private Long departmentId;
     
    @Column(name="DEPT_NAME")
    private String departmentName;
     
    @OneToMany(mappedBy="department")
    private Set<Employee> employees;
    // Getter and Setter methods
}


@Entity
@Table(name="EMPLOYEE")
public class Employee {
    @Id
    @GeneratedValue
    @Column(name="employee_id")
    private Long employeeId;
     
    @Column(name="firstname")
    private String firstname;

@ManyToOne

  @JoinColumn(name="department_id")

  private Department department;

}

http://viralpatel.net/blogs/hibernate-one-to-many-annotation-tutorial/

What  is  lazy loading in hibernate?
it will not load association entity when owner entity is fetched first time. It loads the association entity upon user request.

note that @OneToMany and @ManyToMany associations are defaulted to LAZY loading; and @OneToOne and @ManyToOneare defaulted to EAGER loading. This is important to remember to avoid any pitfall in future.
example
@OneToMany( mappedBy = "category", fetch = FetchType.LAZY )
private Set<ProductEntity> products;

Eager Initialization in Hibernate..?
"FetchType.EAGER"  is just opposite to LAZY i.e. it will load association entity as well when owner entity is fetched first time.

Locking

Hibernate Cashing?
Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications.
Caching is important to Hibernate as well which utilizes a multilevel caching schemes as explained below:
Hibernate Caching
difference between first level cache and second level cache?

First-level cache:The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database.If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database.

Second-level cache:Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions.Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider interface is provided, which must be implemented to provide Hibernate with a handle to the cache implementation.



What is intercepter in hybernate?
an object passes through different stages in its life cycle and Interceptor Interface provides methods which can be called at different stages to perform some required tasks.
http://www.tutorialspoint.com/hibernate/hibernate_interceptors.htm

What  is  the process to persist data in Java?
persistence manager

You are trying to connect to database using Hibernate, can you briefly explain the steps?

Create POJO Classes:consider our Employee class with getXXX and setXXX methods

download hybernate

Update Hibernate Configuration File

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
       <mapping class="net.viralpatel.hibernate.Employee"/>
          
    </session-factory>
</hibernate-configuration>





What is the difference bw SessionFactory and EntityManager..?


If you are using the JPA’s standard specification implementation, then you would use EntityManagerFactory for opening the session. But, if you are using the hibernate implementation, you have hibernate specific SessionFactory for managing the sessions. Here there is lot of confusion between developers like which one is the best approach. Here, there is two opinions are popular:
  1. EntityManagerFactory is  the standard implementation, it is the same across all the implementations. If we migrate our ORM for any other provider, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate’s session factory, it is tied  to hibernate APIs and ca not migrate to new vendor easily.
  2. One dis-advantage of using the standard implementation is that, it is not providing the advanced features. There is not much control provided in the EntityManager APIs. Whereas, hibernate’s SessionFactory has lot of advanced features which can not done in JPA. One such thing is retrieving the ID generator without closing the transaction, batch insert, etc.

Can we define more than one session Factories in Hibernate..?

It is always recommended that there is one session factory per database, per JVM. Having multiple instances of session factory can lead to performance problems as well as abnormal behavior of transactions.

Write code to define SessionFactory..?

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
or 
SessionFactory factory = new Configuration().configure().buildSessionFactory();

ServletIJSP

-Servlet/Jsp LifeCycle
-Parameters
-get/post difference
-jsp/servlet thread safety
-forward/redirect difference ces  I
-Generic Servlet
-Difference b/w @Include and Jsp Inculed
-context path
-Request/Response Diffemce
-Jsp/Servlet Difference
-What are page directives in JSP..?
-What is the difference bw GET/POST..?
-What is URL Re-writting..?
-Is  JSP Thread safe?
-How you will make your jsp thread safe..?
-What is Generic Servlet..?
-How you will define a Servelt..?
-Write a code to forward your request from start.jsp-> ServletA -> ServletB->  end  jsp
-What is request/response scope..?
-What are tag libraries..?
How a tag works/ what is its life cycle..?

between hide comment and output comment?

What are the JSP implicit objects?
How can I  implement a thread -safe JSP page? What are the advantages and Disadvantages of using it?
How can I  prevent the output of my JSP or Servlet pages from being cached by the browser?
(OR) How to disable caching on back button of the browser?
How can we handle the exceptions in JSP?
How can we forward the request from jsp page to the servlet  ?
Can we use the exception implicit object in any jsp page?
What are context initialization parameters?
What are the different scope values for the <jsp:useBean> tag?
What is the difference between ServletContext and PageContext?
difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
What is EL in JSP?
What is JSTL?
How many tags are provided in JSTL?
What are the 3 tags used in JSP bean development?
How to disable session in JSP?

Exception Handling

What are checked  and unchecked Exceptions? Eff I

Design Patterns

What  is  a Factory Design Pattern?

Factory pattern is one of most used design pattern in Java.In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Factory Pattern UML Diagram
or
Design screenshot
http://www.tutorialspoint.com/design_pattern/factory_pattern.htm

What other Design Patterns have you used in Java?
MVC, Factory Method, Proxy Method, Singleton Pattern, Prototype, Facade


Explain Singleton Patterns.
Singleton pattern is one of the simplest design patterns in Java.This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. SingleObject class have its constructor as private and have a static instance of itself.
SingleObject class provides a static method to get its static instance to outside world.
public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}
public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();

      //Get the only object available
      SingleObject object = SingleObject.getInstance();

      //show the message
      object.showMessage();
   }
}
Explain Facade Patterns.
This pattern involves a single class which provides simplified methods required by client and delegates calls to methods of existing system classes.
Facade Pattern UML Diagram
public interface Shape {
   void draw();
}
public class Rectangle implements Shape {

   @Override
   public void draw() {
      System.out.println("Rectangle::draw()");
   }
}
public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Square::draw()");
   }}
public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Circle::draw()");
   }
}
public class ShapeMaker {
   private Shape circle;
   private Shape rectangle;
   private Shape square;

   public ShapeMaker() {
      circle = new Circle();
      rectangle = new Rectangle();
      square = new Square();
   }

   public void drawCircle(){
      circle.draw();
   }
   public void drawRectangle(){
      rectangle.draw();
   }
   public void drawSquare(){
      square.draw();
   }
}
public class FacadePatternDemo {
   public static void main(String[] args) {
      ShapeMaker shapeMaker = new ShapeMaker();

      shapeMaker.drawCircle();
      shapeMaker.drawRectangle();
      shapeMaker.drawSquare();  
   }
}
Explain proxy Patterns.
In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.
In proxy pattern, we create object having original object to interface its functionality to outer world.
Proxy Pattern UML Diagram
public interface Image {
   void display();
}
public class RealImage implements Image {

   private String fileName;

   public RealImage(String fileName){
      this.fileName = fileName;
      loadFromDisk(fileName);
   }

   @Override
   public void display() {
      System.out.println("Displaying " + fileName);
   }

   private void loadFromDisk(String fileName){
      System.out.println("Loading " + fileName);
   }
}
public class ProxyImage implements Image{

   private RealImage realImage;
   private String fileName;

   public ProxyImage(String fileName){
      this.fileName = fileName;
   }

   @Override
   public void display() {
      if(realImage == null){
         realImage = new RealImage(fileName);
      }
      realImage.display();
   }
}
public class ProxyPatternDemo {
 
   public static void main(String[] args) {
      Image image = new ProxyImage("test_10mb.jpg");

      //image will be loaded from disk
      image.display(); 
      System.out.println("");
      
      //image will not be loaded from disk
      image.display();  
   }
}
Verify the output.
Loading test_10mb.jpg
Displaying test_10mb.jpg

Displaying test_10mb.jpg
Explain prototype Patterns.

http://www.tutorialspoint.com/design_pattern/prototype_pattern.htm

What  is  the difference bw .jsf pages and .xhtml pages..?
The *.jsf is just one of widely used URL patterns of the FacesServlet mapping in web.xml. Other ones are *.faces and /faces/
Wheas .xhtml is widely used html extension for JSF framework.


<servlet-mapping>
<servlet-name> faces-servlet-name </servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
http://stackoverflow.com/questions/7914660/what-is-the-difference-between-creating-jsf-pages-with-jsp-or-xhtml-or-jsf-ex




Database

What  are Joins  in  SQL?
There are different types of joins available in SQL:
  • INNER JOIN: returns rows when there is a match in both tables.
  • Customer
  • +----+----------+-----+-----------+----------+
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    |  3 | kaushik  |  23 | Kota      |  2000.00 |
    |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    |  6 | Komal    |  22 | MP        |  4500.00 |
    |  7 | Muffy    |  24 | Indore    | 10000.00 |
    +----+----------+-----+-----------+----------+
  • Order
  • | OID | DATE                |          ID | AMOUNT |
    +-----+---------------------+-------------+--------+
    | 102 | 2009-10-08 00:00:00 |           3 |   3000 |
    | 100 | 2009-10-08 00:00:00 |           3 |   1500 |
    | 101 | 2009-11-20 00:00:00 |           2 |   1560 |
    | 103 | 2008-05-20 00:00:00 |           4 |   2060 |
    +-----+---------------------+-------------+--------+
  • SQL> SELECT  ID, NAME, AMOUNT, DATE
         FROM CUSTOMERS
         INNER JOIN ORDERS
         ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
    This would produce the following result:
    +----+----------+--------+---------------------+
    | ID | NAME     | AMOUNT | DATE                |
    +----+----------+--------+---------------------+
    |  3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
    |  3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
    |  2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
    |  4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
    +----+----------+--------+---------------------+
  • LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
  • SQL> SELECT  ID, NAME, AMOUNT, DATE
         FROM CUSTOMERS
         LEFT JOIN ORDERS
         ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
    This would produce the following result:
    +----+----------+--------+---------------------+
    | ID | NAME     | AMOUNT | DATE                |
    +----+----------+--------+---------------------+
    |  1 | Ramesh   |   NULL | NULL                |
    |  2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
    |  3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
    |  3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
    |  4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
    |  5 | Hardik   |   NULL | NULL                |
    |  6 | Komal    |   NULL | NULL                |
    |  7 | Muffy    |   NULL | NULL                |
    +----+----------+--------+---------------------+

  • RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
  • SQL> SELECT  ID, NAME, AMOUNT, DATE
         FROM CUSTOMERS
         RIGHT JOIN ORDERS
         ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
    This would produce the following result:
    +------+----------+--------+---------------------+
    | ID   | NAME     | AMOUNT | DATE                |
    +------+----------+--------+---------------------+
    |    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
    |    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
    |    2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
    |    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
    +------+----------+--------+---------------------+
  • FULL JOIN: returns rows when there is a match in one of the tables.
  • SQL> SELECT  ID, NAME, AMOUNT, DATE
         FROM CUSTOMERS
         FULL JOIN ORDERS
         ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
    This would produce the following result:
    +------+----------+--------+---------------------+
    | ID   | NAME     | AMOUNT | DATE                |
    +------+----------+--------+---------------------+
    |    1 | Ramesh   |   NULL | NULL                |
    |    2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
    |    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
    |    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
    |    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
    |    5 | Hardik   |   NULL | NULL                |
    |    6 | Komal    |   NULL | NULL                |
    |    7 | Muffy    |   NULL | NULL                |
    |    3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
    |    3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
    |    2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
    |    4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
    +------+----------+--------+---------------------+
  • CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
  • SQL> SELECT  ID, NAME, AMOUNT, DATE
         FROM CUSTOMERS, ORDERS;
    This would produce the following result:
    +----+----------+--------+---------------------+
    | ID | NAME     | AMOUNT | DATE                |
    +----+----------+--------+---------------------+
    |  1 | Ramesh   |   3000 | 2009-10-08 00:00:00 |
    |  1 | Ramesh   |   1500 | 2009-10-08 00:00:00 |
    |  1 | Ramesh   |   1560 | 2009-11-20 00:00:00 |
    |  1 | Ramesh   |   2060 | 2008-05-20 00:00:00 |
    |  2 | Khilan   |   3000 | 2009-10-08 00:00:00 |
    |  2 | Khilan   |   1500 | 2009-10-08 00:00:00 |
    |  2 | Khilan   |   1560 | 2009-11-20 00:00:00 |
    |  2 | Khilan   |   2060 | 2008-05-20 00:00:00 |
    |  3 | kaushik  |   3000 | 2009-10-08 00:00:00 |
    |  3 | kaushik  |   1500 | 2009-10-08 00:00:00 |
    |  3 | kaushik  |   1560 | 2009-11-20 00:00:00 |
    |  3 | kaushik  |   2060 | 2008-05-20 00:00:00 |
    |  4 | Chaitali |   3000 | 2009-10-08 00:00:00 |
    |  4 | Chaitali |   1500 | 2009-10-08 00:00:00 |
    |  4 | Chaitali |   1560 | 2009-11-20 00:00:00 |
    |  4 | Chaitali |   2060 | 2008-05-20 00:00:00 |
    |  5 | Hardik   |   3000 | 2009-10-08 00:00:00 |
    |  5 | Hardik   |   1500 | 2009-10-08 00:00:00 |
    |  5 | Hardik   |   1560 | 2009-11-20 00:00:00 |
    |  5 | Hardik   |   2060 | 2008-05-20 00:00:00 |
    |  6 | Komal    |   3000 | 2009-10-08 00:00:00 |
    |  6 | Komal    |   1500 | 2009-10-08 00:00:00 |
    |  6 | Komal    |   1560 | 2009-11-20 00:00:00 |
    |  6 | Komal    |   2060 | 2008-05-20 00:00:00 |
    |  7 | Muffy    |   3000 | 2009-10-08 00:00:00 |
    |  7 | Muffy    |   1500 | 2009-10-08 00:00:00 |
    |  7 | Muffy    |   1560 | 2009-11-20 00:00:00 |
    |  7 | Muffy    |   2060 | 2008-05-20 00:00:00 |
    +----+----------+--------+---------------------+
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.


Left Outer Join  in  SQL?
Employee table
LastNameDepartmentID
Rafferty31
Jones33
Heisenberg33
Robinson34
Smith34
WilliamsNULL
Department table
DepartmentIDDepartmentName
31Sales
33Engineering
34Clerical
35Marketing



















SELECT *
FROM employee 
LEFT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID;
Employee.LastNameEmployee.DepartmentIDDepartment.DepartmentNameDepartment.DepartmentID
Jones33Engineering33
Rafferty31Sales31
Robinson34Clerical34
Smith34Clerical34
WilliamsNULLNULLNULL
Heisenberg33Engineering33
The keyword OUTER is marked as optional (enclosed in square brackets), and what this means in this case is that whether you specify it or not makes no difference. Note that while the other elements of the join clause is also marked as optional, leaving them out will of course make a difference.
For instance, the entire type-part of the JOIN clause is optional, in which case the default is INNER if you just specify JOIN. In other words, this is legal:
SELECT *
FROM A JOIN B ON A.X = B.Y
Here's a list of equivalent syntaxes:
A LEFT JOIN B            A LEFT OUTER JOIN B
A RIGHT JOIN B           A RIGHT OUTER JOIN B
A FULL JOIN B            A FULL OUTER JOIN B
A INNER JOIN B           A JOIN B

Groupby Clause.
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
     GROUP BY NAME;
Order By Clause
SQL> SELECT * FROM CUSTOMERS
     ORDER BY NAME DESC;
Like Clause


SELECT FROM table_name
WHERE column LIKE '%XXXX%'
Top Clause
SQL> SELECT TOP 3 * FROM CUSTOMERS;
Distinct Keyword:
SELECT DISTINCT SALARY FROM CUSTOMERS
     ORDER BY SALARY;
Having Clause.
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;
subquery
SQL> SELECT * 
     FROM CUSTOMERS 
     WHERE ID IN (SELECT ID 
                  FROM CUSTOMERS 
                  WHERE SALARY > 4500) ;

Normalization of Database

Database Normalisation is a technique of organizing the data in the database. Normalization is a systematic approach of decomposing tables to eliminate data redundancy and undesirable characteristics like Insertion, Update and Deletion Anamolies. It is a multi-step process that puts data into tabular form by removing duplicated data from the relation tables.
Normalization is used for mainly two purpose,
  • Eliminating reduntant(useless) data.
  • Ensuring data dependencies make sense i.e data is logically stored.

Problem Without Normalization

Without Normalization, it becomes difficult to handle and update the database, without facing data loss. Insertion, Updation and Deletion Anamolies are very frequent if Database is not Normalized. To understand these anomalies let us take an example of Student table.
S_idS_NameS_AddressSubject_opted
401AdamNoidaBio
402AlexPanipatMaths
403StuartJammuMaths
404AdamNoidaPhysics

  • Updation Anamoly : To update address of a student who occurs twice or more than twice in a table, we will have to update S_Address column in all the rows, else data will become inconsistent.
  • Insertion Anamoly : Suppose for a new admission, we have a Student id(S_id), name and address of a student but if student has not opted for any subjects yet then we have to insert NULL there, leading to Insertion Anamoly.
  • Deletion Anamoly : If (S_id) 401 has only one subject and temporarily he drops it, when we delete that row, entire student record will be deleted along with it.

Normalization Rule

Normalization rule are divided into following normal form.
  1. First Normal Form
  2. Second Normal Form
  3. Third Normal Form
  4. BCNF

First Normal Form (1NF)

As per First Normal Form, no two Rows of data must contain repeating group of information i.e each set of column must have a unique value, such that multiple columns cannot be used to fetch the same row. Each table should be organized into rows, and each row should have a primary key that distinguishes it as unique.
The Primary key is usually a single column, but sometimes more than one column can be combined to create a single primary key. For example consider a table which is not in First normal form
Student Table :
StudentAgeSubject
Adam15Biology, Maths
Alex14Maths
Stuart17Maths
In First Normal Form, any row must not have a column in which more than one value is saved, like separated with commas. Rather than that, we must separate such data into multiple rows.
Student Table following 1NF will be :
StudentAgeSubject
Adam15Biology
Adam15Maths
Alex14Maths
Stuart17Maths
Using the First Normal Form, data redundancy increases, as there will be many columns with same data in multiple rows but each row as a whole will be unique.

Second Normal Form (2NF)

As per the Second Normal Form there must not be any partial dependency of any column on primary key. It means that for a table that has concatenated primary key, each column in the table that is not part of the primary key must depend upon the entire concatenated key for its existence. If any column depends only on one part of the concatenated key, then the table fails Second normal form.
In example of First Normal Form there are two rows for Adam, to include multiple subjects that he has opted for. While this is searchable, and follows First normal form, it is an inefficient use of space. Also in the above Table in First Normal Form, while the candidate key is {StudentSubject}, Age of Student only depends on Student column, which is incorrect as per Second Normal Form. To achieve second normal form, it would be helpful to split out the subjects into an independent table, and match them up using the student names as foreign keys.
New Student Table following 2NF will be :
StudentAge
Adam15
Alex14
Stuart17
In Student Table the candidate key will be Student column, because all other column i.e Age is dependent on it.
New Subject Table introduced for 2NF will be :
StudentSubject
AdamBiology
AdamMaths
AlexMaths
StuartMaths
In Subject Table the candidate key will be {StudentSubject} column. Now, both the above tables qualifies for Second Normal Form and will never suffer from Update Anomalies. Although there are a few complex cases in which table in Second Normal Form suffers Update Anomalies, and to handle those scenarios Third Normal Form is there.

Third Normal Form (3NF)

Third Normal form applies that every non-prime attribute of table must be dependent on primary key, or we can say that, there should not be the case that a non-prime attribute is determined by another non-prime attribute. So this transitive functional dependency should be removed from the table and also the table must be in Second Normal form. For example, consider a table with following fields.
Student_Detail Table :
Student_idStudent_nameDOBStreetcityStateZip
In this table Student_id is Primary key, but street, city and state depends upon Zip. The dependency between zip and other fields is called transitive dependency. Hence to apply 3NF, we need to move the street, city and state to new table, with Zip as primary key.
New Student_Detail Table :
Student_idStudent_nameDOBZip
Address Table :
ZipStreetcitystate

The advantage of removing transtive dependency is,
  • Amount of data duplication is reduced.
  • Data integrity achieved.

Boyce and Codd Normal Form (BCNF)

Boyce and Codd Normal Form is a higher version of the Third Normal form. This form deals with certain type of anamoly that is not handled by 3NF. A 3NF table which does not have multiple overlapping candidate keys is said to be in BCNF. For a table to be in BCNF, following conditions must be satisfied:
  • R must be in 3rd Normal Form
  • and, for each functional dependency ( X -> Y ), X should be a super Key.
BCNF Normal Form

What  is SQL injection?
If you take user input through a webpage and insert it into a SQL database, there's a chance that you have left yourself wide open for a security issue known as SQL Injection.
Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a SQL statement that you will unknowingly run on your database.

JDBC

-JDBC Bridge
-JDBC Connection
-JDBC Statement
-Statement vs Prepared Statement
-Result Set vs Cached Result Set
-JNDI
-Connection Polling
-What  is Java realm..?

Collections API

difference between Collection and Collections?
What  is the difference  bw  HashTable and HashMap..?
difference between ArrayList and Vector?
ArrayList and LinkedList?
difference between Iterator and Listlterator?
difference between Iterator and Enumeration?
difference between List and Set?
difference between HashSet and TreeSet?
difference between Set and Map?
difference between HashSet and HashMap?
difference between HashMap and TreeMap?

difference between HashMap and Hashtable?
difference between Comparable and Comparator?
advantage  of  Properties file?
What does the hashCode() method?
Why we override equals() method?
How  to synchronize List, Set and Map elements?
advantage  of  generic collection?
What is  hash  -collision  in  Hashtable and how it  is  handled  in  Java?
What is the Dictionary class?

Spring

When  Spring introduce? is it EE solution?
The first milestone release, 1.0, was released in March 2004, Spring 2.0 was released in October 2006, 
No,Spring always depended on Java EE
Spring was and has always been a wrapper over core middleware infrastructure: ORM, Transactions, Messaging, HTTP.  It always depended core Java EE specs like JPA, JTA, JMS, and Servlet.  So, since you couldn’t deploy a Spring app without at least one of these core technologies/specifications, Java EE stayed in users minds.  There was always the opportunity that Java EE could get its act together in component model development.  While Rod Johnson always tried to position Spring as a Java EE alternative and JBoss killer, the Spring “platform” was never a true alternative to Java EE and JBoss, and in fact, couldn’t really exist without it.  IMO, this was a huge missed opportunity for the Spring folks.
Benefits  of  Spring  framework,  Why not Struts ,JSF ?
 JSF 2 (Java Server Faces 2) is a component-based, Web development framework. JSF follows an event-driven programming model. but The Spring Framework is open sourceLike Struts, Spring MVC is a request-based framework. (Find more detail)

What are the module  in  Spring?
The Spring Framework consists of features organized into about 20 modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, Messaging, and Test, as shown in the following diagram
spring overview
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/overview.html


What  is  the loC and  Dl?  both are same or different? How?


he Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.
For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:
public class TextEditor
{
    private SpellChecker checker;
    public TextEditor()
    {
        this.checker = new SpellChecker();
    }
}
What we've done here is create a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:
public class TextEditor
{
    private ISpellChecker checker;
    public TextEditor(ISpellChecker checker)
    {
        this.checker = checker;
    }
}
Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the TextEditor with the dependency.
The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container.  org.springframework.beans.factory.BeanFactory Interface is the central IoC container interface in Spring.
In JAVA, there are several basic techniques to implement inversion of control. These are:
  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection

Differentiating with dependency injection

Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. Inversion of control relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality.

What are the Types  of  Injections  in  Spring?


  • a constructor injection
  •     public class TestSetter {
        DemoBean demoBean = null;
        public void TestSetter () {
            this.demoBean = new DemoBean();
        }
    }
  • a setter injection: Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
  •     public class TestSetter {
        DemoBean demoBean = null;
        public void setDemoBean(DemoBean demoBean) {
            this.demoBean = demoBean;
        }
    }
  • an interface injection:In this methodology we implement an interface from the IOC framework. IOC framework will use the interface method to inject the object in the main class. It is much more appropriate to use this approach when you need to have some logic that is not applicable to place in a property. Such as logging support.
    public void SetLogger(ILogger logger)
    {
      _notificationService.SetLogger(logger);
      _productService.SetLogger(logger);
    }

http://howtodoinjava.com/2013/03/19/inversion-of-control-ioc-and-dependency-injection-di-patterns-in-spring-framework-and-related-interview-questions/
See the interview question here..
Which is better constructor injection or setter injection?
My preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems starts.

What  is  the difference between constructor injection  and  setter injection?
See above

BeanFactory  vIs  Application  context?
In short, the BeanFactory provides the configuration framework and basic functionality, and the ApplicationContext adds more enterprise-specific functionality. TheApplicationContext is a complete superset of the BeanFactory,

BeanFactory


A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
 Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.

What  is  the role  of IOC  container  in  spring?
The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application
Spring IoC Container
Spring provides following two distinct types of containers.
1Spring BeanFactory Container
2Spring ApplicationContext Container

Interview Question Found on internet

Qns-1: Which packages is the basis of Spring IoC container?
Ans: a. org.springframework.beans b. org.springframework.context
Qns-2: What is the role of BeanFactory in Spring IoC container?
Ans: BeanFactory provides the configuration mechanism so that any type of object can be managed easily.
Qns-3: What is the role of ApplicationContext in Spring IoC container?
Ans: ApplicationContext extends BeanFactory. ApplicationContext helps to integrate other module like Spring AOP, messages resource , event publication, application-layer specific contexts.
Qns-4: How can we instantiate ApplicationContext in standalone application?
Ans: We need to call ClassPathXmlApplicationContext or FileSystemXmlApplicationContext.
      ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
Message message = (Message) applicationContext.getBean("message");

        logger.debug("message='" + message.getMessage() + "'");
ApplicationContext context = new FileSystemXmlApplicationContext(“bean.xml”);
Qns-5: What are the variants of dependency Injection?
Ans: There are two variants of Dependency Injection.
a. Constructor-based dependency injection
b. Setter-based dependency injection
Qns-6: What are disadvantages of autowiring in Spring?
Ans: a. We cannot autowire primitives dat type, String and Classes.
b. Autowiring is not so exact as explicit wiring.
c. Autowiring will not be available for those tools that will generate documentation.
Qns-7: How many beans scopes are there in Spring IoC Container?
Ans: There are five Bean scopes.
singletonThis scopes the bean definition to a single instance per Spring IoC container (default).
prototypeThis scopes a single bean definition to have any number of object instances.
requestThis scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
sessionThis scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-sessionThis scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
<bean id="..." class="..." scope="prototype">// or singleton
   <!-- collaborators and configuration for this bean go here -->
</bean>
http://www.tutorialspoint.com/spring/spring_bean_scopes.htm
Qns-8: How to customize the nature of a bean?
Ans: a. Lifecycle callbacks can be customized by implementing interface InitializingBean and DisposableBean.
b. Startup and shutdown callbacks can be customized by implementing interface Lifecycle.
c. Use ApplicationContextAware and BeanNameAware.
Qns-9: What is the role of BeanPostProcessor Interface?
Ans: Implementing BeanPostProcessor interface, we can write our own bean instantiation logic.
Qns-10: What is the role of PropertyPlaceholderConfigurer in spring?
Ans: PropertyPlaceholderConfigurer externalize property values from a bean definition to another separate file.

In which scenario, you will use singleton and prototype scope?
 In singleton scope, no matter how many times you retrieve it with getBean(), it will always return the same instance. In prototype scope, you will have a new instance for each getBean() method called. 

What are the transaction management supports provided by spring?
Spring supports two types of transaction management:
Programmatic transaction management: This means that you have manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
  • getTransaction,commit, rollback.
What are the advantages ofJdbcTemplate  in  spring?
Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of JDBC API.
The Advantages of JDBC API are as follows:
  • We need not to write a lot of code before and after executing the query, such as creating connection, statement, closing resultset, connection etc.
  • We need not to perform exception handling code on the database logic.
  • We need not  to handle transaction.
  • easy to switch the database
in application Context we have to write just these things
  1. <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  2. <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
  3. <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
  4. <property name="username" value="system" />  
  5. <property name="password" value="oracle" />  
  6. </bean>    
  7. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  8. <property name="dataSource" ref="ds"></property>  
  9. </bean>    
  10. <bean id="edao" class="com.javatpoint.EmployeeDao">  
  11. <property name="jdbcTemplate" ref="jdbcTemplate"></property>  
  12. </bean>  

What are classes for spring JDBC  API?

How  can you fetch records by spring JdbcTemplate?

What  is  the advantage  of  NamedParameterJdbcTemplate?
What  is  the advantage  of  SimpleJdbcTemplate?

AOP

What  is  AOP?
What are the advantages  of  spring  AOP?
What are the  AOP  terminology?
What  is  JoinPoint?
What  is  Advice?
What are the types of advice  in  AOP?
What  is  Pointcut?
What  is  Aspect?
What  is  Introduction?

What is  target object?
What is interceptor?
What is weaving?
Does spring perform weaving at compile time?
What are the AOP implementation?

MVC

What is the front controller class of Spring MVC?
What does @Controller annotation?
What does @RequestMapping annotation?
What does the ViewResolver class?

Web Services

What is WSDL?
What is PortType in WSDL?
Can you explain the structure of a SOAP Message?

Threads

What is Thread in java?
What is thread  safety.?
Difference between Thread and Process?
Advantages  of  Thread?
How  many ways to create Thread in Java?
What is thread life cycle..?

What are the states  of  Thread?


Web Services

What is WSDL?
What is PortType in WSDL?
Can you explain the structure of a SOAP Message?
Threads
What is Thread in Java?
What is thread safety.?
Difference between Thread and Process?
Advantages of Thread?
How many ways to create Thread in Java?
What is thread life cycle..?
What are the states of Thread?
Yield  Ws  sleep?
wait  Ws  sleep?
notify  Ws  notifyall?
Can you explain synchronization..?

EJB

What are the types of EJB..?
Please Explain Java Bean, ManagedBean and BackingBean..?
What is the difference bw Stateless and Stateful EJB..?
What is the difference bw (Locale and (Remote in EJB..?

JSF

What is JSF life cycle..?
What are JSF Phases..?

Struts


What is difference between struts  1  and 2?


Quick problem

Check if the input data is palindrome


Miscellaneous question

Why is clone() method in Object protected?
How to prevent Singleton class to be cloneable?

Thread question reference(Bao)
http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/
(Nitesh)
what implicit objects are supported by JSP?
How would you swap values of 2 variables without using temp variable?
Can class be synchronized in java?
A whole bunch of questions regarding collection API
What are types of JSP directives?
Difference between DI and IOC?
Java Heap, Perm gen space questions

Agile Engine Technical questions ...
(bolkhu)

1. What is the Deadlock?
2. U have multithreading. How will you call other thread ... ? /something like that/
3. Name Spring Bean Scopes?
4. About LazyInitializationException, how to solve it?
5. What do you use for concatenating large amount String ?
Forgot some of them, generally started with few multithread questions and we shifted to Spring, Hibernate.

Comments

Popular posts from this blog

ifference between @RestController and @Controller

Difference between @RestController and @Controller Annotation in Spring MVC and REST Read more:  http://javarevisited.blogspot.com/2017/08/difference-between-restcontroller-and-controller-annotations-spring-mvc-rest.html#ixzz4sbGy2Glh The  @RestController  annotation in Spring MVC is nothing but a combination of  @Controller  and  @ResponseBody  annotation. It was added into Spring 4.0 to make the development of RESTful Web Services in Spring framework easier. If you are familiar with the  REST web services  you know that the fundamental difference between a web application and a REST API is that the response from a web application is generally view (HTML + CSS + JavaScript) while REST API just return data in form of JSON or XML. This difference is also obvious in the  @Controller  and  @RestController  annotation. The job of  @Controller  is to create a Map of model object and find a view but  @RestContr...

Presentation topics

Topics for presentation : Knockout.js, Angular.js, Node,js, Kendo UI, MVC 4, Nuget, Ninject, Unity Framework, Dependency Injection , PMC Package Manager Control, Mordenizer, Moq, Json, Html5, Entity Framework code1st. Spring.net Castle Windsor , Structure Map and Microsoft Unity ,
What happens when you compile/run the following code: class MyClass { public static void main(String[] args) { new MyClass(); } Ans: It executes and create a object for that class without reference. The output of the program is nothing.