1. equals will only compare what it is written to compare, no more, no less.
  2. if a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
  3. If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you’re left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
  4. Always remember to override hashCode if you override equals so as not to “break the contract”. As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods shows that they are equivalent. The converse is not necessarily true.

With respect to the String class:

The equals() method compares the “value” inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn’t make a difference. Its the “value” (that is: the contents of the character array) inside each String instance that is being compared.

On the other hand, the “==” operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references “refer to” the same String instance then the result of the boolean expression would be “true”..duh. If, on the other hand, the value of both object references “refer to” different String instances (even though both String instances have identical “values”, that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be “false”.

You will have to override the equals function (along with others) to use this with custom classes.

The equals method compares the objects.

“==” is an operator and “equals” is a method. operators are used for primitive type comparisons and so “==” is used for memory address comparison.”equals” method is used for comparing objects.

The Behavior of equals on class which is final is different.So it is on ENUM.

final class A
{
    // static
    public static String s;
    A()
    {
        this.s = new String( "aTest" );
    }
}

final class B
{
    private String s;
    B()
    {
        this.s = new String( "aTest" );
    }

    public String getS()
    {
        return s;
    }
}

First is the Normal working of equals over a String

public final class MyEqualityTest
{
    public static void main( String args[] )
    {
        String s1 = new String( "Test" );
        String s2 = new String( "Test" );

        System.out.println( "\n1 - PRIMITIVES ");
        System.out.println( s1 == s2 ); // false
        System.out.println( s1.equals( s2 )); // true
    }
}

Now lets see how equals work in final class

 A a1 = new A();
 A a2 = new A();

System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
System.out.println( a1 == a2 ); // false
System.out.println( a1.s == a2.s ); // true
System.out.println( a1.s.equals( a2.s ) ); // true

In the above you can see that a1.s == a2.s is true.This is because s is static variable and its is possible to have only one instance.(Investigate Further)

Third case is which is well know.

  B b1 = new B();
  B b2 = new B();

  System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
  System.out.println( b1 == b2 ); // false
  System.out.println( b1.getS() == b2.getS() ); // false
  System.out.println( b1.getS().equals( b2.getS() ) ); // true

How to override equals method
Now I have a Person class which has Name and Age as class variables.I want to override equals method so that I can check between 2 People objects.

public class Person 
{
private String name;
private int age;

public Person(String name, int age){
    this.name = name;
    this.age = age;
}

@Override
public boolean equals(Object obj) 
{
    if (obj == null) {
        return false;
    }

    if (!Person.class.isAssignableFrom(obj.getClass())) {
        return false;
    }

    final Person other = (Person) obj;

    if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
        return false;
    }

    if (this.age != other.age) {
        return false;
    }
    return true;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
    hash = 53 * hash + this.age;
    return hash;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public String getName() {
    return name;
}

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

TestEquals.java

public class TestEquals
{
  public static void main(String[] args) 
  {  
    ArrayList<Person> people = new ArrayList<Person>();
    people.add(new Person("Mugil",30));
    people.add(new Person("Susan",23));
    people.add(new Person("Madhu",32));
    people.add(new Person("Monolisa",25));

    Person checkPerson = new Person();

    for (int i=0;i<people.size()-1;i++)
    {
            System.out.println("-- " + checkPerson.getName() + " - VS - " + people.get(i).getName());
            boolean check = people.get(i).equals(checkPerson);
            System.out.println(check);
    }
  }
}

You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals()

1.Compile the Files which should be added.

javac Test.java

Incase you are working in eclipse the same thing can be seen under the bin directory in the Navigator tab.you need to navigate to the folder to access the class files.

2.Manifest.txt
Incase if you are going to run the jar file the main class which should be called should be added to JAR file as meta-data through META-DATA/MANIFEST.There should be a Carriage Return Empty line in Manifest.txt to get read properly

Manifest.txt

Main-Class: com.mugil.util.Test

3.Create JAR file using the Below command

jar cfm Test.jar manifest.txt com/mugil/util/*

The Above command should be executed from bin directory in our case

* specifies the list of all files in that folder

4.To Run this JAR file

 java -jar Test.jar

When you run the Created Jar file it should be exactly placed in the folder from where the com folder starts.

jar cfm Test.jar manifest.txt com/mugil/util/*

The letters “m” and “f” must appear in the same order that “manifest” and “jarfile” appear.

It is a metadata file that contains name-value pairs organized in different sections.

If a JAR file is intended to be used as an executable file, the manifest file specifies the main class of the application. The manifest file is named MANIFEST.MF

Other uses are:

  1. store hashes of stored files for signature validation
  2. sealing jar files (i.e. ensure that only classes from this jar file are loaded in the packages defined in this jar file).
  3. store version/product/producer information to be readable at runtime

The Main class to be called once the JAR is executed is defined as below

If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method

Manifest-Version: 1.0
Main-Class: com.mugil.util.Test

While Using JSON Array for adding Details the required filter parameter in the Array may appear in any part of the Array.To Filter the Array which has many multiple data types i.e String, Integer, boolean you need to do instanceof comparison

In the below JSON array has a List of Employee Details from which Employee from a Particular location is taken out after Filtering

 
 package com.mugil.json;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;

public class Employee {

	public static void main(String[] args) {
		String Location = "Chennai";
		JSONArray arrEmpDetails = getEmpList();

		System.out
				.println("*-----------------Before Filter-----------------------------*");
		displayEmpDetails(arrEmpDetails);
		arrEmpDetails = filterEmpByLocation(arrEmpDetails, Location);

		System.out
				.println("*-----------------After Filter-----------------------------*");
		displayEmpDetails(arrEmpDetails);
		System.out
				.println("*-----------------------------------------------------*");

	}

	private static void displayEmpDetails(JSONArray arrEmpDetails) {
		JSONArray arrEmpDet = new JSONArray();

		for (int i = 0; i < arrEmpDetails.length(); i++) {
			try {
				arrEmpDet = arrEmpDetails.getJSONArray(i);
				System.out.println(arrEmpDet);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	private static JSONArray filterEmpByLocation(JSONArray arrEmpDetails,
			String location) {
		JSONArray arrEmpByLoc = new JSONArray();
		String strToComp = null;
		boolean isSameLoc = false;

		for (int i = 0; i < arrEmpDetails.length(); i++) {
			try {
				JSONArray type = arrEmpDetails.getJSONArray(i);

				for (int j = 0; j < type.length(); j++) {
					Object strString = type.get(j);
					if (strString instanceof java.lang.String) {
						strToComp = (String) strString;
						isSameLoc = strToComp.equals(location);
					}
				}

				if (isSameLoc) {
					arrEmpByLoc.put(type);
					isSameLoc = false;
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return arrEmpByLoc;
	}

	public static JSONArray getEmpList() {
		JSONArray arrEmpDetails = new JSONArray();
		JSONArray arrPerDetails = new JSONArray();

		arrPerDetails.put("Empl1");
		arrPerDetails.put(23);
		arrPerDetails.put("Address1");
		arrPerDetails.put("Chennai");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl2");
		arrPerDetails.put(23);
		arrPerDetails.put("Address2");
		arrPerDetails.put("Coimbatore");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl3");
		arrPerDetails.put(24);
		arrPerDetails.put("Address3");
		arrPerDetails.put("Tirchy");
		arrEmpDetails.put(arrPerDetails);

		arrPerDetails = new JSONArray();
		arrPerDetails.put("Empl4");
		arrPerDetails.put(26);
		arrPerDetails.put("Address4");
		arrPerDetails.put("Chennai");
		arrEmpDetails.put(arrPerDetails);

		return arrEmpDetails;
	}

}

“Reflection” is a language’s ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

For example, all objects in Java has the method getClass, which lets you determine its class even if you don’t know it at compile time (like if you declared it as Object) – this might seem trivial, but such reflection is not by default possible in less dynamic languages such as C++.

Why do we need reflection?

Reflection enables us to:

  1. Examine an object’s class at runtime
  2. Construct an object for a class at runtime
  3. Examine a class’s field and method at runtime
  4. Invoke any method of an object at runtime
  5. Change accessibility flag of Constructor, Method and Field
    etc.

Reflection is important since it lets you write programs that does not have to “know” everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Lets see the simple example of forName() method.

    class Simple{}  
      
    class Test{  
     public static void main(String args[]){  
      Class c=Class.forName("Simple");  
      System.out.println(c.getName());  
     }  
    }  

For example, say you have an object of an unknown type in Java, and you would like to call a ‘doSomething’ method on it if one exists. Java’s static typing system isn’t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called ‘doSomething’ and then call it if you want to.

So, to give you a code example of this in Java (imagine the object in question is foo) :

Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);

Getting list of methods in a Class by Reflection

Method[] methods = MyObject.class.getMethods();

for(Method method : methods){
    System.out.println("method = " + method.getName());
}

Details which can be accessed by reflection

  1. Class Name
  2. Class Modifies (public, private, synchronized etc.)
  3. Package Info
  4. Implemented Interfaces
  5. Superclass
  6. Constructors
  7. Fields
  8. Methods
  9. Annotations

Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection.

It is frequently used in scenarios where a class name changes frequently. If such a situation arises, then it is complicated for the programmer to rewrite the application and change the name of the class again and again.

Drawbacks
Since everything is done at runtime optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Usage

  1. Reflection is used when it is needed to get into the other classes in deeper level. So in most of the cases, these implementors have the container-behavior. For instance, dependency injection is mostly done with the use of reflection
  2. Remote procedure calling — treat part of a message received over the network as a method name.
  3. Object-relational mappings — maintain a relationship between fields in an object and columns in a database.
  4. Interfaces with dynamically typed scripting languages — turn a string value produced by a scripting language into a reference to a field or method on an object.
  5. Serialization and deserialization — convert field names to string so you can write the object’s fields to a stream and later convert it back into an object.

One useful real-world use of reflection is when writing a framework that has to interoperate with user-defined classes, where th framework author doesn’t know what the members (or even the classes) will be. Reflection allows them to deal with any class without knowing it in advance. For instance, I don’t think it would be possible to write a complex aspect-oriented librory without reflection.

Servlet Mapping in web.xml and Junit annotations are other where reflection is used.

For example, JUnit use reflection to look through methods tagged with the @Test annotation, and then call those methods when running the unit test. (Here is a set of examples of how to use JUnit.)

For web frameworks, product developers define their own implementation of interfaces and classes and put is in the configuration files. Using reflection, it can quickly dynamically initialize the classes required.

For example, Spring uses bean configuration such as:

<bean id="someID" class="com.programcreek.Foo">
    <property name="someField" value="someValue" />
</bean>

When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument “com.programcreek.Foo” to instantiate that Class. It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.

The same mechanism is also used for Servlet web applications:

<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.programcreek.WhyReflectionServlet</servlet-class>
<servlet>
 Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);

The above returns actual maximum for current month. For example it is February of leap year now, so it returns 29.

And to get last day as Date object:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

Date lastDayOfMonth = cal.getTime();

Invocation of toString on an array

private String [] arrActions;

public String [] getArrActions() {
  return arrActions;
}

public void setArrActions(String [] parrActions) {
  this.arrActions = parrActions;
}

String action = null;

if(form.getArrActions() != null){
  action = form.getArrActions().toString;
}

Bug Code

  action = form.getArrActions().toString;

Fix Code

  action = Arrays.toString(form.getArrActions());

——————————————————————————————————————————————————————

Incorrect lazy initialization and Update of Static Field

Below is the Sample code trying to implement Singleton pattern without synchronized

public static Object getInstance() {
    if (instance != null) {
        return instance;
    }

    instance = new Object();
    return instance;
}

In a multi thread environment, there would be potential for your singleton to be created more than once with your current code.

The race condition here is on the if check. On the first call, a thread will get into the if check, and will create the instance and assign it to ‘instance’. But there is potential for another thread to become active between the if check and the instance creation/assignment. This thread could also pass the if check because the assignment hasn’t happened yet. Therefore, two (or more, if more threads got in) instances would be created, and your threads would have references to different objects.

The solution for this can be in Two Ways
Solution 1

private static volatile Object myLock = new Object(); // must be declared volatile

public static Object getInstance() {
    if (instance == null) { // avoid sync penalty if we can
        synchronized (MyCurrentClass.myLock) { // declare a private static Object to use for mutex
            if (instance == null) {  // have to do this inside the sync
                instance = new Object();
            }
        }
    }

    return instance;
}

For more Details on Volatile memory refer the following Link
http://tutorials.jenkov.com/java-concurrency/volatile.html

Solution 2

public synchronized static Object getInstance() {
    if (instance == null) {
        instance = new Object();
    }

    return instance;
}

——————————————————————————————————————————————————————
Covariant Equals method Defined

When equals method not properly overridden in your class then this Error is Thrown.

Things to Check
1.The Passing parameter should be Object Type.

Code for Overridding equals() method

public boolean equals(Object other){
    boolean result;
    if((other == null) || (getClass() != other.getClass())){
        result = false;
    } // end if
    else{
        People otherPeople = (People)other;
        result = name.equals(otherPeople.name) &&  age == otherPeople.age;
    } // end else

    return result;
} // end equals

——————————————————————————————————————————————————————

int value cast to float and then passed to Math.round

 public static String createFileSizeString(big size)
 {
   if (size < 1048576)
   {
     return (Math.round(((size * 10) / 1024)) / 10) + " KB";
   }
 }

Math.round was intended to be used on floating point arithmetic.The (size*10)/1024 may or may not return float value.So we should explicitly convert to float before using math.round

  (size * 10) / 1024 

should be

  ((float)size * 10) / 1024

——————————————————————————————————————————————————————
Bad comparison of nonnegative value with negative constant

 if (rows.size() < 0 || rows.isEmpty()) {
 .
 .
 .
 }

rows.size() can either be 0 or Positive Integer

 if (rows.size() < 0 || rows.isEmpty()) 

Should be

 if (rows.size() <= 0 || rows.isEmpty()) 

——————————————————————————————————————————————————————
the parameter is dead upon entry

 public void TestSample(boolean status)
 {
  .
  . 
  .
  status = true;
 }

The Parameter status is set to true and it was never used.So we can simply remove it as shown below

 public void TestSample(boolean status)
 {
  .
  . 
  .
 }

——————————————————————————————————————————————————————
Null value guaranteed to be De referenced
Solution
Check for null value of the Bean before calling bean method

 .
 shipmentBean.getStatus();
 .

should be

 .
 (shipmentBean==null?null:shipmentBean.getStatus());
 .

——————————————————————————————————————————————————————
Suspicious reference Comparison
Suspicious reference Comparison of Long

  Long val1 = 127L;
  Long val2 = 127L;

  System.out.println(val1 == val2);

  Long val3 = 128L;
  Long val4 = 128L;

  System.out.println(val3 == val4);

Output

 true
 false

This is happening because you are comparing Long objects references, not long primitives values.

To safely do this comparison you want (still using Long objects), you have the following options:

 System.out.println(val3.equals(val4));                    // true
 System.out.println(val3.longValue() == val4.longValue()); // true
 System.out.println((long)val3 == (long)val4);             // true

Java caches the primitive values from -128 to 127. When we compare two Long objects java internally type cast it to primitive value and compare it. But above 127 the Long object will not get type caste. Java caches the output by .valueOf() method.

This caching works for Byte, Short, Long from -128 to 127. For Integer caching works From -128 to java.lang.Integer.IntegerCache.high or 127.

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

——————————————————————————————————————————————————————

Convert double to BigDecimal and set BigDecimal Precision

new BigDecimal(0.1)

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625.

This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

 new BigDecimal(0.1)

should be

 BigDecimal.valueOf(0.1)

Value that is returned by BigDecimal.valueOf is equal to that resulting from invocation of

Double.toString(double).

——————————————————————————————————————————————————————
Dead store to Local Variable

public class Foo
{
    public static void Bar()
    {
    
    }
}

public class Abc
{
    public void Test()
    {
      Foo objFoo = new Foo(); 
      objFoo.Bar();

    }
}

Bug

    Foo objFoo = new Foo(); 
    objFoo.Bar(); 

Fix

   Foo.Bar();

If I look at code someVariable.SomeMethod() I expect it to use the value of someVariable. If SomeMethod() is a static method, that expectation is invalid. Java won’t let you use a potentially uninitialized variable to call a static method, despite the fact that the only information it’s going to use is the declared type of the variable.

Creating Database Connection in Context.xml

<Context>
  <Resource name="jdbc/[YourDatabaseName]"  auth="Container" type="javax.sql.DataSource"
   username="[DatabaseUsername]" password="[DatabasePassword]" driverClassName="com.mysql.jdbc.Driver"
   url="jdbc:mysql:/[yourserver]:3306/[yourapplication]" maxActive="15" maxIdle="3"/>
</Context>

context.xml

<Context>
  <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
    maxActive="100" maxIdle="30" maxWait="10000" username="root" password="" driverClassName="com.mysql.jdbc.Driver"  url="jdbc:mysql://localhost:3306/test"/>
  <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Test.java

 PrintWriter out = response.getWriter();
 String Sno = request.getParameter("t1");
 String Name = request.getParameter("t2");
		
 try{
   InitialContext context = new InitialContext();
   DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/test");
   Connection conn  = ds.getConnection();
   PreparedStatement statement = conn.prepareStatement("insert into Details values(?,?)");
   statement.setString(1, Sno);
   statement.setString(2, Name);
   statement.execute();
   conn.close();
   statement.close();
   out.println("Done");
  }catch (Exception e) {
   e.printStackTrace();
  }

Working with ENUM
ENUM is just a list of set of value which are static and final.Executing the below code will have a output like one below

public class Test {
	public enum Company {
		EBAY, PAYPAL, GOOGLE, YAHOO, ATT
	}

	public static void main(String[] args) {
                System.out.println(Company.EBAY);
	}
}

Output

  EBAY

Now what you can do is to make this constant (static and final) to have further attributes like one below.

public enum Company {
EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
private int value;
 
private Company(int value) {
this.value = value;
}
}

and more Values with overloaded constructor

public class Test1 {

	public enum JobStatus {
		OPEN("Open", "Its Open", "1"), ERROR("Error", "Its a Error", "2"), WORKING(
				"Working", "Its Working", "3"), CLOSED("Closed", "Its Closed");
		private String	value;
		private String	label;
		private String	order;

		private JobStatus(String label, String value, String order) {
			this.label = label;
			this.value = value;
			this.order = order;
		}

		private JobStatus(String label, String value) {
			this.label = label;
			this.value = value;
		}

		public String getValue() {
			return this.value;
		}

		public String getLabel() {
			return this.label;
		}
	}

	public static void main(String[] args) {
		System.out.println(JobStatus.OPEN.value);
		System.out.println(JobStatus.OPEN.label);
		System.out.println(JobStatus.OPEN.order);
		System.out.println(JobStatus.CLOSED.order);
	}
}

Output

Its Open
Open
1
null

When you need a predefined list of values which do not represent some kind of numeric or textual data, you should use an enum. For instance, in a chess game you could represent the different types of pieces as an enum

enum ChessPiece {
PAWN,
ROOK,
KNIGHT,
BISHOP,
QUEEN,
KING;
}

Assigning Values to ENUM

public enum Company {
EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
private int value;
 
private Company(int value) {
this.value = value;
}
}
  • All enums implicitly extend java.lang.Enum.
  • MyEnum.values() returns an array of MyEnum’s values.
  • Enum constants are implicitly static and final and can not be changed once created.
  • Enum can be safely compare using “==” equality operator
  • An enum can be declared outside or inside a class, but NOT in a method.
  • An enum declared outside a class must NOT be marked static, final , abstract, protected , or private
  • Enums can contain constructors, methods, variables, and constant class bodies.
  • enum constructors can have arguments, and can be overloaded.

1.Utility Classes should have constants for variable

public class PolicyUtils 
{
 public static final String TOTAL_POLICY_LIMIT = "totalpolicylimit";
 requestHelper.setRequestAttribute(TOTAL_POLICY_LIMIT, policyLimit);
}

Since multiple Users can access the JSP page at same time assigning variable name to constant and changing it later makes it easy to change the actual variable name in case needed in future.

Posted in JSP.