Thursday, 12 January 2017

Why does Java have transient fields?

The transient variables are never serialized during the Serialization process   and initialize with default value during Deserialization process.

The below example simplify the transient keyword uses. In this example we are consider the id field in Employee is transient variable. In this below example before Serialization Employee object value [id=100, name=Sitansu, Address=BBSR] and After Serialization the Employee object   [id=0, name=Sitansu, Address=BBSR]. This example shows the id field after Serialization assign to default value to 0.


package Java91.blogspot.in;

import java.io.Serializable;

public class Employee implements Serializable{
      
       private static final long serialVersionUID = 1L;
       private transient int id=100;
       private String name;
       private String Address;
      
       public Employee(int id,String name,String Address){
              this.id=id;
              this.name=name;
              this.Address=Address;
       }

       public int getId() {
              return id;
       }

       public void setId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

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

       public String getAddress() {
              return Address;
       }

       public void setAddress(String Address) {
              this.Address = Address;
       }

       @Override
       public String toString() {
              return "Employee [id=" + id + ", name=" + name + ", Address=" + Address + "]";
       }

}

package Java91.blogspot.in;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class DemoTransientTest {
         public static void main(String args[]) {
               
                Employee narnia = new Employee(100,"Sitansu","BBSR");
              System.out.println("Before Serialization: " + narnia);
            
               try {
                   FileOutputStream fos = new FileOutputStream("narnia.ser");
                   ObjectOutputStream oos = new ObjectOutputStream(fos);
                   oos.writeObject(narnia);

                   System.out.println("Employee details is successfully Serialized ");

                   FileInputStream fis = new FileInputStream("narnia.ser");
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   Employee oldNarnia = (Employee) ois.readObject();
                
                   System.out.println("Employee details successfully created from Serialized data");
                   System.out.println("Employee details after seriazliation : " + oldNarnia);
                
               } catch (Exception e) {
                   e.printStackTrace();
               }

           }

}


Output:
Before Serialization: Employee [id=100, name=Sitansu, Address=BBSR]
Employee details is successfully Serialized
Employee details successfully created from Serialized data

Employee details after seriazliation : Employee [id=0, name=Sitansu, Address=BBSR]

Wednesday, 11 January 2017

Convert double to float in java.

There are no on the way to convert the Double to Float.

Just cast your double to a float.
double d = getInfoValueNumeric();
float f = (float)d;
Also, notice that the primitive types can NOT store an infinite set of numbers:
float range: from 1.40129846432481707e-45 to 3.40282346638528860e+38
double range: from 1.7e308 to 1.7e+308

1) You can achieve it by using decimal formatter .

 double d = 2.342565656767E13;
     DecimalFormat decimalFormat = new DecimalFormat("#");
     System.out.println(decimalFormat.format(d));

2)You can also achieve it by Cast it .
double d = 2.342565656767E13;
float f = (float)d;

What is the best way of using Arrays.asList() to initialize a List.

  1. Arrays.asList(temp)
    It takes an array ia and creates a wrapper that implements List<String>, which makes the original array available as a list. Nothing is copied and all, only a single wrapper object is created. Operations on the list wrapper are propagated to the original array. This means that if you shuffle the list wrapper, the original array is shuffled as well, if you overwrite an element, it gets overwritten in the original array, etc. Of course, some List operations aren't allowed on the wrapper, like adding or removing elements from the list, you can only read or overwrite the elements.
    Note that the list wrapper doesn't extend ArrayList - it's a different kind of object. ArrayLists have their own, internal array, in which they store their elements, and are able to resize the internal arrays etc. The wrapper doesn't have its own internal array, it only propagates operations to the array given to it. On the other hand, if you subsequently create a new array as
  2. new ArrayList<String>(Arrays.asList(temp))
    then you create new ArrayList, which is a full, independent copy of the original one. Although here you create the wrapper using Arrays.asList as well, it is used only during the construction of the new ArrayList and is garbage-collected afterwards. The structure of this new ArrayListis completely independent of the original array. It contains the same elements (both the original array and this new ArrayList reference the same integers in memory), but it creates a new, internal array, that holds the references. So when you shuffle it, add, remove elements etc., the original array is unchanged.

Singleton design pattern in Java

Singleton design pattern

package swain.singleton.javainterviewhub.blogspot.in.designpattern.singleton;

public class SingleObject {

       public static SingleObject singleton = new SingleObject();

       private SingleObject() {

       }

       public static SingleObject getInstance() {
              return singleton;
       }
      
       public void showMessage(){
              System.out.println("hello world");
       }

}


package swain.singleton.javainterviewhub.blogspot.in.designpattern.singleton;

public class SingletonPatternDemo {

       public static void main(String[] args) {
              SingleObject singleObject=SingleObject.getInstance();
              singleObject.showMessage();
       }

}

There are three cases singleton class fail
1) Serialization :We can create multiple instance by searialization case.
2) Multi threading :Singleton class not thread safe
3) Class loader: We can create multiple instance with different class loader

Friday, 15 April 2016

How to get Start Date and End Date for Year, Month, Week in java ?

package com.product.webapp.utilities;

import java.util.Calendar;
import java.util.Date;

public class DateUtils {

public static Calendar[] getDateIntervals(IntervalType type, Calendar reference) {
if (reference == null) {
reference = Calendar.getInstance();
}
Calendar startDate = (Calendar) reference.clone();
Calendar endDate = (Calendar) reference.clone();
if (type == IntervalType.CurrentYear) {
// first date of the Year
startDate.set(Calendar.DAY_OF_YEAR, 1);

// current date of the Year
endDate.set(Calendar.YEAR, endDate.get(Calendar.YEAR));
} else if (type == IntervalType.LastYear) {
// first date of the Year
startDate.set(Calendar.YEAR, startDate.get(Calendar.YEAR) - 1);

// Last date of the Year
startDate.set(Calendar.DAY_OF_YEAR, 1);

endDate.add(Calendar.YEAR, -1);
endDate.set(Calendar.DAY_OF_YEAR, endDate.getActualMaximum(Calendar.DAY_OF_YEAR));
} else if (type == IntervalType.CurrentMonth) {
// first date of the month
startDate.set(Calendar.DAY_OF_MONTH, 1);

// first date of the month
endDate.set(Calendar.YEAR, endDate.get(Calendar.YEAR));

} else if (type == IntervalType.LastMonth) {
// previous month
startDate.add(Calendar.MONTH, -1);
startDate.set(Calendar.DATE, 1);
// previous month, last date
endDate.add(Calendar.MONTH, -1);
endDate.set(Calendar.DAY_OF_MONTH, endDate.getActualMaximum(Calendar.DAY_OF_MONTH));
} else if (type == IntervalType.YesterDay) {
startDate.add(Calendar.DATE, -1);
endDate.add(Calendar.DATE, -1);
} else if (type == IntervalType.Today) {
startDate.add(Calendar.DATE, 0);
endDate.add(Calendar.DATE, 0);
} else if (type == IntervalType.Last3Month) {
// previous month
startDate.add(Calendar.MONTH, -3);
startDate.set(Calendar.DATE, 1);
// previous month, last date
endDate.add(Calendar.MONTH, -1);
endDate.set(Calendar.DAY_OF_MONTH, endDate.getActualMaximum(Calendar.DAY_OF_MONTH));
} else if (type == IntervalType.Last6Month) {
// previous month
startDate.add(Calendar.MONTH, -6);
startDate.set(Calendar.DATE, 1);
// previous month, last date
endDate.add(Calendar.MONTH, -1);
endDate.set(Calendar.DAY_OF_MONTH, endDate.getActualMaximum(Calendar.DAY_OF_MONTH));
} else if (type == IntervalType.CurrentWeek) {

// current Week
startDate.add(Calendar.DAY_OF_WEEK, startDate.getFirstDayOfWeek() - startDate.get(Calendar.DAY_OF_WEEK));
// previous Week, last date
endDate.set(Calendar.YEAR, endDate.get(Calendar.YEAR));

} else if (type == IntervalType.LastWeek) {
// previous week by convention (monday ... sunday)
// you will have to adjust this a bit if you want
// sunday to be considered as the first day of the week.
// start date : decrement until first sunday then
// down to monday
int dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
while (dayOfWeek != Calendar.SUNDAY) {
startDate.add(Calendar.DATE, -1);
dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
}
while (dayOfWeek != Calendar.MONDAY) {
startDate.add(Calendar.DATE, -1);
dayOfWeek = startDate.get(Calendar.DAY_OF_WEEK);
}

// end date , decrement until the first sunday
dayOfWeek = endDate.get(Calendar.DAY_OF_WEEK);
while (dayOfWeek != Calendar.SUNDAY) {
endDate.add(Calendar.DATE, -1);
dayOfWeek = endDate.get(Calendar.DAY_OF_WEEK);
}
} else {
new Exception();
}
return new Calendar[] { startDate, endDate };
}

public static Date[] getCurrentWeek(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getLastWeek(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getCurrentMonth(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getLastMonth(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getLast3Month(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getLast6Month(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getCurrentYear(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getLastYear(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getYesterDay(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static Date[] getToday(IntervalType type, Calendar reference) {
Calendar[] results = DateUtils.getDateIntervals(type, null);
return new Date[] { getFormattedFromDateTime(results[0].getTime()), getFormattedToDateTime(results[1].getTime()) };
}

public static String getDateRangeNameByIntervalType(String intervalType) {
String dateName = "";
if (IntervalType.CurrentWeek.toString().equals(intervalType)) {
dateName = IntervalType.CurrentWeek.name();
} else if (IntervalType.LastWeek.toString().equals(intervalType)) {
dateName = IntervalType.LastWeek.name();
} else if (IntervalType.CurrentMonth.toString().equals(intervalType)) {
dateName = IntervalType.CurrentMonth.name();
} else if (IntervalType.LastMonth.toString().equals(intervalType)) {
dateName = IntervalType.LastMonth.name();
} else if (IntervalType.Last3Month.toString().equals(intervalType)) {
dateName = IntervalType.Last3Month.name();
} else if (IntervalType.Last6Month.toString().equals(intervalType)) {
dateName = IntervalType.Last6Month.name();
} else if (IntervalType.CurrentYear.toString().equals(intervalType)) {
dateName = IntervalType.CurrentYear.name();
} else if (IntervalType.LastYear.toString().equals(intervalType)) {
dateName = IntervalType.LastYear.name();
}
return dateName;
}

public static Date[] getDatesByIntervalType(String intervalType) {

Date[] dateRange = new Date[1];
if (IntervalType.CurrentWeek.toString().equals(intervalType)) {
dateRange = DateUtils.getCurrentWeek(IntervalType.CurrentWeek, null);
} else if (IntervalType.LastWeek.toString().equals(intervalType)) {
dateRange = DateUtils.getLastWeek(IntervalType.LastWeek, null);
} else if (IntervalType.CurrentMonth.toString().equals(intervalType)) {
dateRange = DateUtils.getCurrentMonth(IntervalType.CurrentMonth, null);
} else if (IntervalType.LastMonth.toString().equals(intervalType)) {
dateRange = DateUtils.getLastMonth(IntervalType.LastMonth, null);
} else if (IntervalType.Last3Month.toString().equals(intervalType)) {
dateRange = DateUtils.getLast3Month(IntervalType.Last3Month, null);
} else if (IntervalType.Last6Month.toString().equals(intervalType)) {
dateRange = DateUtils.getLast6Month(IntervalType.Last6Month, null);
} else if (IntervalType.CurrentYear.toString().equals(intervalType)) {
dateRange = DateUtils.getCurrentYear(IntervalType.CurrentYear, null);
} else if (IntervalType.LastYear.toString().equals(intervalType)) {
dateRange = DateUtils.getLastYear(IntervalType.LastYear, null);
} else if (IntervalType.YesterDay.toString().equals(intervalType)) {
dateRange = DateUtils.getYesterDay(IntervalType.YesterDay, null);
} else if (IntervalType.Today.toString().equals(intervalType)) {
dateRange = DateUtils.getToday(IntervalType.Today, null);
}

return dateRange;
}

private static Date getFormattedFromDateTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}

private static Date getFormattedToDateTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}

public static Date removeTime(Date date) {
       Calendar cal = Calendar.getInstance();
       cal.setTime(date);
       cal.set(Calendar.HOUR_OF_DAY, 0);
       cal.set(Calendar.MINUTE, 0);
       cal.set(Calendar.SECOND, 0);
       cal.set(Calendar.MILLISECOND, 0);
       return cal.getTime();
   }
}