“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>

In linux there the file access is based under three categories

 CurrentUser - Users in Group - Other Users
  drwxr-xr-x 


drwxr – CurrentUser can read, write and execute
xr – Users in Group can read and execute
x – Users can execute

 >>ls -l
-rw-r--r-- 1 root root    0 Apr 14 17:19 test.txt 

The test.txt file has only Read and Write access (rw) for Current User – Read access for Users in Group – Read access for other Users

 >>chmod u+x test.txt

Now the test.txt file has Execute access along with Read and Write as below

 >>ls -l
-rwxr--r-- 1 root root    0 Apr 14 17:19 test.txt

Giving Read wrtite to Group

 >>chmod g+r test.txt

Giving read right to Current User, Group Users and Other Users

 >>chmod a+r test.txt

Giving Execute right to Other Users

 >>chmod o+x test.txt

rwx – 111 7
r-x – 101 5
rw- – 110 6
rw- – 101 4
-wx – 011 3
-w- – 010 2
–x – 001 1
– 000 0

Example of binary format

 >>chmod 752  test.txt

Current User can rwx
Group User can r-x
Other User can -w-

Giving Multiple Permission for Multiple User Types at Once

 >>chmod u+r, o+x test.txt

How folders are organized
when you enter terminal the default location it takes is the location of the folder of the current user which
comes under /home/mugil(user logged In)

How to Login as a Root User

>> su
Password:

R
Logout of Root User

>> exit

Current Working Directory

>> pwd

Navigate Backward

>> cd ..
>> cd ../..

Navigate Forward

>> cd home/mugil

Home Directory

>> cd ~

Equivalent to Microsoft User Directory i.e My Documents

How to reset admin password

>> sudo passwd

How to Find Directory Files info

>> ls -l

Touch- Creates a Time Stamp

>> touch test.txt

If the file does not exist it creates new once else it updates just the time

Make new Directory

>> mkdir NewFolder

Moving File within folder that exist

>> mv test.txt NewFolder/

Copying File within folder that exist
Copies test.txt to NewFolder

>> cp test.txt NewFolder/

Copies test.txt to one folder above

>> cp test.txt ..

Deleting File that exist

>> rm test.txt 

Deleting File in folder that is not empty
-r recursive

>> rm -r NewFolder/

What is Telescoping Constructor Pattern?
In Java, there is no support for default values for constructor parameters. As a workaround, a technique called “Telescoping constructor” is often used. A class has multiple constructors, where each constructor calls a more specific constructor in the hierarchy, which has more parameters than itself, providing default values for the extra parameters.

We’ve all at some point encountered a class with a list of constructors where each addition adds a new option parameter

Pizza(int size) { ... }        
Pizza(int size, boolean cheese) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }

Disadvantage
This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

    public Pizza build() {
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder’s setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

Factory Patterns vs Builder Pattern
Consider a restaurant. The creation of “today’s meal” is a factory pattern, because you tell the kitchen “get me today’s meal” and the kitchen (factory) decides what object to generate, based on hidden criteria.

The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) “I need a pizza; add cheese, onions and bacon to it!” Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

 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();

java beans = default constructor + getters + setters

You want to model a person and in your model each person must have a name and surname.
In java beans convention you would have to
1) create a person and then
2) populate it with name and surname.

But in between 1 and 2 you have existing object that has inconsistent state, its a person without a name. in this trivial example it looks as a exaggeration but if you have a complex system it starts to matter.

Let’s see simple example

class Person {
   private String firstName;
   private String lastName;
   public String getFirstName() {return firstName;}
   public void setFirstName(String firstName) {this.firstName = firstName;}
   public String getLastName() {return lastName;}
   public void setLastName(String lastName) {this.lastName = lastName;}
}

The code creates instance of Person an initiates it:

Person president = new Person();
p.setFirstName("George");
p.setLastName("Bush");

From the above line of code the below can be incurred

  1. This means that the object is in constant state when all 3 lines are completed and in not consistent state before that.
  2. The object is indeed mutable: values that it calls may be changed by invoking of setter.

Our class Person is not thread-safe and therefore we cannot use it directly in multi threaded environment without thinking about syncrhonization.

Here is an example. Several years ago Barak Obama became the President of the US. How can we express this in code?

p.setFirstName("Barak");
p.setLastName("Obama");

In mutlti threaded environment the president object is in wrong state when when setFristName() had already completed and setLastName() has not called yet because the object contains “Barak Bush” that is obviously wrong.

What is the solution? Let’s make `Person immutable:

class Person {
   private final String firstName;
   private final String lastName;
   Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
   }

   public String getFirstName() {return firstName;}
   public String getLastName() {return lastName;}
}

As you can see there is not way to change either first or last name stored in object. The fields a final and do not have setters. So, our example looks like:

Person president = new Person("George", "Bush"); 
// elections..... 
president = new Person("Barak", "Obama");

Since Person is immutable we cannot re-use the old instance of Person and change its attribute. We have to create the new instance instead. If president is volatile reference assignment is atomic and therefore the code is thread safe.

Disadvantage
The problem of constructors is that they are not flexible. Our example has only 2 parameters. But think about real world when class Person has probably 20 or more field. In this case creating of such object is pretty verbose.

Moreover some fields can be optional. In this case you will probably want to create several overloaded constructors with different number of parameters. To avoid dupplicate assignemnt code it is common technique to use so called telescopic constructors

Few FAQ’s
Is using JavaBeans for data storage a bad practice and should be avoided, or is it perfectly safe?
No, is not a bad practice. Is not perfectly safe either. Depends on the situation.

The problem with mutable objects ( not with JavaBeans per se ) is using different threads to access them.

You have to synchronize the access to avoid one thread modify the object while other is accessing it.

Immutable objects doesn’t have this problem, because, .. well they can’t change, and thus, you don’t have to synchronize anything.

To make sure an object is immutable you have to declare your attributes as final.

class MyBean  {
    private final int i;
}

If you want to assign a reasonable value to MyBean.i you have to specify it in the constructor:

public MyBean( int i ) {
     this.i = i;
 }

Since the variable is final, you can’t use a setter. You can just provide a getter.

This is perfectly thread-safe and the best is, you don’t have to synchronize the access, because if two threads try to get the value of i they both will always see the value that was assigned on instantiation, you don’t have to synchronize anything.

Is not bad practice or good practice. Must of us have to work with a single thread, even in multithread environments like servlets.

How to set and change values if Immutable Objects
The Solution is to create immutable beans, and still provide a
bunch of setters is using Builders like

Setting Value

Employee e = new EmployeeBuilder()
                  .setName("Oscar")
                  .setLastName("Reyes")
                  .setAge(0x1F)
                  .setEmployeeId("123forme")
                  .build(); 

Which looks pretty similar to the regular setXyz used in regular beans with the benefit of using immutable data.

If you need to change one value, you can use a class method

Employee e = Employee.withName( e, "Mr. Oscar");

Which takes the existing object, and copy all the values, and set’s a new one….

public static EmployeeWithName( Employee e , String newName ){
      return new Employee( newName, e.lastName, e.age, e.employeeId );
}

But again, in a single thread model is perfectly safe to use getters/setters.

What is Static Factory Method

  1. static factory method pattern is a way to encapsulate object creation.This prevents unnecessary object creation through constructors
  2. The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.

Examples

  1. Limit the No of Instances to be Created – If the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null if it’s above the upper threshold.
  2. We can provide a meaningful name for our constructors

RandomIntGenerator.java

public class RandomIntGenerator {
  private final int min;
  private final int max;

  private RandomIntGenerator(int min, int max) {
    this.min = min;
    this.max = max;
  }

  public static RandomIntGenerator between(int max, int min) {
    return new RandomIntGenerator(min, max);
  }

  public static RandomIntGenerator biggerThan(int min) {
    return new RandomIntGenerator(min, Integer.MAX_VALUE);
  }

  public static RandomIntGenerator smallerThan(int max) {
    return new RandomIntGenerator(Integer.MIN_VALUE, max);
  }

  public int next() {...}
}
Foo x = new Foo() 

With this pattern, you would instead call the factory method:

Foo x = Foo.create()

The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.

When to use Static Factory Method
1.One is that the factory can choose from many subclasses (or implementers of an interface) and return that. This way the caller can specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy.

2.Controlling access to a limited resource such as connections. This a way to implement pools of reusable objects – instead of building, using, and tearing down an object, if the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null if it’s above the upper threshold.

3.Alternate to constructor overloading.

Example1 – Returning Object of many Subclass as per parameter

class Employee {
   private int empType;
   static final int ENGINEER = 0;
   static final int SALESMAN = 1;
   static final int MANAGER = 2;

   Employee (int type) {
       empType = type;
   }

I want to make subclasses of Employee to correspond to the type codes. So I need to create a factory method

static Employee create(int type) {
      return new Employee(type);
 }

I then change all callers of the constructor to use this new method and make the constructor private

client code...
   Employee eng = Employee.create(Employee.ENGINEER);

 class Employee...
   private Employee (int type) {
      empType = type;
}

So far I dont have any advantage from the code.The advantage come when I code the create method to return instances of different subclass of Employee.

static Employee create(int type) {
       switch (type) {
           case ENGINEER:
              return new Engineer();
           case SALESMAN:
              return new Salesman();
           case MANAGER:
              return new Manager();
           default:
              throw new IllegalArgumentException("Incorrect type code value");
       }
   }  

If you want to avoid making changes in the switch when ever new classes are added the above code can be replaced as below

static Employee create (String name) {
       try {
           return (Employee) Class.forName(name).newInstance();
       } catch (Exception e) {
           throw new IllegalArgumentException ("Unable to instantiate" + name);
       }
}

Now the calling class should be

 Employee.create("Engineer")

Example2 – Controlling access to Resources

public class DbConnection
{
   private static final int MAX_CONNS = 100;
   private static int totalConnections = 0;

   private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();

   private DbConnection()
   {
     // ...
     totalConnections++;
   }

   public static DbConnection getDbConnection()
   {
     if(totalConnections < MAX_CONNS)
     {
       return new DbConnection();
     }

     else if(availableConnections.size() > 0)
     {
         DbConnection dbc = availableConnections.iterator().next();
         availableConnections.remove(dbc);
         return dbc;
     }

     else {
       throw new NoDbConnections();
     }
   }

   public static void returnDbConnection(DbConnection dbc)
   {
     availableConnections.add(dbc);
     //...
   }
}
  1. The maximum connection allowed in the above case is 100
  2. Incase the no of connection created is above 100, Old connection is sent back in else part of code

Example3 – Alternate to Constructor Overloading
Link

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable

Immutable objects have a number of properties that make working with them easier, including relaxed synchronization requirements and the freedom to share and cache object references without concern for data corruption.

An immutable object is one whose externally visible state cannot change after it is instantiated. The String, Integer, and BigDecimal classes in the Java class library are examples of immutable objects — they represent a single value that cannot change over the lifetime of the object.

Immutable classes generally make the best map keys.

Potential problem with a mutable Date object

  Date d = new Date();
  Scheduler.scheduleTask(task1, d);
  d.setTime(d.getTime() + ONE_DAY);
  scheduler.scheduleTask(task2, d);

Since Date is mutable, the scheduleTask method must be careful to defensively copy the date parameter into its internal data structure. Otherwise, task1 and task2 might both execute tomorrow, which is not what was desired.

Classic Value Objects
Strings and integers and are often thought of as values. Therefore its not surprising to find that String class and the Integer wrapper class (as well as the other wrapper classes) are immutable in Java. A color is usually thought of as a value, thus the immutable Color class.

Playing Cards

Ever write a playing card program? I did. I could have represented a playing card as a mutable object with a mutable suit and rank. A draw-poker hand could be 5 fixed instances where replacing the 5th card in my hand would mean mutating the 5th playing card instance into a new card by changing its suit.

However, I tend to think of a playing card as an immutable object that has a fixed unchanging suit and rank once created. My draw poker hand would be 5 instances and replacing a card in my hand would involve discarding one of those instance and adding a new random instance to my hand.

Simple Immutable Class Code

public final class Employee
   {  
    final String pancardNumber;  
      
    public Employee(String pancardNumber){  
    this.pancardNumber=pancardNumber;  
    }  
      
    public String getPancardNumber(){  
    return pancardNumber;  
  }  
 }  
  1. The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
  2. The class is final so we cannot create the subclass.
  3. There is no setter methods i.e. we have no option to change the value of the instance variable.

Scenario

Event – Parent Event
Sub-Event – Child Event

1.The Events contains multiple sub events.
2.When there is Parent event, there should be No sub event of that Parent event in that same period
3.There can me more than one sub event of the same Parent event in the same period.There can be overlapping sub event.

 SELECT COUNT(ParentEventId)    
    FROM Events
   WHERE lower(status) = 'open'
     AND ParentEventId = p_parent_id
      AND (ChildEvent is null or p_child_event IS NULL OR
          ChildEvent = NVL(p_child_event, child_event))
     AND (p_startdate BETWEEN StartDate AND
          EndDate OR
          p_admin_enddate BETWEEN StartDate AND
          EndDate OR
          (p_startdate <= StartDate AND
          p_enddate >= EndDate));

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.