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.

//Function declaration
function foo() { return 5; }

//Anonymous function expression
var foo = function() { return 5; }

//Named function expression
var foo = function foo() { return 5; }

function declarations loads before any code is executed.While function expressions loads only
when the interpreter reaches that line of code.

So if you try to call a function expression before it’s loaded, you’ll get an error

But if you call a function declaration, it’ll always work. Because no code can be called until all declarations are loaded.

Function Expression

  alert(foo()); // ERROR! foo wasn't loaded yet
  var foo = function() { return 5; } 

Function Declaration

  alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
  function foo() { return 5; } 

The difference is in First case foo() is defined at run-time, whereas in second case foo() is defined at parse-time
for a script block

Getting GMT Time for the Day

 var strDate = new Date();

 hour = strDate.getUTCHours().toString();
 minute = strDate.getUTCMinutes().toString();
 second = strDate.getUTCSeconds().toString();

 if (hour.length == 1) { hour = "0" + hour; }
 if (minute.length == 1) { minute = "0" + minute; }
 if (second.length == 1) { second = "0" + second; }

 Cal.SetHour(hour); 
 Cal.SetMinute(minute); 
 Cal.SetSecond(second);

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

How to check for overlapping events in a period

Case1: No Event between Period Start Date and Period End Date
Case2: No Event which subsets another event Period Start Date and Period End Date
Case3: No Event which starts before period start date and ends in between some other events end date
Case4: No Event which starts after some other event period start date and ends after events end date

oVERLAPPING eVENT

Where Clause:

SELECT count(event) 
  FROM tblEvent
 WHERE (new_event_start_date BETWEEN old_event_start_date and old_event_end_date OR
        new_event_end_date BETWEEN old_event_start_date and old_event_end_date) OR 
        new_event_start_date <= old_event_start_date OR new_event_end_date >= old_event_start_date

Case1,2,3:

     new_event_start_date BETWEEN old_event_start_date and old_event_end_date OR
     new_event_end_date BETWEEN old_event_start_date and old_event_end_date

Case4:

new_event_start_date <= old_event_start_date OR new_event_end_date >= old_event_start_date