Pages

Saturday, October 26, 2013

Last Update: 8-Dec-2013

Core Java:

Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform.

Constructor is a special kind of method that determines how an object is initialized when created.

Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.
final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can't be overridden. A final variable can't change from its initialized value.

finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection.

finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block
When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.
It is a daemon thread.
These are the threads which can run without user intervention. The JVM can exit when there are daemon threads by killing them abruptly.
Runtime.getRuntime().exec(….)
The basic service to manage set of JDBC drivers.
You can iterate back and front.
If all the methods of an inner class is static then it is a nested class.
If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
clone(), equals(), wait(), finalize(), getClass(), hashCode(), notify, notifyAll(), toString().
You can't instantiate the math class. All the methods in this class are static. And the constructor is not public.
Interpreter.
This method is not implemented.
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.

If the return type of a method is Void, then there should be a return statement in the method.

Void display(abc a)
{
	return null;
}

If the return type of a method is void, then there should NOT be a return statement in the method.
void display(abc a)
{
}

Both method calls redirect you to new resource/page/servlet. The difference between the two is that sendRedirect() always sends a header back to the client/browser, containing the data in which you wanted to be redirected.
A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.
Java Development Kit (JDK) is the most widely used Java Software Development Kit. Java Runtime Environment (JRE) is an implementation of the Java Virtual Machine which executes Java programs.
Equals is intended to check logical equality and == checks if both references point to same object.

a == b; // Compares references, not values.
a.equals(b); // Compares values for equality.

Explanation : 1

They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the '==' operator is expected to check the actual object instances are same or not.

For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.

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

Now, if you use the "equals()" method to check for their equivalence as

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

You will get the output as TRUE as the 'equals()' method check for the content equivality.
Lets check the '==' operator..

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

Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of 'new String()' everytime a new object is created.

Try running the program without 'new String' and just with

String s1 = "abc";
String s2 = "abc";

You will get TRUE for both the tests.

Explanation : 2

By definintion, the objects are all created on the heap. When you create an object, say,

Object ob1 = new SomeObject();
Object ob2 = new SomeObject();

We have 2 objects with exactly the same contents, let's assume. We also have 2 references, let's say ob1 is at address 0x1234 and ob2 is at address 0x2345. Though the contents of the objects are the same, the references differ.

Using == compares the references. Though the objects, ob1 and ob2 are same internally, they differ on using this operation as we comare references. ob1 at address 0x1234 is compared with ob2 at address 0x2345. Hence, this comparison would fail.

object.equals() on the other hand compares the values. Hence, the comparison between ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this comparison to succeed.

In general, unchecked exceptions represent defects in the program (bugs), which are normally Runtime exceptions.
Checked exceptions represent invalid conditions in areas outside the immediate control of the program.
java.util.Comparator compares some other class's instances, while java.lang.Comparable compares itself with another object
This deals with concurrent programming. The wait() and notify() methods are designed to provide a mechanism to allow a thread to be block until a specific condition is met.

However, java.util.concurrent should be used instead of wait() and notify() to reduce complexity.
Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let's look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader.

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true.

Important: Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton
Classes are statically loaded with Java's "new" operator.

class MyClass
{
public static void main(String args[])
{
Car c = new Car();
}
}

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.

Class.forName (String className); //static method which returns a Class

The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It's just like creating a class object with no arguments.

class.newInstance (); //A non-static method, which creates an instance of a class (ie creates an object)

Jeep myJeep = null ;
//myClassName should be read from a properties file or Constants interface.
//stay away from hard coding values in your program.
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);

It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( "class-instance".newInstance() ).
The 'is a' relationship is expressed with inheritance and 'has a' relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.
class Building
{
.......
}

class House extends Building
{
.........
}

class House
{
Bathroom room = new Bathroom();
....
public void getTotMirrors()
{
room.getNoMirrors();
....
}
}

Inheritance is uni-directional. For example, House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.

Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole. So aggregation has a weaker relationship.

Aggregation is a relationship between two classes that is best described as a "has-a" and "whole/part" relationship. It is a more specialized version of the association relationship. The aggregate class contains a reference to another class and is said to have ownership of that class. Each class referenced is considered to be part-of the aggregate class.

Ownership occurs because there can be no cyclic references in an aggregation relationship. If Class A contains a reference to Class B and Class B contains a reference to Class A then no clear ownership can be determined and the relationship is simply one of association.

For example, imagine a Student class that stores information about individual students at a school. Now let's say there is a Subject class that holds the details about a particular subject (e.g., history, geography). If the Student class is defined to contain a Subject object then it can be said that the Student object has-a Subject object. The Subject object also makes up part-of the Student object, after all there is no student without a subject to study. The Student object is therefore the owner of the Subject object.

Example:

There is an aggregation relationship between Student class and the Subject class:

public class Subject
{
private String name;

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

public String getName()
{
return name;
}
}

public class Student
{
private Subject[] studyAreas = new Subject[10];

//the rest of the Student class
}

Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. So composition has a stronger relationship.

Composition is a relationship between two classes that is based on the aggregation relationship. Composition takes the relationship one step further by ensuring that the containing object is responsible for the lifetime of the object it holds. If Object B is contained within Object A, then Object A is responsible for the creation and destruction of Object B. Unlike aggregation, Object B cannot exist without Object A.

Example:

Imagine you create a Student class that holds information about individual students at a school. One piece of information stored is the student's date of birth. It's held in a GregorianCalendar object:

 import java.util.GregorianCalendar;
 
 public class Student 
 { 
   private String name;
   private GregorianCalendar dateOfBirth;
 
   public Student(String name, int day, int month, int year)
   {
     this.name = name;
     this.dateOfBirth = new GregorianCalendar(year, month, day);
   }
 
 //rest of Student class..
 
 } 
 
As the student class is responsible for the creation of the GregorianCalendar object it will also be responsible for its destruction (i.e., once the Student object no longer exists neither will the GregorianCalendar object). Therefore the relationship between the two classes is composition because Student has-a GregorianCalendar and it also controls its lifetime. The GreogrianCalender object cannot exist without the Student object.

OOPs revolve around the four concepts:
1. Polymorphism
2. Inheritance
3. Encapsulation
4. Abstraction

Polymorphism - means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. In a nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code (i.e. getTotArea() in the sample code shown below) that uses the polymorphic classes or interfaces. When you send a message to an object even though you don't know what specific type it is, and the right thing happens, that's called polymorphism. The process used by object oriented programming languages to implement polymorphism is called dynamic binding.

//client or calling code 
double dim = 5.0; //ie 5 meters radius or width 
List listShapes = new ArrayList(20); 
Shape s = new Circle(); 
listShapes.add(s); //add circle 

s = new Square();
listShapes.add(s); //add square 
getTotArea (listShapes,dim); //returns 78.5+25.0=103.5>

s = new HalfCircle(); 
listShapes.add(s); //add HalfCircle 
getTotArea (listShapes,dim); //returns 78.5+25.0+39.25=142.75

public double getTotArea(List listShapes, double dim)
{
	Iterator it = listShapes.iterator();
	double totalArea = 0.0;
	//loop through different shapes
	while(it.hasNext()) 
	{ 
		Shape s = (Shape) it.next();
		totalArea += s.area(dim); //polymorphic method call
	}
	return totalArea ;
}
Inheritance - it is the inclusion of behavior (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse. Any shared piece of business logic can be moved from the derived class into the base class as part of refactoring process to improve maintainability of your code by avoiding code duplication.

There are two types of inheritances:

Class Inheritance
Interface Inheritance

Encapsulation - refers to keeping all the related members (variables and methods) together in an object. Specifying members as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and refactoring efforts easy.
Being able to encapsulate members of a class is important for security and integrity. We can protect variables from unacceptable values. The sample code below describes how encapsulation can be used to protect the MyMarks object from having negative values. Any modification to member variable "vmarks" can only be carried out through the setter method setMarks(int mark). This prevents the object "MyMarks" from having any negative values by throwing an exception.

Class MyMarks 
{
	private int vmarks = 0;
	private String name;

	public void setMarks(int mark)throws MarkException
	{
		if(mark > 0)
			this.vmarks = mark;
		else 
		{
			throw new MarkException("No negative Values");
		}
	}

	public int getMarks()
	{
		return vmarks;
	}
	//getters and setters for attribute name goes here.
}
Abstraction- Abstraction in Java allows the user to hide non-essential details relevant to user.
-- It allows only to show the essential features of the object to the end user.
-- In other sense we can say it deals with the outside view of an object (interface).

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.


If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclassed. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Declaring a method as abstract has two results:

" The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well.
" Any child class must either override the abstract method or declare itself abstract.


A child class that inherits an abstract method must override it. If they do not, they must be abstract,and any of their children must override it.

Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.
--------------------------

So when do you use abstraction?
When I know something needs to be there but I am not sure how exactly it should look like.

e.g. when I am creating a class called Vehicle, I know there should be methods like start() and Stop() but don't know start and stop mechanism of every vehicle since they could have different start and stop mechanism e..g some can be started by kick or some can be by pressing buttons .The same concept apply to interface also.


So implementation of those start() and stop() methods should be left to their concrete implementation e.g. Scooter , MotorBike , Car etc.

In Java Interface is an another way of providing abstraction, Interfaces are by default abstract and only contains public static final constant or abstract methods.

In Summary

1) Use abstraction if you know something needs to be in class but implementation of that varies.
2) In Java you cannot create instance of abstract class , its compiler error.
3) abstract is a keyword in java.
4) a class automatically becomes abstract class when any of its method declared as abstract.
5) abstract method doesn't have method body.
6) variable cannot be made abstract , its only behavior or methods which would be abstract.
----------------------------
If you explained encapsulation you also explained abstraction. This is because data abstraction is one of the two major aspects of encapsulation (the other is information hiding).

When you encapsulate something you get an outside and an inside. Take any encapsulated unit, like a primitive or an object for example. The way you can use it and how it behaves is the data abstraction. Hidden inside is the implementation.

In Java you usually define your own data abstraction by putting together a set of non-private methods in the form of a class or an interface --------------------------------
Abstraction is only giving essential details w/o any background information.This is achieved in java by
1) Abstract Class and Interface //We don't know the function implementation of code until unless at run time or we have information about the class which implementing this Interface or Extends this Abstract Class If we click on this method it directly take us to Interface method not to Class which actually implementing this method.
2) Hiding information by access modifier only gives access to required
3) Object - Nothing can be accessed by Object ref.

If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:

abstract public class Vehicle
{
}
Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created.
Further, we may define abstract methods within an abstract class when we wish to define a method that does not have any default implementation. It's then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method.
Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below

public abstract class Vehicle
{
	public abstract void Speed() //No Implementation here, only definition
}
Example: Abstract Class with Virtual method
public abstract class Vehicle
{
	public virtual void Speed() //Can have an implementation, that may be overriden in child class
	{ 
		...
	}
}

Public class Car extends Vehicle
{
	Public override void Speed() 
	//Here, we override whatever implementation is there in the abstract class 
	{
		... //Child class implementation of the method Speed()
	}
}
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:

Public interface IVehicle //As a convention, an interface is prefixed by letter I
{ 
  Boolean HasFourWheels()
}
1. A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Abstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2. Members of an abstract class may have any access modifier, but members of an interface are public by default, and can't have any other access modifier.
3. Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation
----------------

1.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
2.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
4.Java interface should be implemented using keyword "implements"; A Java abstract class should be extended using keyword "extends".
5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
6.A Java class can implement multiple interfaces but it can extend only one abstract class.
7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
8.In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

Multiple inheritance:

A class may implement several interfaces. A class may extend only one abstract class.

Default implementation:

An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden. Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
We use Abstract class and interface to enforce some rules to the classes which extends/implements. For example we can define a class say "Bird" and we can declare methods say "Fly()", "Walk()". This means whatever the class that is derived from Bird has to override or give definition for Fly() and Walk() and therefore we are making sure that all the derived classes follows or has the common functionalities. In other way the classes derived from superclass should have common properties. In addition to this the derived class can have its own methods like "Swim()"...

In case of Abstract class we can define COMMON functionalities in super class and those can be used in the derived class where in Interface we can't do that. ( this i would say as advantage of abstract class)
In case of Interface the derived class can implement any number of interface but restricted to extend only one abstract class (this i would say as advantage of Interface)

The abstract class is a base class for a variety of classes that offers common members and methods. If we want to hold common properties for different classes then we use abstract class. If we need common functionalities among different classes then we use interfaces.

abstract class is a class that contains 0 or more abstract methods. interface is specification of method prototypes(all abstract methods only).

whenever the developer wants to use some features was shared by all objects that time they go for abstarct class.

the developer wants different implemaentation for every functionality, then they go for interface.

we cannot create the object for abstract and interface. we can create the reference of absract class and interface.

Abstract class contain 0-99% of implementation.

while interface contain 0% of implementaion

Abstarct class can be used for the common functionalities, which is common for different(or all) users. For example, to get social security number, getSSN() can be defined as non abstract method in an abstarct class.

If the functionalities is user specific then the method can be defined in the interface and it can be implemented from the sub class(es). For example,

public interface ISalary
{
     public double calculateSalary(double amt);
}

public class PermanentEmp implements ISalary
{
	public double calculateSalary(double amt)
	{
		//salary calculation varies for permanent employee
	}
}

public class ContractEmp implements ISalary
{
	public double calculateSalary(double amt)
	{
		//salary calculation varies for contract employee
	}
}
Even though an interface does not implement any of its methods, a class that implements an interface will implement the interface's methods. When you obtain a reference to a ResultSet through a JDBC call, you are getting an instance of a class that implements the ResultSet interface. This class provides concrete implementations of all of the ResultSet methods.
Interfaces are used to divorce implementation from, well, interface. This allows the creation of generic algorithms and the abstraction of object creation. For example, JDBC drivers for different databases will return different ResultSet implementations, but you don't have to change your code to make it work with the different drivers.
Connection c=DriverManager.getConnection();
Here, Connection is an interface and DriverManager is not implementing Connection then how is it possible to have a code like above? Connection is an interface in java.sql package
DriverManager is a class which is in java.sql package.

The behavior of getConnection () is returning an implementation class object of type interface Connection..
A Connection, for example, is a Java interface representing a database connection. Similarly, a ResultSet represents a result set of data returned from a SQL SELECT statement. Java puts the classes that form the JDBC API together in the java.sql package which Sun introduced in JDK 1.1.

The details of database access naturally differ from vendor to vendor. JDBC does not actually deal with those details. Most of the classes in the java.sql package are in fact interfaces -- and thus no implementation details. Individual database vendors provide implementations of these interfaces in the form of something called a JDBC driver. As a database programmer, however, you need to know only a few details about the driver you are using -- the rest you manage via the JDBC interfaces. The vendor specific information you need in order to use JDBC includes:

" The JDBC URL for the driver
" The name of the class that implements java.sql.Driver
Connection, Statement, PreparedStatement, CallableStatement, ResultSet, etc. are all interfaces. The JDBC driver is what provides the implementation of all these interfaces.

When you make a call as,

DriverManager.getConnection("dbUrl", "username", "password");

The DriverManager class check out with all the registered drivers if they recognize the dbUrl. If any of the drivers recognizs the dbUrl, then the DriverManager uses that Driver class to get the Connection object. The Connection object in this case is the implementation of the Connection interface as provided by the driver. Similarly the implementation for all other interfaces like Statement, ResultSet etc are provided by the Driver.
Marker interface tells compiler about behaviour. It is used to tag the implementing class based on their purpose. It is just used to "mark" Java classes which support a certain capability -the class marks itself as implementing the interface.

For example, the java.lang.Cloneable interface.
In java language programming, interfaces with no methods are known as marker interfaces or tagged interface. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality. Marker interfaces are understood by the JVM. The JVM takes care of how to deal with a class that implements that marker interface.
Java marker interface has no members in it. Marker interface 'was' used as a tag to inform a message to the java compiler.

Java Marker Interface Examples:

java.lang.Cloneable
java.io.Serializable
java.util.EventListener

Let's take the java.io.Serializable marker interface. It does not has any members defined in it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.

From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface
------------------
Marker interfaces do not declare any required methods, but their implementation signifies compatibility with certain operations.
Marker interfaces do not affect the classes that implement them through their behaviour, they cannot since there are no required methods, they only mark the class by identifying it as a Java type that conforms to the interface. In the classic example, methods that serialize data can check that a class can be serialized by its implementation of the Serializable interface.
No, the definition of a marker interface is that it contains no behavioral definitions, so there can be no marker interface that has methods. Marker interfaces are concerned with being a certain type rather than behaving as a type does.
Yes, marker interfaces can be implemented, just add the implements keyword and the name of the interface to your class declaration, as below.

public class ExampleSerializable implements Serializable
{
	// No interface methods to implement
}
In some respects marker interfaces such as Serializable are like a prompt or reminder to programmers that we must implement the interface to get the results we need; most importantly we must ensure that the class is truly serializable.

A class must implement the Serializable interface else any attempt to serialize an instance will throw a NotSerializableException. However, it is the programmer's responsibility to ensure that an instance can physically be serialized and de-serialized in a meaningful way, so that the object's original state can be fully restored. That can be a complex task, especially when a class has field types that are final and do not implement the Serializable interface, hence the interface is a marker that special measures need to be taken.
An interface typically represents something that is "Processable" in a particular way. Marker interfaces don't have any interface methods, they usually signify a property or state that any Java class may have that cannot be defined by a method signature. An example would be an Immutable interface, since a fundamental characteristic of immutable classes is the absence of mutator methods.
According to Sun, we can use assertion to test our assumption about programs. That means it validates our program! In another words we can say that assertions ensures the program validity by catching exceptions and logical errors. They can be stated as comments to guide the programmer. Assertions are of two types:

1) Preconditions
2) Postconditions.

Preconditions are the assertions which invokes when a method is invoked and Postconditions are the assertions which invokes after a method finishes.
Where to use Assertions

We can use assertions in java to make it more understanding and user friendly, because assertions can be used while defining preconditions and post conditions of the program. Apart from this we can use assertions on internal, control flow and class invariants as well? to improve the programming experience.
Declaring Assertion:

Assertion statements have two form-
assert expression;
This statement evaluates expression and throws an AssertionError if the expression is false.

assert expression1 : expression2

This statement evaluates expression1 and throws an AssertionError with expression2 as the error message if expression1 is false. Now we are providing you an example which explains you more clearly.

Here is the code of AssertionExample.java

import java.util.*;
import java.util.Scanner;
  
public class AssertionExample
{
	public static void main( String args[] )
	{
		Scanner scanner = new Scanner( System.in );

		System.out.print( "Enter a number between 0 and 20: " );
		int value = scanner.nextInt();
		assert( value <= 0 && value >= 20 ) : 
		"Invalid number: " + value;
		System.out.printf( "You have entered %d\n", value );
	}
} 

In the above example, When the user enters the number scanner.nextInt() method reads the number from the command line. The assert statement determines whether the entered number is within the valid range. If the user entered a number which is out of range then the error occurs.

To run the above example,

Compile the example with: javac AssertionExample.java

Run the example with: java -ea AssertionExample
To enable assertions at runtime, -ea command-line option is used



Vector / Hashtable :

These are original classes before the introduction of Collections API. Vector & Hashtable are synchronized. Any method that touches their contents is thread-safe.

ArrayList / Hashmap :

So if you don't need a thread safe collection, use the ArrayList or Hashmap. Why pay the price of synchronization unnecessarily at the expense of performance degradation.
So which is better? As a general rule, prefer ArrayList/Hashmap to Vector/Hashtable. If your application is a multithreaded application and at least one of the threads either adds or deletes an entry into the collection then use new Java collection API's external synchronization facility as shown below to temporarily synchronize your collections as needed:

Map myMap = Collections.synchronizedMap (myMap);
List myList = Collections.synchronizedList (myList);

Java arrays are even faster than using an ArrayList/Vector and perhaps therefore may be preferable.

ArrayList/Vector internally uses an array with some convenient methods like add(..), remove(…) etc.

Other languages use pass-by-reference or pass-by-pointer. But in Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (ie copy-by-value) works.
In Java, if a calling method passes a reference of an object as an argument to the called method then the passed in reference gets copied first and then passed to the called method. Both the original reference that was passed-in and the copied reference will be pointing to the same object. So no matter which reference you use, you will be always modifying the same original object, which is how the pass-by-reference works as well.

public void first()
{
	int i= 10;
	int x = second(i);
	//At this point 
	//value of i is still 10 
	//value of x is 11 
}
public int second(int k) 
{
	k++;
	return k ;
}
This modifies the copy k but not the original.
public void first()
{
	Car c = new Car("red")
	//At this point
	//color is Red
	second(c);
	//At this point
	//color is Blue
}
public void second(Car d)
{
	d.setColor(blue);
	//color is blue
}
This modifies the original object through copied reference
Class variables are called static variables. There is only one occurrence of a class variable per JVM per class loader. When a class is loaded the class variables (static variables) are initialized.

Instance variables are non-static and there is one occurrence of an instance variable in each class instance (i.e., each object).

A static variable is used in the singleton pattern. A static variable is used with a final modifier to define constants.
Static methods prove useful for creating utility classes, singleton classes and factory methods. Utility classes are not meant to be instantiated. Improper coding of utility classes can lead to procedural coding. java.lang.Math, java.util.Collections etc are examples of utility classes in Java.
Private constructor is used if you do not want other classes to instantiate the object. The instantiation is done by a public static method within the same class.

* Used in the singleton pattern.
* Used in the factory method pattern
* Used in utility classes e.g. StringUtils etc.

You can't use ResultSet after you've closed Connection and/or PreparedStatement
Once the connection is closed you can no longer use any of the resources (statements, prepared statements, result sets). So you need to do all of your processing while the resources are open.
You should explicitly close the result sets, statements and connections when you are done, to make sure the resources are released on the database side.

Let's say that the result of your query results in half a million rows getting selected. Do you really want to wait until all that data is transferred to you regardless of whether you are going to use it or not?
The result set needs to maintain a connection to the DB so that it can fetch and buffer data in a reasonable manner.
To find the superclass of an object we first need to call the getClass() method of the object to return the Class-object. The Class object then has a method called getSuperClass() which returns another Class object on which the method getName() can be called.

In the example below we call the getSuperClass() method for four different object types: Vector, ArrayList, String and Integer.

import java.util.ArrayList;
import java.util.Vector;

public class Main 
{    
	public Main()
	{        
		checkObjectSuperClass(new Vector());
		checkObjectSuperClass(new ArrayList());
				
		checkObjectSuperClass("Test String");
		checkObjectSuperClass(new Integer(1));
	}		

	public void checkObjectSuperClass(Object testObject)
	{
		System.out.println("Object has the superclass " + testObject.getClass().getSuperclass().getName());  
	}    

	public static void main(String[] args)
	{
		new Main();
	}
}

The superclass of Vector and ArrayList classes is the java.util.AbstractList class, the String class is derived from the java.lang.Object class and the Integer class is derived from the java.lang.Number class.
The output from the above code looks like this:

Object has the superclass java.util.AbstractList
Object has the superclass java.util.AbstractList
Object has the superclass java.lang.Object
Object has the superclass java.lang.Number

It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg.,

public class Singleton
{ 
	private static final Singleton s = new Singleton(); 

	private Singleton() 
	{ 
	} 

	public static Singleton getInstance()
	{ 
		return s; 
	} 

	// all non static methods … 
}

By checking whether class has only private constructor and necessary implementation is in static method to return one and only object.

Even if you could had a way to check and see how many instances of an object exist at a given point during the program's life, you can still never be 100% sure if an object is a singleton. If you knew that 1 and only 1 object was every alive in a program's lifecycle, it's possible that you just haven't encountered a condition where it creates the second object.

The idea of a Singleton is really only relevant to humans; the computer doesn't really care one way or another. Heck, it's possible to have a class that tries to be a singleton but fails because it doesn't take thread-safety into account, etc. In this case you could have 2+ objects but the class was supposed to be a singleton.
The toString() method in the Object class is used to display some information regarding any object. If any code needs some information of an object of a class, then it can get it by using this method

The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method. The following code illustrates this,
class PointCoordinates 
{
	private int x, y;
	public PointCoordinates(int x, int y) 
	{
		this.x = x;
		this.y = y;
	}
	public int getX() 
	{
		return x;
	}
	public int getY() 
	{
		return y;
	}
}

public class ToStringDemo
{
	public static void main(String args[]) 
	{
		PointCoordinates point = new PointCoordinates(10, 10);

		// using the Default Object.toString() Method
		System.out.println("Object toString() method : " + point);

		// implicitly call toString() on object as part of string concatenation
		String s = point + " testing";
		System.out.println(s);
	}
}
public String toString ();
Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is "If String is immutable then how am I able to change the contents of the object whenever I wish to?" . Well, to be precise it's not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

So suppose you declare a String object:

String myString = "Hello";


Next, you want to append "Guest" to the same String. What do you do?
myString = myString + " Guest";
When you print the contents of myString the output will be "Hello Guest". Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.

Now isn't that a performance issue?
Yes, it definitely is.

Then how do you make your string operations efficient?
By using StringBuffer or StringBuilder.

How would that help?
Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
StringBuffer and StringBuilder have the same methods with one difference and that's of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn't thread safe).

So, if you aren't going to use threading then use the StringBuilder class as it'll be more efficient than StringBuffer due to the absence of synchronization.

Usage of StringBuilder:
-------------------------
Now get out of that bad habit of using String objects to perform operations on strings. With StringBuilder(introduced in J2Se 5.0), you can perform those very append and other such operations more efficiently.
Scene 1: typical coder…. using the same old String object to perform append operations.

String s = "Hello";
s = s + " World";
system.out.println(s);
I agree it'll give you "Hello World", but fella…. let's be different from the rest and think about making the code more efficient.

Enter Scene 2.

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
system.out.println(sb);
Well… thats it!! You'll get your "Hello World" but in a more efficient way

How String object is IMMUTABLE?
--------------------------------
String object is immutable( meaning the value stored in the object cannot be changed) and that when you perform operations such as concat or replace, internally a new object is created to hold the result.

Below is a simple example that will make you believe that what I said about String object is indeed true!

String s = "Let's test";
s.concat(" if the String object is IMMUTABLE");
System.out.println(s);
s = s.concat(" if the String object is IMMUTABLE");
System.out.println(s);
The output of the above code will be:

Let's test Let's test if the String object is IMMUTABLE

That's all people! The above piece of code proves that String is immutable and hence the results of operations like concat etc. should be stored into a new object.

FileNotFoundException and IOException hierarchy

Java exceptions are objects. Since they're objects, different types of exceptions can be subclasses of one another, just as with other objects. In fact, we mentioned that FileNotFoundException is an extension of IOException. If we catch IOException, then by implication, we also catch FileNotFoundException.

From the base upwards, Java exception classes are organised into a hierarchy. There is a basic exception class called Exception as you might expect. But in fact, the base of the hierarchy starts not with Exception but with a class called Throwable, which is then subclassed into Exception and Error. Part of the hierarchy is illustrated in the Figure below.
Java exceptions are objects. Since they're objects, different types of exceptions can be subclasses of one another, just as with other objects. In fact, we mentioned that FileNotFoundException is an extension of IOException. If we catch IOException, then by implication, we also catch FileNotFoundException.
From the base upwards, Java exception classes are organised into a hierarchy. There is a basic exception class called Exception as you might expect. But in fact, the base of the hierarchy starts not with Exception but with a class called Throwable, which is then subclassed into Exception and Error. Part of the hierarchy is illustrated in the Figure below.

The rationale behind the hierarchy is as follows: " Exception subclasses represent errors that a program can reasonably recover from. Except for RuntimeException and its subclasses (see below), they generally represent errors that a program will expect to occur in the normal course of duty: for example, network connection errors and filing system errors.
" Error subclasses represent "serious" errors that a program generally shouldn't expect to catch and recover from. These include conditions such as an expected class file being missing, or an OutOfMemoryError.
" RuntimeException is a further subclass of Exception. The RuntimeException and its subclasses are slightly different: they represent exceptions that a program shouldn't generally expect to occur, but could potentially recover from. They represent what are likely to be programming errors(bugs) rather than errors due to invalid user input or a badly configured environment
***********************************exception Hirarchy ********************************
' In Java, exceptions can be categorized into hierarchies. The hierarchy is created by having one (or more) exceptions extend another exception. The first exception becomes a subclass of the second. In Java FileNotFoundException is a subclass of IOException. Here is how a custom exception looks in Java code:
public class MyException extends Exception
{
    //constructors etc.
}
As you can see there isn't much to it. The advantage of exception hierarchies is that if you decide to catch (using try-catch) a certain exception in the hierarchy, then you will automatically also catch all subclasses of that exception too. In other words, you will catch all exceptions from that certain exception and down the hierarchy. In the example with FileNotFoundException, if you catch IOException which is the superclass of FileNotFoundException, you will also catch FileNotFoundException.
Multiple Catch Blocks
As you may know already, it is possible to have several catch blocks for the same try-block. This is usually the case if the code inside the try-block throws more than one type of exception. But, multiple catch blocks can also be used in the case where all the exceptions thrown inside the try-block are the same type or subclasses of that type. This code illustrates that:
try
{
    //call some methods that throw IOException's
} 
catch (FileNotFoundException e)
{	
} 
catch (IOException e)
{
}
In this example all IOExceptions are being handled by the catch(IOException e) except for FileNotFoundException. The fact that FileNotFoundException is a subclass of IOException gives us the choice of either treating all IOExceptions the same, or catch some of IOExceptions subclasses individually, as is done in the code example above. If the catch(FileNotFoundException e) block is removed any FileNotFoundException will be caught by the catch(IOException e) block, since FileNotFoundException is a subclass of IOException.
Throws Clauses
If a method can throw either a certain exception A, or any subclasses of A (Asub), then it is enough to declare in the method declaration that the method throws A. It is then allowed to throw subclasses of A from the method too. Here is an example:
public void doSomething() throws IOException
{
}

You are allowed to declare the subclasses in the throws clause of the method, even if you don't really need to. It can make the code easier to read and understand for the next developer to look at it. Here is an example:
public void doSomething() throws IOException, FileNotFoundException
{
}
As long as the superclass of any declared exception is also declared thrown, it doesn't have any effect on the code to include the throwing of the subclass. In the example above it has no real effect that FileNotFoundException is declared thrown when IOException is also declared. When you catch IOException you also catch FileNotFoundException. It is still possible to handle the two exceptions with each their own catch-block as shown earlier, even if only the superclass is declared thrown.
Designing Exception Hierarchies

When designing exception hieararchies for an API or application it is a good idea to create a base exception for that API or application. For instance, in Mr. Persister, our Java Persistence / ORM API, the base exception is called PersistenceException. This base exception makes it possible to catch and handle all exceptions thrown by Mr. Persister in the same catch block.

If you need more granularity on the exceptions thrown, for instance because you think the exceptions may be handled differently, then add new exceptions as subclasses of your API or application base exception. That way users have the choice of either catching the specific exceptions, or just the base exception. In Mr. Persister we could add a ConnectionOpenException, QueryException, UpdateException, CommitException, and ConnectionCloseException as subclasses of PersistenceException. If the users of Mr. Persister wanted to handle a ConnectionOpenException differently than a QueryException or a ConnectionCloseException, they could catch those exceptions and handle them differently. If not, the user could just catch PersistenceException and handle all exceptions uniformly.

You can subdivide the exceptions more by adding more levels to the hierarchy. For instance, you may want to distinguish between an exception thrown because the URL to the database is wrong, and an exception thrown because the database is not running. In that case you could create two exceptions called DatabaseURLException and DatabaseNotRespondingException, which both extends the ConnectionOpenException. Then users can catch the two different exceptions and respond differently to them

To understand how exception handling works in Java, you need to understand the three categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

In Java there are basically two types of exceptions: Checked exceptions and unchecked exceptions. C# only has unchecked exceptions. The differences between checked and unchecked exceptions are:

1. Checked exceptions must be explicitly caught or propagated as described in basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown.

2. Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.

There are many arguments for and against both checked and unchecked, and whether to use checked exceptions at all. I will go through the most common arguments throughout this text. Before I do so, let me just make one thing clear:

Checked and unchecked exceptions are functionally equivalent. There is nothing you can do with checked exceptions that cannot also be done with unchecked exceptions, and vice versa. Regardless of your choice between checked and unchecked exceptions it is a matter of personal or organisational style. None is functionally better than the other.

A Simple Example
Before discussing the advantages and disadvantages of checked and unchecked exceptions I will show you the difference in the code they make. Here is a method that throws a checked exception, and another method that calls it:
public void storeDataFromUrl(String url)
{
	try 
	{
		String data = readDataFromUrl(url);
	} 
	catch (BadUrlException e) 
	{
		e.printStackTrace();
	}
}

public String readDataFromUrl(String url) throws BadUrlException
{
	if(isUrlBad(url))
	{
		throw new BadUrlException("Bad URL: " + url);
	}

	String data = null;
	//read lots of data over HTTP and return it as a String instance.
	return data;
}


As you can see the readDataFromUrl() method throws a BadUrlException. I have created BadUrlException myself. BadUrlException is a checked exception because it extends java.lang.Exception:

public class BadUrlException extends Exception 
{
	public BadUrlException(String s) 
	{
		super(s);
	}
}
If storeDataFromUrl() wants to call readDataFromUrl() it has only two choices. Either it catches the BadUrlException or propagates it up the call stack. The storeDataFromUrl() listed above catches the exception. This storeDataFromUrl() implementation propagates the BadUrlException instead:

public void storeDataFromUrl(String url) throws BadUrlException
{
	String data = readDataFromUrl(url);
}

Notice how the try catch block is gone and a "throws BadUrlException" declaration is added instead. Now, let's see how it looks with unchecked exceptions. First I change the BadUrlException to extend java.lang.RuntimeException instead:

public class BadUrlException extends RuntimeException 
{
	public BadUrlException(String s) 
	{
		super(s);
	}
}

Then I change the methods to use the now unchecked BadUrlException:
public void storeDataFromUrl(String url)
{
	String data = readDataFromUrl(url);
}

public String readDataFromUrl(String url) 
{
	if(isUrlBad(url))
	{
		throw new BadUrlException("Bad URL: " + url);
	}

	String data = null;
	//read lots of data over HTTP and
	//return it as a String instance.

	return data;
}

Notice how the readDataFromUrl() method no longer declares that it throws BadUrlException. The storeDataFromUrl() method doesn't have to catch the BadUrlException either. The storeDataFromUrl() method can still choose to catch the exception but it no longer has to, and it no longer has to declare that it propagates the exception.

We mentioned above that certain exceptions are generally indicative of a programming error rather than errors that we'd expect to occur in the normal course of events. (Whereas, it is reasonable for the programmer to expect that a networking or file system error will occur from time to time.) We also mentioned that subclasses of Error are not necessarily programming errors, but still errors that we wouldn't really expect to occur in the normal course of events.

A feature built into the Java language is that Errors and RuntimeExceptions (and their subclasses- marked in red in the Figure above) are what are called unchecked exceptions:

" unchecked exceptions can be thrown "at any time"; " methods don't explicitly have to declare that they can throw an unchecked exception; " callers don't have to handle them explicitly. Checked or Unchecked?

Now that we have seen the difference in code between checked and unchecked exceptions, let's dive into the arguments for and against both.
Some Java books(*) covering exceptions advice you to use checked exceptions for all errors the application can recover from, and unchecked exceptions for the errors the application cannot recover from. In reality most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions. The action / transaction that failed will be aborted but the application has to stay alive and be ready to serve the next action / transaction. The only time it is normally legal to shut down an application is during startup. For instance, if a configuration file is missing and the application cannot do anything sensible without it, then it is legal to shut down the application.

(*) Suns Java Tutorial does for one.
My advice to you is to use either only checked exceptions or only unchecked exceptions. Mixing exception types often results in confusion and inconsistent use. Of course you should be pragmatic. Do what makes sense in your situation.
1. If a method in Superclass declares an exception, it is NOT necessary for the overriding method in Subclass to declare an exception. It may decide NOT to declare ANY exceptions at all.
2. But if the overriding method in Subclass MUST declare ANY exceptions, those exceptions have to be a sub-type of exceptions declared by the Superclass method.
So it is like this, either declare an exception that is a sub type of exception declared by the SuperClass Method. Or DO NOT declare ANY exceptions.
import java.io.*;
class Super{
public static void amethod()throws Exception{}
}

public class Test extends Super{
public static void amethod()throws IOException{}
}

Will compile.
------------------------------------------------------
import java.io.*;
class Base{
public static void amethod()throws FileNotFoundException{}
}

public class ExcepDemo extends Base{
  //Will not compile, exception not in base version of method
  public static void amethod()throws IOException{}
}

/tmp/jc_12003/ExcepDemo.java:8: amethod() in ExcepDemo cannot override amethod() in Base; overridden method does not throw java.io.IOException public static void amethod()throws IOException{}
^ 1 error

If it were the method in the parent class that was throwing IOException and the method in the child class that was throwing FileNotFoundException this code would compile. Again, remember that this only applies to overridden methods, there are no similar rules to overloaded methods. Also an overridden method in a sub class may throw Exceptions.
  class A{   	    
  public void fun() throws ArrayIndexOutOfBoundsException{   
	    
	}   
	}   
	    
	public class B extends A{   
	    
	public void fun() throws ArrayIndexOutOfBoundsException,Exception{   	    
	}   
	}   

In this case, the overriding method throws more exceptions than the original method. This doesnt compile. Check the message which compiler gives. It says "fun() in B cannot override fun() in A; overridden method does not throw java.lang.Exception public void fun() throws ArrayIndexOutOfBoundsException,Exception{"
class A{
  public void method()throws Exception{}
 }
 class B{
  public void method(){}
 }

Will compile(See Rule 1)
String str = ""; Integer.parseInt(str); --- How this works
Runtime Exception will come
C:\Users\Madhu\Desktop>java -classpath . Test
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
NumberFormatException is a subclass of the Runtime Exception class. A NumberFormatException occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.
The conversions are done by the functions Integer.parseInt and Integer.parseDouble. Consider the function call Integer.parseInt(str) where str is a variable of type String. Suppose the value of str is "60", then the function call convert the string into the int 60. However, if you give the value of str is "saurabh", the function call will fail to compile because "saurabh" is not a legal string representation of an int value. In such case, NumberFormatException will occur.
public class ConvertStringToNumber
{
   public static void main(String[] args)
{ 
   try
{
   String s = "saurabh";
   int i = Integer.parseInt(s);
  // this line of code will never be reached//
   System.out.println("int value = " + i);
}
   catch (NumberFormatException nfe)
{
  nfe.printStackTrace();
}
}
}
public class ParseException extends java.lang.Exception
A ParseException occurs when a parser is unable to match the input source to the grammar it is trying to match. However, in certain cases, even though a parse exception occurred the parser can make a best guess as to what the correct parse should have resulted in. In this case, the parser is allowed to place that result in the exception so that the handler can deal with it
 import java.util.Date;
   import java.text.SimpleDateFormat;

   public class CheckSimpleDateFormat
{
   public static void main (String[] args)
{
  SimpleDateFormat dateParser = new SimpleDateFormat("MM'/'dd'/'yyyy'   'H':'m':'s'.'SSS"); 
   try
{
  String dateString = "05/18/2008 16:30:53.700"; //now it's correct. any mismatch here will result in ParseException
  Date   e   = dateParser.parse(dateString);			
  if( e == null )
   System.err.println("ERROR: parse returned null");
   else
   System.out.println("Date parsed: value = " + e );
}
   catch( Exception e )
{
   System.err.println ("ERROR: this date parser threw an exception:\n " +   dateParser.toString() );
   if (e instanceof java.text.ParseException)
  System.err.println(" Index = " + ((java.text.ParseException)e).getErrorOffset ( ));
  e.printStackTrace (System.err);
}
}
}
Though Java provides an extensive set of in-built exceptions, there are cases in which we may need to define our own exceptions in order to handle the various application specific errors that we might encounter.
While defining an user defined exception, we need to take care of the following aspects:
" The user defined exception class should extend from Exception class. " The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception. Let us see a simple example to learn how to define and make use of user defined exceptions.
public class NegativeAgeException extends Exception {

    private int age;

    public NegativeAgeException(int age){
        this.age = age;
    }

    public String toString(){
        return "Age cannot be negative" + " " +age ;
    }
}
public class CustomExceptionTest {

    public static void main(String[] args) throws Exception{

        int age = getAge();

        if (age < 0){
            throw new NegativeAgeException(age);
        }else{
            System.out.println("Age entered is " + age);
        }
    }
    
    static int getAge(){
        return -10;
    }
}
In the CustomExceptionTest class, the age is expected to be a positive number. It would throw the user defined exception NegativeAgeException if the age is assigned a negative number. At runtime, we get the following exception since the age is a negative number.
Exception in thread "main" Age cannot be negative -10 at tips.basics.exception.CustomExceptionTest.main(CustomExceptionTest.java:10)
Short story about serialization

After hard work of many years, Earth's scientists developed a robot which can help them in daily work. But this robot was less featured than the robots which were developed by the scientists of Mars planet.

After a meeting between both planets' scientists, it is decided that mars will send their robots to earth. But a problem occurred. The cost of sending 100 robots to earth was $100 million. And it takes around 60 days for traveling.

Finally, Mar's scientists decided to share their secret with Earth's scientists. This secret was about the structure of class/robot. Earth's scientists developed the same structure on earth itself. Mar's scientists serialized the data of each robot and send it to earth. Earth's scientists deserialized the data and fed it into each robot accordingly.

This process saved the time in communicating mass amount of data.

Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transient before sending their data to Earth. Note that transient property is set to null(in case of reference) or to default value(in case of primitive type) when the object gets deserialized.

One more point which was noticed by Earth's scientists is that Mars's scientists ask them to create some static variables to keep environmental detail. This detail is used by some robots. But Mars's scientists did not share this detail. Because the environment on earth was different than Mars environment.

Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects state is converted into a byte stream. This type of the file cannot be understood by the user. It is a special type of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

Default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.

We all know the Java platform allows us to create reusable objects in memory. However, all of those objects exist only as long as the Java virtual machine1 remains running. It would be nice if the objects we create could exist beyond the lifetime of the virtual machine, wouldn't it? Well, with object serialization, you can flatten your objects and reuse them in powerful ways.

Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. The Java Serialization API provides a standard mechanism for developers to handle object serialization. The API is small and easy to use, provided the classes and methods are understood.

The following program illustrates how to use object serialization and deserialization. It begins by instantiating an object of class MyClass. This object has three instance variables that are of types String, int, and double. This is the information we want to save and restore.
A FileOutputStream is created that refers to a file named "serial," and an ObjectOutputStream is created for that file stream. The writeObject() method of ObjectOutputStream is then used to serialize our object. The object output stream is flushed and closed.
A FileInputStream is then created that refers to the file named "serial," and an ObjectInputStream is created for that file stream. The readObject() method of ObjectInputStream is then used to deserialize our object. The object input stream is then closed.
Note that MyClass is defined to implement the Serializable interface. If this is not done, a NotSerializableException is thrown. Try experimenting with this program by declaring some of the MyClass instance variables to be transient. That data is then not saved during serialization.
import java.io.*; 
public class SerializationDemo { 
public static void main(String args[]) { 
// Object serialization 
try { 
MyClass object1 = new MyClass("Hello", -7, 2.7e10); 
System.out.println("object1: " + object1); 
FileOutputStream fos = new FileOutputStream("serial"); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 
oos.writeObject(object1); 
oos.flush(); 
oos.close(); 
} 
catch(Exception e) { 
System.out.println("Exception during serialization: " + e); 
System.exit(0); 
} 
// Object deserialization 
try { 
MyClass object2; 
FileInputStream fis = new FileInputStream("serial"); 
ObjectInputStream ois = new ObjectInputStream(fis); 
object2 = (MyClass)ois.readObject(); 
ois.close(); 
System.out.println("object2: " + object2); 
} 
catch(Exception e) { 
System.out.println("Exception during deserialization: " + 
e); 
System.exit(0); 
} 
} 
} 
class MyClass implements Serializable { 
String s; 
int i; 
double d; 
public MyClass(String s, int i, double d) { 
this.s = s; 
this.i = i; 
this.d = d; 
} 
public String toString() { 
return "s=" + s + "; i=" + i + "; d=" + d; 
} 
}

This program demonstrates that the instance variables of object1 and object2 are
identical. The output is shown here:
object1: s=Hello; i=-7; d=2.7E10
object2: s=Hello; i=-7; d=2.7E10

Serialization provides: 1. a method of persisting objects which is more convenient than writing their properties to a text file on disk, and re-assembling them by reading this back in.
2. a method of remote procedure calls, e.g., as in SOAP
3. a method for distributing objects, especially in software componentry such as COM, CORBA, etc.
4. a method for detecting changes in time-varying data.
For some of these features to be useful, architecture independence must be maintained. For example, for maximal use of distribution, a computer running on different hardware architecture should be able to reliably reconstruct a serialized data stream, regardless of endianness. This means that the simpler and faster procedure of directly copying the memory layout of the data structure cannot work reliably for all architectures. Serializing the data structure in an architecture independent format means that we do not suffer from the problems of byte ordering, memory layout, or simply different ways of representing data structures in different programming languages.
Advantages :
At first, you get serialization pretty much for free. You don't need to make very many changes to your objects in order to let the serialization mechanism work with it. Another advantage is that, because it is a binary format, it is much more compact than the textual format, and so will probably use less space (which is good for conserving network bandwidth or for conserving storage space on disk).
Disadvantages :
The disadvantage to serialization is that, if you make changes to your object, making the different serialization formats compatible can really be a major nightmare. Also, whereas you can manually edit XML and JSON, you cannot edit a serialized Java object (without reading it into Java). For the same reasons, it is often easier to debug XML and JSON than binary formats, because XML and JSON are human-readable. Nonserializable Objects :
The basic mechanism of Java serialization is simple to use, but there are some more things to know. As mentioned before, only objects marked Serializable can be persisted. The java.lang.Object class does not implement that interface. Therefore, not all the objects in Java can be persisted automatically. The good news is that most of them -- like AWT and Swing GUI components, strings, and arrays -- are serializable.
On the other hand, certain system-level classes such as Thread, OutputStream and its subclasses, and Socket are not serializable. Indeed, it would not make any sense if they were. For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all. Another important point about java.lang.Object not implementing the Serializable interface is that any class you create that extends only Object (and no other serializable classes) is not serializable unless you implement the interface yourself (as done with the previous example).
That situation presents a problem: what if we have a class that contains an instance of Thread? In that case, can we ever persist objects of that type? The answer is yes, as long as we tell the serialization mechanism our intentions by marking our class's Thread object as transient.
Let's assume we want to create a class that performs an animation. I will not actually provide the animation code here, but here is the class we'll use:
 import java.io.Serializable;
 public class PersistentAnimation implements Serializable, Runnable
 {
 transient private Thread animator;
 private int animationSpeed;
 public PersistentAnimation(int animationSpeed)
 {
 this.animationSpeed = animationSpeed;
 animator = new Thread(this);
     animator.start();
   }
       public void run()
   {
     while(true)
     {
       // do animation here
     }
   } 
 }

When we create an instance of the PersistentAnimation class, the thread animator will be created and started as we expect. We've marked the thread on line 40 transient to tell the serialization mechanism that the field should not be saved along with the rest of that object's state (in that case, the field speed). The bottom line: you must mark transient any field that either cannot be serialized or any field you do not want serialized. Serialization does not care about access modifiers such as private -- all nontransient fields are considered part of an object's persistent state and are eligible for persistence.
Therefore, we have another rule to add. Here are both rules concerning persistent objects:
Rule #1: The object to be persisted must implement the Serializable interface or inherit that implementation from its object hierarchy
Rule #2: The object to be persisted must mark all nonserializable fields transient
The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating groups of data as a single unit, a collection. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behavior than arrays.

Rather than having to write your own collection classes, Java provides these ready-to-use collection classes for you.
In order to understand and use the Java Collections API effectively it is useful to have an overview of the interfaces it contains. So, that is what I will provide here.
There are two "groups" of interfaces: Collection's and Map's.
Here is a graphical overview of the Collection interface hierarchy:

s ***********************************collection Hierarchy **********************************
List Implementations Being a Collection subtype all methods in the Collection interface are also available in the List interface.
Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following List implementations in the Java Collections API:
*. java.util.ArrayList
*. java.util.LinkedList
*. java.util.Vector
*. java.util.Stack

Set Implementations
Being a Collection subtype all methods in the Collection interface are also available in the Set interface.
Since Set is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Set implementations in the Java Collections API:
#. java.util.EnumSet
#. java.util.HashSet
#. java.util.LinkedHashSet
#. java.util.TreeSet

Map Implementations
Since Map is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following Map implementations in the Java Collections API:
$. java.util.HashMap
$. java.util.Hashtable
$. java.util.EnumMap
$. java.util.IdentityHashMap
$. java.util.LinkedHashMap
$. java.util.Properties
$. java.util.TreeMap
$. java.util.WeakHashMap
In my experience, the most commonly used Map implementations are HashMap and TreeMap.
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time, precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the arraylist may be shrunk.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)

The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.
The following program shows a simple use of ArrayList. An array list is created, and then objects of type String are added to it. (Recall that a quoted string is translated into a String object.) The list is then displayed. Some of the elements are removed and the
import java.util.*; 
class ArrayListDemo { 
public static void main(String args[]) { 
ArrayList al = new ArrayList(); 
System.out.println("Initial size of al: " + 
al.size()); 
al.add("C"); 
al.add("A"); 
al.add("E"); 
al.add("B"); 
al.add("D"); 
al.add("F"); 
al.add(1, "A2"); 
System.out.println("Size of al after additions: " + 
al.size()); 
System.out.println("Contents of al: " + al); 
al.remove("F"); 
al.remove(2); 
System.out.println("Size of al after deletions: " + 
al.size()); 
System.out.println("Contents of al: " + al); 
} 
}
The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Notice that a1 starts out empty and grows as elements are added to it. When elements are removed, its size is reduced.

Although the capacity of an ArrayList object increases automatically as objects are stored in it, you can increase the capacity of an ArrayList object manually by calling ensureCapacity( ). You might want to do this if you know in advance that you will be storing many more items in the collection that it can currently hold. By increasing its capacity once, at the start, you can prevent several reallocations later. Because reallocations are costly in terms of time, preventing unnecessary ones improves performance. The signature for ensureCapacity( ) is shown here:
void ensureCapacity(int cap);
Here, cap is the new capacity. Conversely, if you want to reduce the size of the array that underlies an ArrayList object so that it is precisely as large as the number of items that it is currently holding, call
trimToSize( ),
shown here:
void trimToSize( ); 

Obtaining an Array from an ArrayList
When working with ArrayList, you will sometimes want to obtain an actual array that contains the contents of the list. As explained earlier, you can do this by calling toArray( ). Several reasons exist why you might want to convert a collection into an array such as:
o To obtain faster processing times for certain operations.
o To pass an array to a method that is not overloaded to accept a collection.
o To integrate your newer, collection-based code with legacy code that does not understand collections.
Whatever the reason, converting an ArrayList to an array is a trivial matter, as the following program shows:

Object ia[] = al.toArray();
int sum = 0;
for(int i=0; i sum += ((Integer) ia[i]).intValue();
System.out.println("Sum is: " + sum);
}
}

The output from the program is shown here:
Contents of al: [1, 2, 3, 4]
Sum is: 10
The methods hashCode() and equals() play a distinct role in the objects you insert into Java collections. The specific contract rules of these two methods are best described in the JavaDoc. Here I will just tell you what role they play. What they are used for, so you know why their implementations are important.
equals();
equals() is used in most collections to determine if a collection contains a given element. For instance:
List list = new ArrayList();
list.add("123");

boolean contains123 = list.contains("123");

The ArrayList iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". It is the String.equals() implementation that determines if two strings are equal.
The equals() method is also used when removing elements. For instance:
List list = new ArrayList();
list.add("123");

boolean removed = list.remove("123");

The ArrayList again iterates all its elements and execute "123".equals(element) to determine if the element is equal to the parameter object "123". The first element it finds that is equal to the given parameter "123" is removed.
As you can see, a proper implementation of equals() is essential for your own classes to work well with the Java Collection classes. So how do you implement equals() "properly"?
So, when are two objects equal? That depends on your application, the classes, and what you are trying to do. For instance, let's say you are loading and processing Employee objects stored in a database. Here is a simple example of such an Employee class:

public class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;
}

You could decide that two Employee objects are equal to each other if just their employeeId's are equal. Or, you could decide that all fields must be equal - both employeeId, firstName and lastName. Here are two example implementation of equals() matching these criterias:
public class Employee {
  ...
  public boolean equals(Object o){
    if(o == null)                return false;
    if(!(o instanceof) Employee) return false;

    Employee other = (Employee) o;
    return this.employeeId == other.employeeId;
  }
}
public class Employee {
  ...
  public boolean equals(Object o){
    if(o == null)                
	return false;
    if(!(o instanceof) Employee) 
	return false;
    Employee other = (Employee) o;
    if(this.employeeId != other.employeeId)      return false;
    if(! this.firstName.equals(other.firstName)) 
	return false;
    if(! this.lastName.equals(other.lastName))   
	return false;
    return true;
  }
}

Which of these two implementations is "proper" depends on what you need to do. Sometimes you need to lookup an Employee object from a cache. In that case perhaps all you need is for the employeeId to be equal. In other cases you may need more than that - for instance to determine if a copy of an Employee object has changed from the original.
hashCode()
The hashCode() method of objects is used when you insert them into a HashTable, HashMap or HashSet. If you do not know the theory of how a hashtable works internally, you can read about hastables on Wikipedia.org.
When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object.

The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.
So, as you can see, a combination of the hashCode() and equals() methods are used when storing and looking up objects in a hashtable.

Here are two rules that are good to know about implementing the hashCode() method in your own classes, if the hashtables in the Java Collections API are to work correctly:
1. If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
2. If object1 and object2 have the same hash code, they do NOT have to be equal too.
In shorter words:
1. If equal, then same hash codes too.
2. Same hash codes no guarantee of being equal.
Here are two example implementation of the hashCode() method matching the equals() methods shown earlier:

public class Employee {
  protected long   employeeId;
  protected String firstName;
  protected String lastName;

  public int hashCode(){
    return (int) this.employeeId;
  }
}
public class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;

  public int hashCode(Object o){
    return (int)this.employeeId *
                firstName.hashCode() *
                lastName.hashCode();
  }
}

Notice, that if two Employee objects are equal, they will also have the same hash code. But, as is especially easy to see in the first example, two Employee objects can be not equal, and still have the same hash code.
In both examples the hash code is the employeeId is rounded down to an int. That means that many employee id's could result in the same hash code, but these Employee objects would still not be equal, since they don't have the same employee id.
public int hashCode(Object o){}
public boolean equals(Object o){}
The default implementation of equals() method checks to see if the two objects have the same identity. Similarly, the default implementation of the hashCode() method returns an integer based on the object's identity and is not based on the values of instance (and class) variables of the object. No matter how many times the values of its instance variables (data fields) change, the hash code calculated by the default hashCode implementation does not change during the life of the object.
Consider the following code, we have overridden equals() method to check if two objects are equal based on the values of their instance variables. Two objects may be stored at different memory addresses but may still be equal base on their instance variable.
public class CustomerID {
  private long crmID;
  private int nameSpace;

  public CustomerID(long crmID, int nameSpace) {
    super();
    this.crmID = crmID;
    this.nameSpace = nameSpace;
  }

  public boolean equals(Object obj) {
    //null instanceof Object will always return false
    if (!(obj instanceof CustomerID))
      return false;
    if (obj == this)
      return true;
    return  this.crmID == ((CustomerID) obj).crmID &&
            this.nameSpace == ((CustomerID) obj).nameSpace;
  }

  public static void main(String[] args) {
    Map m = new HashMap();
    m.put(new CustomerID(2345891234L,0),"Jeff Smith");
    System.out.println(m.get(new CustomerID(2345891234L,0)));
  }

}

Compile and run the above code, the output result is
null
What is wrong? The two instances of CustomerID are logically equal according to the class's equals method. Because the hashCode() method is not overridden, these two instances' identities are not in common to the default hashCode implementation. Therefore, the Object.hashCode returns two seemingly random numbers instead of two equal numbers. Such behavior violates "Equal objects must have equal hash codes" rule defined in the hashCode contract.
Let's provide a simple hashCode() method to fix this problem:
public class CustomerID {
  private long crmID;
  private int nameSpace;

  public CustomerID(long crmID, int nameSpace) {
    super();
    this.crmID = crmID;
    this.nameSpace = nameSpace;
  }

  public boolean equals(Object obj) {
    //null instanceof Object will always return false
    if (!(obj instanceof CustomerID))
      return false;
    if (obj == this)
      return true;
    return  this.crmID == ((CustomerID) obj).crmID &&
            this.nameSpace == ((CustomerID) obj).nameSpace;
  }

  public int hashCode() {
    int result = 0;
    result = (int)(crmID/12) + nameSpace;
    return result;
  }

  public static void main(String[] args) {
    Map m = new HashMap();
    m.put(new CustomerID(2345891234L,0),"Jeff Smith");
    System.out.println(m.get(new CustomerID(2345891234L,0)));
  }

}

Compile and run the above code, the output result is
Jeff Smith
The hashcode distribution for instances of a class should be random. This is exactly what is meant by the third provision of the hashCode contract. Write a correct hashCode method is easy, but to write an effective hashCode method is extremely difficult.
-------------------------------------------
public int hashCode(){
  return 0;
}
It's legal because it ensures that equal objects have the same hash code, but it also indicates that every object has the same hash code. So every object will be hashed into the same bucket, and hash tables degenerate to linked lists. The performance is getting worse when it needs to process a large number of objects. How to implement a good hash function is a big topic and we will not cover here.
The HashMap is a class in java. It stores values in name values pair. You can store null value of key and values.
Here, you will see how to create an object of HashMap class and display the value of map.
Code: HashMapExample .java
package net.roseindia.java;
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] arr) {

HashMap obMap = new HashMap();

obMap.put(new Integer(1), "Bharat");
obMap.put(new Integer(2), "Gyan");
obMap.put(new Integer(4), "Vrishti");
obMap.put(new Integer(3), "Sarika");
obMap.put(new Integer(5), "Rohit");
obMap.put(new Integer(6), "Parineeta");

System.out.println("Elements in HashMap : \n" + obMap);
}
} 

Output :
Elements in HashMap :
{1=Bharat, 2=Gyan, 3=Sarika, 4=Vrishti, 5=Rohit, 6=Parineeta}

HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.
The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.
import java.util.*; 
class HashMapDemo { 
public static void main(String args[]) { 

// Create a hash map 
HashMap hm = new HashMap(); 

// Put elements to the map 
hm.put("John Doe", new Double(3434.34)); 
hm.put("Tom Smith", new Double(123.22)); 
hm.put("Jane Baker", new Double(1378.00)); 
hm.put("Todd Hall", new Double(99.22)); 
hm.put("Ralph Smith", new Double(-19.08)); 

// Get a set of the entries 
Set set = hm.entrySet(); 

// Get an iterator 
Iterator i = set.iterator(); 

// Display elements 
while(i.hasNext()) { 
Map.Entry me = (Map.Entry)i.next(); 
System.out.print(me.getKey() + ": "); 
System.out.println(me.getValue()); 
} 

System.out.println(); 

// Deposit 1000 into John Doe's account 
double balance = ((Double)hm.get("John Doe")).doubleValue(); 
hm.put("John Doe", new Double(balance + 1000)); 

System.out.println("John Doe's new balance: " + 
hm.get("John Doe")); 
} 
}
Output from this program is shown here: Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Todd Hall: 99.22
Jane Baker: 1378.0
John Doe's current balance: 4434.34
To get the same value back from a map you must use a key object that is "equal" to the one you used to put it in map
	1.	java.util.HashMap m = new java.util.HashMap();   
2.	Object key1 = new Object();   
3.	    
4.	m.put(key1, "some value");   
5.	Object val1 = m.get(new Object()); // val1 becomes null   
6.	Object val2 = m.get(key1); // val2 becomes "some value"   
7.	    
8.	String s1 = "key2";   
9.	String s2 = "key2";   
10.	    
11.	m.put(s1, "some other value");   
12.	Object val3 = m.get(s2); // val3 becomes "some other value", because s1.equals(s2);   
13.	    
14.	System.out.println(val1);   
15.	System.out.println(val2);   
16.	System.out.println(val3);

The nature of hash based collections is to store keys and values. The key is what you use to look up a value. Thus you could for instance use a HashMap to store employee id in the key value and the employee name in the value part.
Generally a hashcode value will be the memory address of the object. You can demonstrate this to yourself quite easily with some trivial code such as.
public class ShowHash{
    public static void main(String argv[]){
        ShowHash sh = new ShowHash();
        System.out.println(sh.hashCode());
    }
}

When I compiled and ran this code I got an output of
7474923
Which is a representation of the memory address of that class on that run of the program. This illustrates one of the features of a hashcode is that it does not have to be the same value from one run of a program to another. If you think about the memory address of an object, there is not guarantee at all what it will be from one run to another of a program.
Every object has access to an equals method because it is inherited from the great grandparent class called Object. However this default object does not always do anything useful as by default it simply compares the memory address of the object. The downside of this can be seen dramatically when used with the String classes. If the String class did not implement its own version of the equals method comparing two Strings would compare the memory address rather than the character sequence. This is rarely what you would want, and for this reason the String class implements its own version of the equals method that makes a character by character comparison.

Objects that are equal according to the equals method must return the same hashCode value

If two objects are not equal according to equals, they are not required to return different hashCode values.
------------------------------ HashTable, HashMap and HashSet are the Collection classes in java.util package that make use of hashing algorithm to store objects. In all these Collection classes except HashSet, objects are stored as key-value pairs. For the storage and the retrieval of any user-defined objects it is a good practice to override the following methods which is mentioned below, " hashCode() " equals()
These methods are available in the Object class and hence available to all java classes. Using these two methods, an object can be stored or retrieved from a Hashtable, HashMap or HashSet.
hashCode() method :
This method returns a hashcode value as an int for the object. Default implementation for hashcode() should be overridden in order to make searching of data faster. The implementation of hashCode() method for an user-defined object should be calculated based on the properties of the class which we wish to consider.

equals() method
This method returns a boolean which specifies whether two objects are equal or not. The default implementation of equals() method given by the Object Class uses the '==' operator to compare two object references, and returns true only if they refer to the same object. But, we can meaningfully re-define this equals() method to have an equality check based on our own criteria.
Consider the following code, which defines two user defined classes Employee and EmployeeId which are supposed to be stored in a Map.
Employee.java 

public class Employee {
	private String name;

	public Employee(String name){
		this.name = name;
	}

	public String toString(){
	return name;
	}
}
EmployeeId.java 

public class EmployeeId {

	private String id;

	public EmployeeId(String id){
		this.id = id;
	}

	public String toString(){
		return id;
	}	
}

The following class makes use of the above classes by storing it in a Map for later retrieval. We are adding Employee objects into the Map keyed with Employee Id.
HashCodeTest.java :
public class HashCodeTest {

	public static void main(String[] args) {

		Map employees = new HashMap();

		employees.put(new EmployeeId("111"), new Employee("Johny"));
		employees.put(new EmployeeId("222"), new Employee("Jeny")); // Line A
		employees.put(new EmployeeId("333"), new Employee("Jessie"));

		Employee emp =  employees.get(new EmployeeId("222")); // Line B
		System.out.println(emp); // Line C
	}
}

In Line B, we try to retrieve the Employee object who has Employee Id with a value of 222. We expect the output to be 'Jeny', because the Employee with Employee Id (222) was already there in the Collection, but surprisingly, the output of the above code is null. The reason is that we did not override the equals() method for EmployeeId and Employee classes because the default implementation of equals() in the Object class considers the new EmployeeId("222") in the put statement and new EmployeeId("222") in the get statement as two different instances, and hence the call to get() in Line B returns null.
Let us look at how the same code works when we provide our desired implementation for hashcode() and equals() methods. We basically override hashcode() here just to make the object to be searched fast.
Employee.java :
public class Employee {

	private String name;

	public Employee(String name){
		this.name = name;
	}

	public String toString(){
		return name;
	}

	@Override
	public boolean equals(Object obj){ 

		if(obj == null) {
			return false;
		}
		if(obj.getClass() != getClass()){
			return false;
		}

		Employee emp = (Employee)obj;
		if(this.name == emp.name){
			return true;
		}
		return false;
	}

	@Override
	public int hashCode(){
		return name.hashCode();
	}
}


public class EmployeeId {

	private String id;

	public EmployeeId(String id){
		this.id = id;
	}

	public String toString(){
		return id;
	}	

	public boolean equals(Object obj){

	if(obj == null) 
		return false;

	if(obj.getClass() != getClass()){
		return false;
	}

	EmployeeId empId = (EmployeeId)obj;
	if(this.id == empId.id){
		return true;
	}
	return false;
	}

	@Override
	public int hashCode(){
		return id.hashCode();
	}
}

Now, we get the desired output 'Jeny', because as per our implementation for the equals() method, the new EmployeeId("222") in the put statement and new EmployeeId("222") in the get statement are considered one and the same
How HashMap works in Java
How HashMap works in Java or sometime how get method work in HashMap is common interview questions now a days. Almost everybody who worked in Java knows what hashMap is, where to use hashMap or difference between hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth this question offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews

Questions start with simple statement
"Have you used HashMap before" or "What is HashMap? Why do we use it "

Almost everybody answers this with yes and then interviewee keep talking about common facts about hashMap like hashMap accpt null while hashtable doesn't, HashMap is not synchronized, hashMap is fast and so on along with basics like its stores key and value pairs etc.
This shows that person has used hashMap and quite familier with the funtionalities HashMap offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in hashmap. Interviewer come back with questions like

"Do you Know how hashMap works in Java" or
"How does get () method of HashMap works in Java"
And then you get answers like I don't bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.
But some interviewee definitely answer this and will say "HashMap works on principle of hashing, we have put () and get () methods for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls hashcode() method on hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.

But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap e.g

"What will happen if two different objects have same hashcode?"

Now from here confusion starts. Some time interviewee will say that since Hashcode is equal, objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them about equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say "Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list." great this answer make sense to me though there could be some other collision resolution methods available, this is simplest and HashMap does follow this. But story does not end here and final questions interviewer ask like
"How will you retrieve if two different objects have same hashcode?"
Hmmmmmmmmmmmmm
Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retreives object but then you need to remind him that there are two objects stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify value object because you don't have value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won't be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.

Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutablity also allows caching there hashcode of different keys which makes overall retreival process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.

Now if you clear all this java hashmap interview question you will be surprised by this very interesting question "What happens On HashMap if the size of the Hashmap exceeds a given threshold defined by load factor ?". Until you know how hashmap works exactly you won't be able to answer this question.

If the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location.

If you manage to answer this question on hashmap in java you will be greeted by "do you see any problem with resizing of hashmap in Java" , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java.

So the answer is Yes, there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during the migration to new bucket because java hashmap doesn't append the new element at tail instead it append new element at head to avoid tail traversing. If race condition happens then you will end up with an infinite loop. Though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer :)

I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified Concept of hashing
Collision resolution in HashMap
Use of equals () and hashCode () method and there importance?
Benefit of immutable object?
race condition on hashmap in Java
Resizing of Java HashMap
Hashtable Hashtable is basically a data structure to retain values of key-value pair. " It doesn't allow null for both key and value. You will get NullPointerException if you add null value. " It is synchronized. So it comes with its cost. Only one thread can access in one time
	Hashtable cityTable = new Hashtable(); 
cityTable.put(1, "Lahore"); 
cityTable.put(2, "Karachi"); 
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/
  
System.out.println(cityTable.get(1)); 
System.out.println(cityTable.get(2)); 
System.out.println(cityTable.get(3));

HashMap Like Hashtable it also accepts key value pair. " It allows null for both key and value " It is unsynchronized. So come up with better performance
Hashtable cityTable = new Hashtable(); 
cityTable.put(1, "Lahore"); 
cityTable.put(2, "Karachi"); 
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/
  
System.out.println(cityTable.get(1)); 
System.out.println(cityTable.get(2)); 
System.out.println(cityTable.get(3));


HashSet Instead of key, value pairs, HashSet Store only objects. HashSet does not allow duplicate values. It provides add method rather put method. You also use it's contains method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.
	HashSet stateSet = new HashSet(); 
stateSet.add ("CA"); 
stateSet.add ("WI"); 
stateSet.add ("NY"); 
  
if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
     System.out.println("Already found"); 
else
    stateSet.add("PB");

Hashtable

HashTable is a implementation of Map interface
HashTable Stores data in form of key value pair
Put method is used to add element in map
It doesn't allow null for both key and value
It is synchronized

Hash Map
HashMap is a implementation of Map interface
HashMap Stores data in form of key value pair
Put method is used to add element in map
In hashmap hashcode value is calculated using key object
It allows null for both key and value
Also it is unsynchronized so it comes with better performance. HashMap is faster than hashset because unique key is used to access object.

Hash Set
HashSet is an implementation of Set Interface
HashSet Store only objects and doesn't allow duplicates
Add method is used to add element is Set. contains method to check whether the object is already available
Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality. If it returns false, it means two objects are different.
HashSet is slower than Hashmap
List: I have an ArrayList that I want to output completely as a String. Essentially I want to output it in order using the toString of each element separated by tabs. Is there any fast way to do this? You could loop through it (or remove each element) and concat it to a String but I think this will be very slow Basically, using a loop to iterate over the ArrayList is the only option:
ArrayList list = new ArrayList(); 
list.add("one"); 
list.add("two"); 
list.add("three"); 
 
String listString = ""; 
 
for (String s : list) 
{ 
    listString += s + "\t"; 
} 
 
System.out.println(listString); 

In fact, a string concatenation is going to be just fine, as the javac compiler will optimize the string concatenation as a series of append operations on a StringBuilder anyway. Here's a part of the disassembly of the bytecode from the for loop from the above program:
   61:  new     #13; //class java/lang/StringBuilder 
   64:  dup 
   65:  invokespecial   #14; //Method java/lang/StringBuilder."":()V 
   68:  aload_2 
   69:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 
   72:  aload   4 
   74:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 
   77:  ldc     #16; //String \t 
   79:  invokevirtual   #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 
   82:  invokevirtual   #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String; 
   
As can be seen, the compiler optimizes that loop by using a StringBuilder, so performance shouldn't be a big concern.
(OK, on second glance, the StringBuilder is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit StringBuilder would probably yield better performance.)
In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.
Edit: As pointed out in the comments, the above compiler optimization is indeed creating a new instance of StringBuilder on each iteration. (Which I have noted previously.)
The most optimized technique to use will be the response by Paul Tomblin, as it only instantiates a single StringBuilder object outside of the for loop.
Rewriting to the above code to:
ArrayList list = new ArrayList(); 
list.add("one"); 
list.add("two"); 
list.add("three"); 
 
StringBuilder sb = new StringBuilder(); 
for (String s : list) 
{ 
    sb.append(s); 
    sb.append("\t"); 
} 
 
System.out.println(sb.toString()); 

Will only instantiate the StringBuilder once outside of the loop, and only make the two calls to the append method inside the loop, as evidenced in this bytecode (which shows the instantiation of StringBuilder and the loop):
// Instantiation of the StringBuilder outside loop:
   33:  new     #8; //class java/lang/StringBuilder 
   36:  dup 
   37:  invokespecial   #9; //Method java/lang/StringBuilder."":()V 
   40:  astore_2 
 
   // [snip a few lines for initializing the loop] 
   // Loading the StringBuilder inside the loop, then append: 
   66:  aload_2 
   67:  aload   4 
   69:  invokevirtual   #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 
   72:  pop 
   73:  aload_2 
   74:  ldc     #15; //String \t 
   76:  invokevirtual   #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 
   79:  pop 
   
So, indeed the hand optimization should be better performing, as the inside of the for loop is shorter and there is no need to instantiate a StringBuilder on each iteration

Map:
import java.util.HashMap;
import java.util.Map;

public class MainClass {
  public static void main(String[] a) {
    Map map = new HashMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println(map);
  }
}

{key1=value1, key3=value3, key2=value2}
package com.so.demos; 
 
import java.util.List; 
import java.util.Map; 
import java.util.Set; 
 
public class ToStringHelper { 
 
    private String separator; 
    private String arrow; 
 
    public ToStringHelper(String separator, String arrow) { 
        this.separator = separator; 
        this.arrow = arrow; 
    } 
public String toString(List l) { 
        StringBuilder sb = new StringBuilder("("); 
        String sep = ""; 
        for (Object object : l) { 
            sb.append(sep).append(object.toString()); 
            sep = separator; 
        } 
        return sb.append(")").toString(); 
    } 
public String toString(Map m) { 
        StringBuilder sb = new StringBuilder("["); 
        String sep = ""; 
        for (Object object : m.keySet()) { 
            sb.append(sep) 
              .append(object.toString()) 
              .append(arrow) 
              .append(m.get(object).toString()); 
            sep = separator; 
        } 
        return sb.append("]").toString(); 
    } 
 
    public String toString(Set s) { 
        StringBuilder sb = new StringBuilder("{"); 
        String sep = ""; 
        for (Object object : s) { 
            sb.append(sep).append(object.toString()); 
            sep = separator; 
        } 
        return sb.append("}").toString(); 
    } 
}
To make use of the fully object orient concept, java introduce the derived objects of all primitive types. Below is the list of all wrapper classes in java.

Primitive data type ---- Wrapper class
Byte - Byte Int - Integer Double - Double Long - Long Boolean - Boolean Char - Character Float - Float
Wrapper class helps you convert the primitive data type into derived variable and from derived variable to primitive data type.
All the wrapper classes are final and toString() and hashCode() method has been overridden in order to compare the state of the object.
All the wrapper classes except Character have two constructors. One constructor takes the respective data type and second constructor takes the string which convert to respective data type.
Character class has only one constructor which takes only char data type.

Auto boxing and unboxing using wrapper class:
Getting the derived object from a primitive data type is called the Autoboxing.
Getting the primitive data type from the derived object called unboxing.
Boxing and unboxing is happening automatically using wrapper classes using java 5 or newer version.
Example of wrapper classes:
	public class Wrapperworld { 
  
    public static void main(String[] args) { 
  
        // Integer Example 
        int i = 9; 
        Integer intObj = new Integer(i); 
        int j = intObj.intValue(); 
  
        // One constructor is taking the literals 
        Integer intOnj2 = new Integer(10); 
  
        // One constructor is taking the String 
        Integer intOnj3 = new Integer("10"); 
  
        // One constructor is taking the literals 
        Double d1 = new Double(100.000); 
  
        // One constructor is taking the String 
        Double d2s = new Double("100.000"); 
    } 
}
In Java not all classes have to be defined separate from each other. You can put the definition of one class inside the definition of another class. The inside class is called an inner class and the enclosing class is called an outer class. So when you define an inner class, it is a member of the outer class in much the same way as other members like attributes, methods and constructors.

Where should you use inner classes?
Code without inner classes is more maintainable and readable. When you access private data members of the outer class, the JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In general we should avoid using inner classes. Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc., which are used in the context of an outer class.
There are four types of inner classes which you can write in java classes.
Non-Static Inner class
1) In non-static class we cannot declare static members like variables or methods or static block.
2) In Inner class we can access outer class member either static or non static.
3) If you do not declare an inner class as static, the class is called as inner class or instance class.
The example of inner class is below
	public class Outer { 
  
    int i; 
    static int j; 
  
    void test() { 
        System.out.println("Ouetr test();"); 
    } 
  
    static void testStatic() { 
        System.out.println("Outer testStatic(); "); 
    } 
  
    class Inner { 
        int k; 
  
        void test() { 
            System.out.println("Inner test();"); 
        } 
    } 
}
Static inner class
1) In static class we can declare static members like variables or methods or static block.
2) In Inner class we can access only static member of outer class.
3) If you declare inner class as static, the class is called as static inner class.
The example of static inner class is below.
	public class Outer { 
  
    int i; 
    static int j; 
  
    void test() { 
        System.out.println("Ouetr test();"); 
    } 
  
    static void testStatic() { 
        System.out.println("Outer testStatic(); "); 
    } 
  
    static class StaticInner{ 
        int k; 
        static int m; 
        void test() { 
            System.out.println("Static Inner test();"); 
            testStatic(); 
        } 
          
        static void testStatic(){ 
            System.out.println("Static Inner testStatic();"); 
              
        } 
    } 
}
Local inner class
1) Defining a class inside a method is known as local inner class.
2) Local variable should not be declared as static, they can be final or transient.
3) In local class we can declare static(?) and non-static members.
4) Local inner class can use only the final member of method in which it has been defined.
5) Local inner class can be used within the method it defined; local inner class cannot be used outside the method.
Example of Local inner class
public class Outer { 
    int i; 
    static int j; 
  
    void test() { 
        System.out.println("Outer test();"); 
        class LocalClass { 
            int y; 
            void test() { 
                System.out.println("Inside local class test();"); 
            } 
        } 
    } 
}
Anonymous inner class
1) The inner class that does not have any name is called as anonymous inner class.
2) It is the implementation of the super class or interface within on line where the implementation of method(s) has been written.
3) Anonymous inner class must use no parameter constructor of the super class.
4) Anonymous inner classes are scoped inside the private scoping of the outer class. They can access the internal (private) properties and methods of the outer class.
5) References to an inner class can be passed to other objects. Note that it still retains its scoping.
6) Useful for controlled access to the innards of another class.
7) Useful when you only want one instance of a special class.
Example of Anonymous inner class using Runnable interface is shown below.
	class Test { 
  
    public static void main(String[] args) { 
        Runnable run = new Runnable() { 
            public void run() { 
                System.out.println("Inside the Anonymous inner class"); 
            } 
        }; 
    } 
}
Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. For example, that streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display. Even the word processor should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display. Software that can do such things is known as concurrent software.
The Java platform is designed from the ground up to support concurrent programming with basic concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the Java platform has also included high-level concurrency APIs.
Processes and Threads In concurrent programming, there are two basic units of execution: processes and threads. In the Java programming language, concurrent programming is mostly concerned with threads. However, processes are also important.
A computer system normally has many active processes and threads. This is true even in systems that only have a single execution core, and thus only have one thread actually executing at any given moment. Processing time for a single core is shared among processes and threads through an OS feature called time slicing.
It's becoming more and more common for computer systems to have multiple processors or processors with multiple execution cores. This greatly enhances a system's capacity for concurrent execution of processes and threads - but concurrency is possible even on simple systems, without multiple processors or execution cores.

A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. Processes are often seen as synonymous with programs or applications. However, what the user sees as a single application may in fact be a set of cooperating processes. To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.
Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object. Multiprocess applications are beyond the scope of this lesson.

Threads Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.
Threads exist within a process - every process has at least one thread. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.
Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread - or several, if you count "system" threads that do things like memory management and signal handling. But from the application programmer's point of view, you start with just one thread, called the main thread.

Thread Objects
Each thread is associated with an instance of the class Thread. There are two basic strategies for using Thread objects to create a concurrent application.
* To directly control thread creation and management, simply instantiate Thread each time the application needs to initiate an asynchronous task.
* To abstract thread management from the rest of your application, pass the application's tasks to an executor.
Defining and Starting a Thread
An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:
* Provide a Runnable object: The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:
public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}

*. Subclass Thread: The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:
public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}
Notice that both examples invoke Thread.start in order to start the new thread.

Which of these idioms should you use? The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. This lesson focuses on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later. The Thread class defines a number of methods useful for thread management. These include static methods, which provide information about, or affect the status of, the thread invoking the method. The other methods are invoked from other threads involved in managing the thread and Thread object.

Different states of a thread are:
When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. By invoking start() method, it doesn't mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed.




New state - After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. Runnable (Ready-to-run) - A thread starts its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.
Running - A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
Dead - A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

Different states implementing Multiple-Threads are:

.....................diagtram..................
As we have seen different states that may be occur with the single thread, a running thread can enter to any non-runnable state, depending on the circumstances. A thread cannot enter directly to the running state from non-runnable state, firstly it goes to runnable state. Now let's understand the some non-runnable states which may be occur handling the multithreads. Sleeping - On this state, the thread is still alive but it is not runnable, it might be return to runnable state later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the method sleep( ) to stop the running state of a thread.
   static void sleep(long millisecond) throws InterruptedException
Waiting for Notification - A thread waits for notification from another thread. The thread sends back to runnable state after sending notification from another thread.
 
   final void wait(long timeout) throws InterruptedException
   final void wait(long timeout, int nanos) throws InterruptedException
   final void wait() throws InterruptedException 

Blocked on I/O - The thread waits for completion of blocking operation. A thread can enter on this state because of waiting I/O resource. In that case the thread sends back to runnable state after availability of resources.
Blocked for joint completion - The thread can come on this state because of waiting the completion of another thread.
Blocked for lock acquisition - The thread can come on this state because of waiting to acquire the lock of an object.
Methods that can be applied on a Thread:

Some Important Methods defined in java.lang.Thread are shown in the table:


Method -      - Return Type     - Description
currentThread( )--       -- Thread --   Returns an object reference to the thread in which it is invoked.
getName( ) -- String --     Retrieve the name of the thread object or instance.
start( ) --      void --    Start the thread by calling its run method.
run( ) --    void -    This method is the entry point to execute thread, like the main method for applications.
sleep( ) --    void --    Suspends a thread for a specified amount of time (in milliseconds).
isAlive( ) -- boolean -- This method is used to determine the thread is running or not.
activeCount( ) -- Int -- This method returns the number of active threads in a particular thread group and all its subgroups.
interrupt( ) -- void -- This method interrupts the threads on which it is invoked.
yield( ) -- Void -- By invoking this method the current thread pause its execution temporarily and allow other threads to execute.
join( ) -- Void -- Join() and join(long millisec) throws InterruptedException. These are not returned until either the thread has completed or it is timed out respectively.



Synchronization
Threads communicate primarily by sharing access to fields and the object references these fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
* Thread Interference describes how errors are introduced when multiple threads access shared data. * Memory Consistency Errors describes errors that result from inconsistent views of shared memory. * Synchronized Methods describes a simple idiom that can effectively prevent thread interference and memory consistency errors. * Implicit Locks and Synchronization describes a more general synchronization idiom, and describes how synchronization is based on implicit locks. * Atomic Access talks about the general idea of operations that can't be interfered with by other threads.

A Synchronized Class Example The class, SynchronizedRGB, defines objects that represent colors. Each object represents the color as three integers that stand for primary color values and a string that gives the name of the color.
public class SynchronizedRGB {

    // Values must be between 0 and 255.
    private int red;
    private int green;
    private int blue;
    private String name;

    private void check(int red,
                       int green,
                       int blue) {
        if (red < 0 || red > 255
            || green < 0 || green > 255
            || blue < 0 || blue > 255) {
            throw new IllegalArgumentException();
        }
    }

    public SynchronizedRGB(int red,
                           int green,
                           int blue,
                           String name) {
        check(red, green, blue);
        this.red = red;
        this.green = green;
        this.blue = blue;
        this.name = name;
    }

    public void set(int red,
                    int green,
                    int blue,
                    String name) {
        check(red, green, blue);
        synchronized (this) {
            this.red = red;
            this.green = green;
            this.blue = blue;
            this.name = name;
        }
    }

    public synchronized int getRGB() {
        return ((red << 16) | (green << 8) | blue);
    }

    public synchronized String getName() {
        return name;
    }

    public synchronized void invert() {
        red = 255 - red;
        green = 255 - green;
        blue = 255 - blue;
        name = "Inverse of " + name;
    }
}
SynchronizedRGB must be used carefully to avoid being seen in an inconsistent state. Suppose, for example, a thread executes the following code:
SynchronizedRGB color =
    new SynchronizedRGB(0, 0, 0, "Pitch Black");
...
int myColorInt = color.getRGB();      //Statement 1
String myColorName = color.getName(); //Statement 2
If another thread invokes color.set after Statement 1 but before Statement 2, the value of myColorInt won't match the value of myColorName. To avoid this outcome, the two statements must be bound together:
synchronized (color) {
    int myColorInt = color.getRGB();
    String myColorName = color.getName();
} 
This kind of inconsistency is only possible for mutable objects - it will not be an issue for the immutable version of SynchronizedRGB.
Deadlock Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Here's an example. Below where the deadlock condition is occurred:




In this diagram two threads having the Printing & I/O operations respectively at a time. But Thread1 need printer that is hold up by the Thread2, likewise Thread2 need the keyboard that is hold up by the Thread1. In this situation the CPU becomes ideal and the deadlock condition occurs because no thread is executed until the held up resources are free Another Example to show DeadLock condition:

In this example, there are two thread objects myThread and yourThread. When myThread starts running it holds lock on str1 object. If now yourThread strarts it gets lock on str2. Now when first thread continues and wants lock on str2 then it is not available because second thread already holds lock on str2. Now both threads will wait for each other. myThread waits for str2 to be released by yourThread and yourThread is waiting for str1 to be released by myThread. This program now goes to deadlock condition. Now if you want to break the program then you need to press CTRL+C from keyboard.
DeadLockDemo.java
import java.util.*;

public class DeadLockDemo extends Thread 
{
	public static String str1 = "str1";
	public static String str2 = "str2";

	public static void main(String[] a) 
	{
		Thread myThread = new MyThread();
		Thread yourThread = new YourThread();

		myThread.start();
		yourThread.start();
	}

	private static class MyThread extends Thread 
	{
		public void run() 
		{
			synchronized (str1) 
			{
				System.out.println("MyThread Holds lock on object str1");
				try 
				{
					Thread.sleep(10);
				}
				catch (InterruptedException e) 
				{
				}

				System.out.println("MyThread waiting for lock on object str2");
				
				synchronized (str2) 
				{
					System.out.println("MyThread Holds lock on objects str1, str2");
				}
			}
		}
	}

	private static class YourThread extends Thread 
	{
		public void run() 
		{
			synchronized (str2) 
			{
				System.out.println("YourThread Holds lock on object str2");
				try 
				{
					Thread.sleep(10);
				}
				catch (InterruptedException e) 
				{
				}
				System.out.println("YourThread waiting for lock on object str1");
				
				synchronized (str1) 
				{
					System.out.println("YourThread Holds lock on objects str1, str2");
				}
			}
		}
	}
}

Output: C:\Users\Madhu\Desktop\Madhu>java -classpath . DeadLockDemo
MyThread Holds lock on object str1
YourThread Holds lock on object str2
YourThread waiting for lock on object str1
MyThread waiting for lock on object str2
Screen would stuck here until we do CTRL + C
Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack if they are local method variables and allocated in the heap if they are member variables (i.e. fields of a class). In Java method's local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is thread safe (each thread will have its own stack) but the heap is not thread safe unless guarded with synchronization through your code.

A method in stack is reentrant allowing multiple concurrent invocations that do not interfere with each other. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.


Type casting means treating a variable of one type as though it is another type.
When up casting primitives as shown below from left to right, automatic conversion occurs. But if you go from right to left, down casting or explicit casting is required. Casting in Java is safer than in C or other languages that allow arbitrary casting. Java only lets casts occur when they make sense, such as a cast between a float and an int. However you can't cast between an int and a String (is an object in Java).

byte -> short -> int -> long -> float -> double
int i = 5;
long j = i; //Right. Up casting or implicit casting
byte b1 = i; //Wrong. Compile time error "Type Mismatch".
byte b2 = (byte) i ; //Right. Down casting or explicit casting is required.
When it comes to object references you can always cast from a subclass to a superclass because a subclass object is also a superclass object. You can cast an object implicitly to a super class type (ie upcasting). If this were not the case polymorphism wouldn't be possible.



You can cast down the hierarchy as well but you must explicitly write the cast and the object must be a legitimate instance of the class you are casting to. The ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance. We can deal with the problem of incorrect casting in two ways:
# Use the exception handling mechanism to catch ClassCastException.
try{
Object o = new Integer(1);
System.out.println((String) o);
}
catch(ClassCastException cce) {
logger.log("Invalid casting, String is expected…Not an Integer");
System.out.println(((Integer) o).toString());
}

# Use the instanceof statement to guard against incorrect casting.
If(v2 instanceof Car) {
Car c2 = (Car) v2;
}
Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you can't force it.
What is an unreachable object? An object's life has no meaning unless something has reference to it. If you can't reach it then you can't ask it to do anything. Then the object becomes unreachable and the garbage collector will figure it out. Java automatically collects all the unreachable objects periodically and releases the memory consumed by those unreachable objects to be used by the future reachable objects.

We can use the following options with the Java command to enable tracing for garbage collection events.
-verbose:gc reports on each garbage collection event.

Explain types of references in Java?

java.lang.ref package can be used to declare soft, weak and phantom references.
$ Garbage Collector won't remove a strong reference.
$ A soft reference will only get removed if memory is low. So it is useful for implementing caches while avoiding memory leaks.
$ A weak reference will get removed on the next garbage collection cycle. Can be used for implementing canonical maps. The java.util.WeakHashMap implements a HashMap with keys held by weak references.
$ A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.
Yes. Refer diagram below.


In this code below, which implementation method will be called for these two call statement w.add(impl1); w.add(impl2);
 interface iA
 class iAimplOne implements iA
 class iAimplTwo implements iA
 
 class Work{
 
  public void add(iA obj)
{
	  System.out.println("Common");
  }
  public void add(iAimplOne obj)
{
	  System.out.println("One");
  }
  public void add(iAimplTwo obj)
{
	   System.out.println("Two");
  }

 } 
 class Main{

  public static void main(String args[]){

   Work w=new Work();
   iAimplOne impl1 = new iAimplOne();
   iAimplTwo impl2 = new iAimplTwo();
   w.add(impl1);
   w.add(impl2);
  }

 }
C:\Users\Madhu\Desktop\Madhu\Java\InterfaceTest>java -cp . Main
One
Two
Object method()
String method()
Is this overloading? will it compile?
Can this be overriding, how?

Compilation Fails. This is not overloading because method signature is same. As per the rules of overloading, method signature should not be same (The signature of a method is the combination of the method's name along with the number and types of the parameters (and their order).)
class ObjectString 
{
	Object method(){}
	String method(){}
}
C:\Users\Madhu\Desktop\Madhu\Java>javac -cp . ObjectString.java
ObjectString.java:4: method() is already defined in ObjectString
        String method(){}
               ^
1 error
class ObjectString 
{	
	String method(){}
	Object method(){}
}
C:\Users\Madhu\Desktop\Madhu\Java>javac -cp . ObjectString.java
ObjectString.java:5: method() is already defined in ObjectString
        Object method(){}
               ^
1 error
This is not overriding as well because method return type must be same as super class method.
The following methods have been overriden
method(Object)
method(String)

So, if we call method(null) which method will execute.
Solution:
class B
{
	void method(String s)
	{
	  System.out.println("B");
	}
}

class A extends B
{	
	void method(Object o)
	{
	  System.out.println("A");
	}

}

class ObjectString
{
	public static void main(String args[])
	{
	A a=new A();
	a.method(new Object());
	a.method(null);
	}
}
C:\Users\Madhu\Desktop\Madhu\Java>java -cp . ObjectString
A
B
If a method in super class throws SQLException, and the method has been overriden, and in the overridden method i am getting 2 exceptions, SQLException and IOException. what should be done in that case.

Solution:
import java.io.*;
import java.sql.*;
class Base{
public static void amethod() throws SQLException{}
}
public class ExcepDemoAlt extends Base{
 public static void amethod() throws SQLException{
try{  throw new IOException();}
catch(IOException e){}
  }
 
}
Interface methods must be public, the compiler will fail and issue a warning if interface methods are declared protected or private, even in nested interfaces. Nested interfaces themselves may be declared protected or private. Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class. Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a super class can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a non-static method. In other words, you can't change a static method into an instance method in a subclass.

Will the below work without having try .. catch .. finally in the calling method?
class WOTryCatch 
{ 
	public static void main(String args[])
	{
	}
	void a() throws  Exception 
	{
		b();
	}
	void b()	//either declare to be thrown here
	{
		throw new Exception();
		//or must be caught here
	}
}

C:\Users\Madhu\Desktop\Madhu\Java>javac -cp . WOTryCatch.java
WOTryCatch.java:12: unreported exception java.lang.Exception; must be caught or
declared to be thrown
throw new Exception();
^
1 error
class Overloading{	
void method (int a){}
void method (int b){}
} 
C:\Users\Madhu\Desktop\Madhu\Java>javac -cp . Overloading.java
Overloading.java:3: method(int) is already defined in Overloading
void method (int b){}
     ^
1 error
class abc{}

class pqr{}

public class A
{ 
	private void display(abc a){} 
	private void display(pqr p){}
}
Compiles successfully.
class VoidTest 
{ 
	public static void main(String args[])
	{
	}
	void a() throws ArithmeticException
	{
		
	}
}
There is nothing wrong in it. It compiles.
public  class StaticTest{
    static int s=5;
    public static void main(String args[])
	{
		StaticTest a = new StaticTest();
		StaticTest b = new StaticTest();
		a.s = 6;
		b.s = 7;
		
		System.out.println(a.s);
		System.out.println(b.s);
    }
}
C:\Users\Madhu\Desktop\Madhu\Java>java -cp . StaticTest
7
7
Yes, you can declare a class like this but you cannot instantiate by itself with only methods that already have implementations. This would be useful if you wanted to add abstract methods in the future, or if you did not want the class to be directly instantiated even though it has no abstract properties. Yes. It compiles.
class WOMain 
{
	String a;
	String b;
	public void setA(String c) 
	{
		a=c;
	}
	public String getA() 
	{
		return a;
	}
	public void setB(String d) 
	{
		b=d;
	}
	public String getB() 
	{
		return b;
	}
}
1. The PreparedStatement is a slightly more powerful version of a Statement, and should always be at least as quick and easy to handle as a Statement.
2. The PreparedStatement may be parameterized.

Most relational databases handles a JDBC / SQL query in four steps:
1. Parse the incoming SQL query
2. Compile the SQL query
3. Plan/optimize the data acquisition path
4. Execute the optimized query / acquire and return data
A Statement will always proceed through the four steps above for each SQL query sent to the database. A PreparedStatement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a PreparedStatement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time.
Interfaces - Recommended Use
Statement - Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters.
PreparedStatement - Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.
CallableStatement - Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.

Oracle has two different JDBC drivers. The "thin" driver is a type-4 or pure Java implementation. It requires only a JAR file on the client machine to work. The "OCI" (Oracle Call Interface) driver is a type-2 JDBC driver that relies on the presence of the OCI client libraries on the client machine to work. The OCI driver will tend to have a few features that the thin driver does not and has historically be a bit faster than the thin driver, but requires that the Oracle client be installed on client machines. LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
The first thing to do is to look at what interfaces these two implement. This might hint us at their purpose, as Sun usually bound purposes into interfaces.
// lang java
public class ArrayList
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable

public class LinkedList
extends AbstractSequentialList
implements List, Queue, Cloneable, Serializable

We can ignore Cloneable and Serializable as all of the JCF implement those. It's also quite obvious that both of them implement the List interface, as they need to provide list functionality (backwards iteration, sub listing, etc).
Now for the differences: ArrayList is implementing RandomAccess while LinkedList implementing Queue. You could already tell something about the usage of the two classes.
ArrayList
The ArrayList is actually encapsulating an Array, an Object[]. When you instantiate ArrayList, an array is created, and when you add values into it, the array changes its size accordingly. This gives you strengths and weaknesses:
Fast Random Access You can perform random access without fearing for performance. Calling get(int) will just access the underlying array. Adding values might be slow When you don't know the amount of values the array will contain when you create it, becausea lot of shifting is going to be done in the memory space when the ArrayList manipulates its internal array.
Slow manipulation When you'll want to add a value randomly inside the array, between two already existing values, the array will have to start moving all the values one spot to the right in order to let that happen.
---------------------------
There are 2 things involved.. capacity and size. Capacity represents how many max elements the list can accommodate in it and size represents how many elements are present currently in the list. The capacity is automatically increased by certain amount once the size is equal to capacity..

When we create the arraylist, we have two factors
1- initial size of array list,
2 - load factor (default is .75).

Load factor means size of the arraylist will be doubled if we fill 75% of the size available. That means if initial size of arraylist is 100 then when we insert 75th element in the arraylist, its size will be doubled.
LinkedList
The LinkedList is implemented using nodes linked to each other. Each node contains a previous node link, next node link, and value, which contains the actual data. When new data is inserted, a node is inserted and the links of the surrounding nodes are updated accordingly. When one is removed, the same happens - The surrounding nodes are changing their links and the deleted node is garbage collected. This, as well, gives strengths and weaknesses:
Fast manipulation As you'd expect, adding and removing new data anywhere in the list is instantaneous. Change two links, and you have a new value anywhere you want it.
No random access Even though the get(int) is still there, it now just iterates the list until it reaches the index you specified. It has some optimizations in order to do that, but that's basically it.
Some Conclusions ArrayList is very useful when a well defined set of data is needed in a List interface as opposed to an array. It can be dynamically changed, but try not to do so frequently throughout the life of the application. LinkedList is there for you to do just that: Manipulating it is very easy, and as long as it is used for iteration purposes only and not for random accessing, it's the best solution. Further, if you need random accessing from time to time, I suggest toArray for that specific moment.
Another point I didn't raise here is the Queue issue. LinkedList implements extended abilities to the normal List interface which allows it to add and remove elements from its beginning and end. This makes the LinkedList perfect for Queue and Stack purposes - Although in Java 5 they already added a Stack class.
There are four factors to consider:
* API
* Synchronization
* Data growth
* Usage patterns
API
We can describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. However, there are still some major differences between the two classes.

Synchronization
Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?

Data growth Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either, in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

Usage patterns Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time -- O(1). However, adding and removing elements from any other position proves more expensive -- linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean?
It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time -- O(1). However, indexing an element is a bit slower -- O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.
Java defines two interesting type modifiers: transient and volatile. These modifiers are used to handle somewhat specialized situations.
When an instance variable is declared as transient, then its value need not persist when an object is stored. For example:
class T {
transient int a; // will not persist
int b; // will persist
}
Here, if an object of type T is written to a persistent storage area, the contents of a would not be saved, but the contents of b would.

The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs. In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.

Volatile Example:
Recall that without using volatile (or some other synchronization mechanism), thread A doesn't know that thread B might access the variable. So thread A thinks it's fair game to just cache the value of the variable in a register or in its local memory, and we run into problems.
A typical example of a simple variable that is written to and read from different threads is a "stop request" flag allowing one thread to signal another to finish:
public class StoppableTask extends Thread {
  private volatile boolean pleaseStop;

  public void run() {
    while (!pleaseStop) {
      // do some stuff...
    }
  }

  public void tellMeToStop() {
    pleaseStop = true;
  }
}
If the variable were not declared volatile (and without other synchronization), then it would be legal for the thread running the loop to cache the value of the variable at the start of the loop and never read it again. If you don't like infinite loops, this is undesirable.
Sorting a collection in Java is easy, just use Collections.sort(Collection) to sort your values. For example: package de.vogella.algorithms.sort.standardjava;
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 
  
public class Simple { 
    public static void main(String[] args) { 
        List list = new ArrayList(); 
        list.add(5); 
        list.add(4); 
        list.add(3); 
        list.add(7); 
        list.add(2); 
        list.add(1); 
        Collections.sort(list); 
        for (Integer integer : list) { 
            System.out.println(integer); 
        } 
    } 
}
This is possible because Integer implements the Comparable interface. This interface defines the method compare which performs pair-wise comparison of the elements and returns -1 if the element is smaller than the compared element, 0 if it is equal and 1 if it is larger.
But what if you want to sort differently, for example in different order. Well, you could just use Collection.reverse(). Or you define your own class which implements the interface Comparator.
package de.vogella.algorithms.sort.standardjava;   
import java.util.Comparator; 
  
public class MyIntComparable implements Comparator{ 
  
    @Override
    public int compare(Integer o1, Integer o2) { 
        return (o1>o2 ? -1 : (o1==o2 ? 0 : 1)); 
    } 
}
package de.vogella.algorithms.sort.standardjava; 
  
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 
  
public class Simple2 { 
    public static void main(String[] args) { 
        List list = new ArrayList(); 
        list.add(5); 
        list.add(4); 
        list.add(3); 
        list.add(7); 
        list.add(2); 
        list.add(1); 
        Collections.sort(list, new MyIntComparable()); 
        for (Integer integer : list) { 
            System.out.println(integer); 
        } 
    } 
}
The nice thing about this approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dataOfBirth you could define different implementations of Comparator and sort the objects according to your needs.
 	List list = new ArrayList(); 
Map map = new HashMap(); 
for (String str : map.keySet()) { 
 list.add(str); 
} 
Collections.sort(list); 
for (String str : list) { 
 System.out.println(str); 
} 
Use a TreeMap. This is precisely what it's for. If this map is passed to you and you cannot determine the type, then you can do the following:

TreeSet keys = new TreeSet(map.keySet()); 
for (String key : keys) {  
   String value = map.get(key); 
   // do something 
} 
This will iterate across the map in natural order of the keys.
public class Stack extends Vector
The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to test for whether the stack is empty, and a method to search the stack for an item and discover how far it is from the top.
When a stack is first created, it contains no items.


Constructor Summary
Stack() Creates an empty Stack.

Method Summary
boolean - empty() :- Tests if this stack is empty.
Object - peek() Looks at the object at the top of this stack without removing it from the stack.
Object - pop() Removes the object at the top of this stack and returns that object as the value of this function.
Object - push(Object item) Pushes an item onto the top of this stack.
int - search(Object o) Returns the 1-based position where an object is on this stack.

Here is the code of program:
import java.io.*;
import java.util.*;

public class StackImplement
{
	Stack stack;
	String str;
	int num, n;

	public static void main(String[] args)
	{
		StackImplement q = new StackImplement();
	}

	public StackImplement()
	{
		try
		{
			stack = new Stack();
			InputStreamReader ir = new InputStreamReader(System.in);
			BufferedReader bf = new BufferedReader(ir);
			System.out.print("Enter number of elements : ");
			str = bf.readLine();
			num = Integer.parseInt(str);

			for(int i = 1; i <= num; i++)
			{
				System.out.print("Enter elements : ");
				str = bf.readLine();
				n = Integer.parseInt(str);
				stack.push(n);
			}
		}
		catch(IOException e){}
		System.out.print("Retrieved elements from the stack : ");
		while (!stack.empty()){
		System.out.print(stack.pop() + "  ");
	}
}
Yes and no. The static modifier is only applicable to so-called member classes -- i.e., classes which are directly enclosed within another class. That means you can make a class static but only inner class can be static not the outer class.
In Java, static class means Top Level Class, and all normal classes are Top Level Classes by default. So logically we cannot make Top-Top Level class right. So (But) Java Inner classes can be Static.
10 points on Static keyword in Java
1) static keyword can be applied to variable, method or nested class.It can not be applied on top level class.
2) static variables are associated with class instead of object.
3) static variables in java keeps same value for every single object.
4) you can not use non-static variable inside a static method , it will result in compilation error.
5) Static variables are binded during compile time so they are comparatively faster than there non-static counter part which were binded during work hour.
6) Static fields are initialised at the time of class loading opposite to instance variable which is initialised when you create instance of a particular class.
7) Static keyword can also be used to create static block in Java which can hold a piece of code which can be executed at the time of class loading as shown below.
 static {
        String category = "electronic trading system";
        System.out.println("example of static block in java");
    }
8) Static method cannot be overridden as they belong to class and not to object. so if you have same method in subclass and super class , method will be invoked based on declared type of object instead of runtime for example:
public class TradingSystem 
{
	 public static void main(String[] args) 
	{
	  	TradingSystem system = new DirectMarketAccess(); 
 		DirectMarketAccess dma = new DirectMarketAccess();
        		
		system.printCategory();//static method of TradingSystem will be called
		dma.printCategory();//static method of DirectMarketAccess class will be called
 	}
   
    	public static void printCategory()
	{
		System.out.println("inside super class static method");
	}
}
   
class DirectMarketAccess extends TradingSystem
{
	 public static void printCategory()
	{
        		System.out.println("inside sub class static method");
	}
}
9. If you try to override a static method with a non-static method in sub class you will get compilation error.
10. Be careful while using static keyword in multi-threading or concurrent programming because most of the issues arise when concurrently modifying a static variable by different threads resulting in working with stale or incorrect value if not properly synchronized.
Static Class in Java: You can make any class Static in Java, but you can only make nested classes i.e. class inside another class as static, you can not make any top level class static. Those classes are called nested static classes. To create instance of any nested class, you require instance of outer class but that is not required in case of static nested Class. You can have an instance of nested static class without any instance of outer class.

Here is an example of nested static class in Java
    public static void main(String args[]){
        StaticClass.NestedStaticClass ns = new StaticClass.NestedStaticClass();
        System.out.println(ns.getDescription());
    }
   
    static class NestedStaticClass{
        public String NestedStaticDescription =" Example of Nested Static Class in Java";
        public String getDescription(){
            return NestedStaticDescription;
        }
    }
When to make a Class Static in Java:
Normally we make a class static in Java when we want a Single resource to be shared between all instances and normally we do this for utility classes which are required by all components and which itself doesn't have any state. Sometime interviewer ask whether you should Singleton or Static Class in Java for those purpose,answer is that if its completely stateless and it works on provided data then you can go for Static Class otherwise Singleton pattern is a better choice.

When to make a method static in Java: We can make a method static in Java in following scenario:
1) Method doesn't depends on object's state, in other words doesn't depend on any member variable and everything they need is passes as parameter to them.
2) Method belongs to class naturally can be made static.
3) Utility methods are good candidates for making static because then they can directly be accessed using class name without even creating any instance. Classic example is java.lang.Math
4) In various designs pattern which need a global access e.g. Singleton pattern, Factory Pattern.

Disadvantage of static method in Java: There are certain disadvantages also if you make any method static, for example you can not override any static method so it makes testing harder that you can not replace that method with mock. Since static method maintains global state they can create subtle bug in concurrent environment which is hard to detect and fix.

Why main is static in Java: Another important interview question on static is related to main method. Since main method is static people often asked why main is static. Since static method can be called even without creating instance of class, main is made static.

Example of static class in Java:
JDK itself is a good example of how to use static keyword in java with methods, variables and classes.
1. java.util.Collections has some static utility method which operates on provided collection.
2. java.lang.Math class has static method for maths operations.
3. BorderFactory has static method to control creation of object.
4. Singleton Classes like java.lang.Runtime.getRuntime().
Caution Static methods should not manage or alter any state.
Static block in java
Basically, static blocks are blocks defined within the body of a class using the static keyword but which are not inside any other blocks. i.e.,
public class shme
    {
    static int foo = 12345;

    static
	{
	foo = 998877;
	}
    }
The primary use of static initializer blocks are to do various bits of initialization that may not be appropriate inside a constructor such that taken together the constructor and initializers put the newly created object into a state that is completely consistent for use.
In contrast to constructors, for example, static initializers aren't inherited and are only executed once when the class is loaded and initialized by the JRE. In the example above, the class variable foo will have the value 998877 once initialization is complete.
Note also that static initializers are executed in the order in which they appear textually in the source file. Also, there are a number of restrictions on what you can't do inside one of these blocks such as no use of checked exceptions, no use of the return statement or the 'this' and 'super' keywords.
Personally, I think this is yet another odd little wart in the Java language that is due to the fact that Java doesn't have first-class classes.
----------------------------

In java you see "static variables", "static methods", "static classes" and "static blocks". Static variables, static methods and static classes are known to everyone but what is this "static block". Lets see what, where and how these static blocks are used.
But before going into "static block", lets refresh what other static stuff are. Now "static variables" are class variables i.e., there will be only one copy for each class and not one copy for each object of the class and these variables will be accessed without instantiating the class. Then what are static methods. Again they are class methods i.e., they can be accessed without creating an instance of the class and like static variables, static methods will be accessed without instantiating the class. Note that static methods cannot access instance variables. They can access only static variables. Next what are static classes. You cannot declare a top-level class as a static class. Java will throw a compilation error. Only inner classes that are member classes can be declared as static. If we declare member classes as static, we can use it as a top-level class outside the context of top-level class. One catch here is "The static keyword does not do to a class declaration what it does to a variable or a method declaration." - what it means is say for example you have a static variable, then to access that static variable you will use the notation
<>.<>
but when you want to use the static inner class, you need to instantiate like
<>.<> newClass = new <>.<>();
Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
    // whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And dont forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes. Here are a couple of points I like to mention:
oIf you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM. oIf you're referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.

Lets see an example:
public class StaticExample{
    static {
        System.out.println("This is first static block");
    }

    public StaticExample(){
        System.out.println("This is constructor");
    }

    public static String staticString = "Static Variable";

    static {
        System.out.println("This is second static block and "+ staticString);
    }

    public static void main(String[] args){
        StaticExample statEx = new StaticExample();
        StaticExample.staticMethod2();
    }

    static {
        staticMethod();
        System.out.println("This is third static block");
    }

    public static void staticMethod() {
        System.out.println("This is static method");
    }

    public static void staticMethod2() {
        System.out.println("This is static method2");
    }
}
What will happen when you execute the above code? You will see below output.
This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is constructor
This is static method2

Now let's see the output. First all static blocks are positioned in the code and they are executed when the class is loaded into JVM. Since the static method staticMethod() is called inside third static block, its executed before calling the main method. But the staticMethod2() static method is executed after the class is instantiated because it is being called after the instantiation of the class.

Again if you miss to precede the block with "static" keyword, the block is called "constructor block" and will be executed when the class is instantiated. The constructor block will be copied into each constructor of the class. Say for example you have four parameterized constructors, then four copies of contructor blocks will be placed inside the constructor, one for each. Lets execute the below example and see the output.
public class ConstructorBlockExample{

    {
        System.out.println("This is first constructor block");
    }

    public ConstructorBlockExample(){
        System.out.println("This is no parameter constructor");
    }

    public ConstructorBlockExample(String param1){
        System.out.println("This is single parameter constructor");
    }

    public ConstructorBlockExample(String param1, String param2){
        System.out.println("This is two parameters constructor");
    }

    {
        System.out.println("This is second constructor block");
    }

    public static void main(String[] args){
        ConstructorBlockExample constrBlockEx = new ConstructorBlockExample();
        ConstructorBlockExample constrBlockEx1 = new ConstructorBlockExample("param1");
        ConstructorBlockExample constrBlockEx2 = new ConstructorBlockExample("param1", "param2");
    }
}
The output is.
This is no parameter constructor
This is first constructor block
This is second constructor block
This is single parameter constructor
This is first constructor block
This is second constructor block
This is second parameter constructor
This is first constructor block
This is second constructor block

Now let's go back to static blocks.
There is an alternative to static blocks -you can write a private static method.
class PrivateStaticMethodExample {
    public static varType myVar = initializeClassVariable();
	
    private static varType initializeClassVariable() {
        //initialization code goes here
    }
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a 'public' static method can't do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method 'public'.
Advantages
oIf you're loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives.
oIf you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded. oSecurity related issues or logging related tasks

Limitations
oThere is a limitation of JVM that a static initializer block should not exceed 64K.
oYou cannot throw Checked Exceptions.
oYou cannot use 'this' keyword since there is no instance.
oYou shouldn't try to access 'super' since there is no such a thing for static blocks.
oYou should not return anything from this block.
oStatic blocks make testing a nightmare.

Servlets & JSP:



If any class qualifies as servlet that class must be subclass of Servlet interface directly or indirectly. The Servlet interface has three methods which play the key role in servlet life cycle. The three method of servlet life cycle are:

Init()
Service()
Destroy()

The life cycle of a servlet starts only and only when a call is given to that servlet.

Whenever a request is going to server for a servlet, the server looks for a particular servlet instance. If the instance is not found, it will be created and the init() method of that servlet will be called. Calling of the init() method is one time process in life cycle of the servlet. And a thread will be allocated to process the same request.

So whenever we are giving the first request to the server for servlet, it takes the URL pattern and identify by the URL that which servlet has to call. And then creates the object of that and calls the init() method.

If you make the second request for same servlet than server will not create a new object for that servlet and also do not call the init() method also. A new thread will be created and will be allocated to handle the request.

So if ten different requests are coming at the same time for same servlet then server will allocate thread to each request using one object.

After allocating thread, the service () method of the servlet will be called where the main business logic will be executed and give response back to the request.

So the service method will be called for each request.

Finally whenever the servlet object become amended for much time or server is going down the destroy () method of servlet will be called.

A diagram of the servlet life cycle is given below.



The doGet() and doPost() methods are specefically meant for a servlet which extends HttpServlet which in itself extends GenericServlet class.

So whenever a request comes up firstly it goes to service() method which redirects it to doGet() or doPost() method depending on the request i.e if it is get type request it will go to doGet() and if its kinda POST request it will go to doPost().

Any sub class of javax.servet.Servlet is considered as servlet, this Servlet Interface contains 3 life cycle methods (ofcourse 2 more methods r there) namely init(),service(),destroy().

API providing built in abstract class javax.servlet.GenericServlet with one abstract method service(), it provides basic implementation of all other methods. GenericServlet is protocol independent, you can use these for your custom protocol also, now comming to javax.servlet.http.HttpServlet. (which extends GenericServlet) this is for only http protocol, in this class service() method is implemented, internally service method will call doGet()/doPost()/doTrace()/doDelete()/doPut() etc. dependent on the http method.

Coming to difference between doGet() and doPost... we should say it as diff b/w http get and post methods. the major difference is about security..

In GET, the param values (in a web form) will be appended at the address bar in browser, hence not secure, limited data can be sent through get, and this is the default method (for html form)

Whereas POST is secure as it will not show the param values on address bar of browser. We can send huge data through post method

Initially every request reaches to service() method and depends on http method, service method calls doGet()/doPost() etc...
----------------
A Generic servlet contains the following five methods:

init()
public void init(ServletConfig config) throws ServletException
The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service.

The servlet cannot be put into the service if
* The init() method does not return within a fix time set by the web server.
* It throws a ServletException

Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred.

service() BR>
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and javax.servlet.ServletResponse are passed by the servlet container.

The status code of the response always should be set for a servlet that throws or sends an error

Parameters - The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception

getServletConfig()

public ServletConfig getServletConfig()

This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented, it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.

Returns - the ServletConfig object

getServletInfo()

public String getServletInfo()

The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup.

Returns - a string that contains the information about the servlet

destroy()

public void destroy()

This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held.


A RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be another servlet, or an HTML file, or a JSP file, etc.

You can also think of a RequestDispatcher object as a wrapper for the resource located at a given path that is supplied as an argument to the getRequestDispatcher method.

For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher() method or the ServletContext.getRequestDispatcher() method. They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same webapp to which the invoking servlet belongs and the pathname specified can be relative to invoking servlet. For the latter, the pathname must begin with '/' and is interpreted relative to the root of the webapp.

To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both in the same directory, you could accomplish this by incorporating the following code fragment in either the service method or the doGet method of Servlet_A:

   RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B");
   dispatcher.forward( request, response );


where request, of type HttpServletRequest, is the first parameter of the enclosing service method (or the doGet method) and response, of type HttpServletResponse, the second. You could accomplish the same by

  RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/servlet/Servlet_B" );
   dispatcher.forward( request, response );


RequestDispatcher creation and using.
public class Dispatcher extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse res) {
	    RequestDispatcher dispatcher = request.getRequestDispatcher("/template.jsp");
	    if (dispatcher != null) 
	   dispatcher.forward(request, response);
	}
}
		



The forward() should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward
public class Dispatcher extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse res) {
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");
		if (dispatcher != null) 
		dispatcher.include(request, response);
	}
}

Following diagram shows the different life cycle stages of jsp. Broadly, these stages can be classified into three.
* Instantiation
* Request Processing
* Destruction




Instantiation: When a web container receives a jsp request (may be first or subsequent), it checks for the jsp's servlet instance. If no servlet instance is available or if it is older than the jsp, then, the web container creates the servlet instance using following stages.
* Translation
* Compilation
* Loading
* Instantiation
* Initialization

Translation:
Web container translates (converts) the jsp code into a servlet code. This means that jsp is actually a servlet. After this stage, there is no jsp, everything is a servlet. This task will create a complete jsp page, by considering all included components. Here on, the static content and dynamic contents are treated differently. The resultant is a java class instead of an html page (which we wrote).
The below is how the structure of a jsp compiled into a java class will be.
package org.apache.jsp.WEB_002dINF.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class firstJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {
  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
  ............
  ............
  public Object getDependants() {
    return _jspx_dependants;
  }
  public void _jspInit() {
	............
	............
  }
  public void _jspDestroy() {
	............
	............
  }
  public void _jspService(HttpServletRequest request,
    HttpServletResponse response)
        throws java.io.IOException, ServletException {
	............
	............
  }
	............
	............
}

Compilation:
The generated servlet is compiled to validate the syntax. As it is a java class, the compilation is done using javac command. This will generate the byte code to be run on JVM. Loading:
The compiled byte code is loaded by the class loader used by web container. This is a standard process of using any java class. Instantiation:
In this step, instance of the servlet class is created so that it can serve the request.
Initialization:
Initialization is done by calling the jspInit() method. This is one time activity at the start of the initialization process. Initialization will make the ServletContext and ServletConfig objects available. One can access many attributes related to the web container and the servlet itself. After initialization the servlet is ready to process requests. Request Processing:
Entire initialization process is done to make the servlet available in order to process the incoming request. jspService() is the method that actually processes the request. It prints the response in html (any other) format, using 'out' object.
Destroy:
Whenever the server is shutting down or when the server needs memory, the server removes the instance of the servlet. The destroy method jspDestroy() can be called by the server after initialization and before or after request processing. Once destroyed the jsp needs to be initialized again.
Just to summarize, web container handles incoming requests to a jsp by converting it into a servlet and then by using this servlet to generate the response. Also when the server shuts down, the container needs to clear the instances.

Controlling Life Cycle: In above discussion, we understood that the jsp initialization phase happens when the first request hits the web container. This might take more time to present the response to the first user of jsp. It should be possible to keep initialized servlets ready to receive first request and immediately return response. This can be achieved by using the attributes provided by web and application server. The attribute can be "load-on-startup", "pre compile" etc.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class ExampleServlet extends HttpServlet {
    
    
    protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        printPageStart(out);
        
        //Obtain the session object, create a new session if doesn't exist
        HttpSession session = request.getSession(true);
        
        //Check if our session variable is set, if so, get the session variable value
        //which is an Integer object, and add one to the value.
        //If the value is not set, create an Integer object with the default value 1.
        //Add the variable to the session overwriting any possible present values.
        Integer param = (Integer) session.getAttribute("MySessionVariable");
        if (param != null) {
            
            session.setAttribute("MySessionVariable", new Integer(param.intValue() + 1));
            param = (Integer) session.getAttribute("MySessionVariable");
            
        } else {
            
            param = new Integer(1);
            session.setAttribute("MySessionVariable", param);
            
        }
        
        out.println("You have displayed this page " + param.intValue() + " times this session.

"); out.println("Hit the browsers refresh button."); printPageEnd(out); } /** Prints out the start of the html page * @param out the PrintWriter object */ private void printPageStart(PrintWriter out) { out.println(""); out.println(""); out.println("Example Servlet of how to store and retrieve session variables"); out.println(""); out.println(""); } /** Prints out the end of the html page * @param out the PrintWriter object */ private void printPageEnd(PrintWriter out) { out.println(""); out.println(""); out.close(); } }
session = request.getSession(false);
The 'true' argument specifies that getSession should create one if one doesn't already exist, otherwise return the existing one.
session = request.getSession(false);
retrieves a session if already a exists otherwise it should return "null".
However, in your case where are you invalidating the session? The servlet container creates a session for you by default. Hence, if you want to make sure that you always want to use a new session, then your code should look like:

// Try retrieving any existing session
HttpSession session = request.getSession(false);

// If session already exists, clear by invalidating the same.
if (session != null)
{
session.invalidate();
}
// Create new session now.
session = request.getSession(true);
We need to follow the above steps since
HttpSession session = request.getSession(true); 
does not always ensures the creation of new session
---------------------------------
For JSPs, by default a session is created. So if you are starting page is a JSP, a session would have already been created when you get the first request. So if you are using a JSP as the starting point try adding this decoration to your page:


<%@ page session="false" %> ............................JSP code..................

This will prevent a session from being created when a JSP is served.
In this lesson we will learn about the various tags available in JSP with suitable examples. JSP tags can be devided into 4 different types. These are:
1. Directives
In the directives we can import packages, define error handling pages or the session information of the JSP page.
2. Declarations
This tag is used for defining the functions and variables to be used in the JSP.
3. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.
4. Expressions
We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream.

Now we will examine each tags in details with examples.
DIRECTIVES :
Syntax of JSP directives is:
<%@directive attribute="value" %> Where directive may be:
1. page: page is used to provide the information about it.
Example: <%@page language="java" %>
2. include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to define our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
and attribute may be:
1. language="java"
This tells the server that the page is using the java language. Current JSP specification supports only java language.
Example: <%@page language="java" %>
2. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages.
Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %>
3. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this value is true.
Example: <%@page language="java" session="true" %>
4. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>
5. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %>


No comments:

Post a Comment