Saturday, November 19, 2011
How to scale images in Java ?
public BufferedImage getScaledInstance(final BufferedImage img,
final int targetWidth, final int targetHeight, final Object hint,
final boolean higherQuality) {
final int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
: BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = img;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = img.getWidth();
h = img.getHeight();
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = targetWidth;
h = targetHeight;
}
do {
if (higherQuality && w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}
if (higherQuality && h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}
final BufferedImage tmp = new BufferedImage(w, h, type);
final Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
} while (w != targetWidth || h != targetHeight);
return ret;
}
public static void main(final String[] args) {
final File file = new File("c:\\fileImg.jpg");
try {
final BufferedImage img = ImageIO.read(file);
ImageIO.write(new ImageUtil().getScaledInstance(img, 72, 72,
RenderingHints.VALUE_INTERPOLATION_BICUBIC, true), "jpg",
new File("c:\\scaledImage.jpg"));
} catch (final IOException e) {
// AUTO Auto-generated catch block
e.printStackTrace();
}
}
}
Friday, November 18, 2011
Java Experienced Interview Questions
Friday, July 29, 2011
Increasing Heap Memory of Tomcat
Apache Tomcat
To increase minimum and maximum heap size for Tomcat applications set the CATALINA_OPTS environment variable before starting Tomcat. To set the same heap sizes, on UNIX edit the Tomcat startup.sh script and add a line:
export CATALINA_OPTS=-Xms16m -Xmx256m;
Wednesday, July 20, 2011
Load a comma delimited file (CSV) into the database
Load a comma delimited file (CSV) into the database:
Command: LOAD DATA LOCAL INFILE "/tmp/TableData.csv" INTO TABLE employer FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY """" LINES TERMINATED BY "\r\n" (Name, Dept, jobTitle);Monday, May 2, 2011
Address of a Java Object
In conventional java programming, you will never need address or location of a java object from memory. When you discuss about this in forums, the first question raised is why do you need to know the address of a java object? Its a valid question. But always, we reserve the right to experiment. Nothing is wrong in exploring uncharted areas.
I thought of experimenting using a little known class from sun package. Unsafe is a class that belongs to sun.misc package. For some of you the package might be new. You need not worry about it. If you have sun’s JDK then you have this class already.
When a class name is “Unsafe” in java, it calls for your attention immediately. Then I decided to dig deep into it and find what is unsafe about that class. Voila, it really opens up the pandora’s box. Its difficult to find the source of Unsafe. Get the source and look at the methods you will know what I am referring to.
Java’s security manager provides sufficient cover and ensures you don’t fiddle with memory that easily. As a first step, I thought of getting the memory location of a java object. Until the exploration, I too was 100% confident that it was not possible to find the location / address of an object in java.
Sun’s Unsafe.java api documentation shows us an opportunity to get the address using the method objectFieldOffset. That method says, “Report the location of a given field in the storage allocation of its class“. It also says, “it is just a cookie which is passed to the unsafe heap memory accessors“. Whatsoever, I am able to get the storage memory location of an object from the storage allocation of its class.
You can argue that, what we have got is not the absolute physical memory address of an object. But we have got the logical memory address. The following program will be quite interesting for you!
As a first step, I have to get an object of Unsafe class. It is quite difficult as the constructor is private. There is a method named getUnsafe which returns the unsafe object. Java’s security manager asks you to make your java source code privileged. I used little bit of reflection and got an instance out. I know there are better ways to get the instance. But to bypass the security easily I chose the following.
Using Unsafe’s object just invoke objectFieldOffset and staticFieldOffset. The result is address / location of object in the storage allocation of its class.
Following example program runs well on JDK 1.6
import sun.misc.Unsafe; |
import java.lang.reflect.Field; |
public class ObjectLocation { |
private static int apple = 10; |
private int orange = 10; |
public static void main(String[] args) throws Exception { |
Unsafe unsafe = getUnsafeInstance(); |
Field appleField = ObjectLocation.class.getDeclaredField("apple"); |
System.out.println("Location of Apple: " |
+ unsafe.staticFieldOffset(appleField)); |
Field orangeField = ObjectLocation.class.getDeclaredField("orange"); |
System.out.println("Location of Orange: " |
+ unsafe.objectFieldOffset(orangeField)); |
} |
private static Unsafe getUnsafeInstance() throws SecurityException, |
NoSuchFieldException, IllegalArgumentException, |
IllegalAccessException { |
Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe"); |
theUnsafeInstance.setAccessible(true); |
return (Unsafe) theUnsafeInstance.get(Unsafe.class); |
} |
} |
Index besed Access and Iterator based Access
Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the ‘n’ location and get the element. It doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the ‘n’th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.
Substring in Java
String s1 = "Monday";
String s = s1.substring(0,3);
or
s1.substring(0,3).equals("Mon")
substring is clever. It does not make a deep copy of the substring the way most languages do. It just creates a pointer into the original immutable String, i.e. points to the value char[] of the base string, and tracks the starting offset where the substring starts and count of how long the substring is.
The downside of this cleverness is a tiny substring of a giant base String could suppress garbage collection of that big String in memory even if the whole String were no longer needed. (actually its value char[] array is held in RAM; the String object itself could be collected.)
If you know a tiny substring is holding a giant string in RAM, that would otherwise be garbage collected, you can break the bond by using
String s = new String(s1.substring(0,3));
Comparision in Java
Consider the case in which >, == and >= operator are used for comparison.
long starttime = System.currentTimeMillis();
for (int i = 0; i < 8888888; i++) {
if (i == 10 || i < 10) {
}
}
System.out.println(“Total time taken case1″+(System.currentTimeMillis()-starttime));
starttime = System.currentTimeMillis();
for (int i = 0; i < 8888888; i++) {
if (i <= 10) {
}
}
System.out.println(“Total time taken case2″+(System.currentTimeMillis()-starttime));
Output is :
Total time taken case1 31ms
Total time taken case2 16ms
Just try to use code efficiently.
How does HashSet works
Hashset is used to store the unique elements, in which their is no gurantee of the iteration order.
Hashset internally use HashMap .
Elements passed to Hashset are stored as a key of the HashMap with null as value. Since the objects passed to set are key so no extra check is done to identify duplicates. For eg after adding integer 1 and 2 if i add 1 again, no check is performed to identify whether 1 is present or not. The hashset simply performs the put with the same value( ’1′) in this case as key.
Similariy when an element is removed from the Set the internal HashMap remove method is called.
So HashSet data structure is nothing but a HashMap with objects as key.
HashSet Implemenation from java.util package
- public HashSet() {
map = new HashMap();
} - public boolean add(E o) {
return map.put(o, PRESENT)==null;
} - /**
* Removes the specified element from this set if it is present.
*
* @param o object to be removed from this set, if present.
* @return true if the set contained the specified element.
*/
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
Integer Caching in Java 1.5 and above
What is the O/p of following ?
Integer i1 = 20;
Integer i2 = 20;
Integer i3 = 200;
Integer i4 = 200;
if(i1 == i2){
System.out.println("True");
}else{
System.out.println("False");
}
if(i3 == i4){
System.out.println("True");
}else{
System.out.println("False");
}
if(Integer.valueOf(20) == Integer.valueOf(20)){
System.out.println("True");
}else{
System.out.println("False");
}
if(Integer.valueOf(200) == Integer.valueOf(200)){
System.out.println("True");
}else{
System.out.println("False");
}
The answer is
True
False
True
False
It is because in JDK1.5 there is a new concept called Caching Integer Objects.
Until JDK1.5 it didn’t matter whether to use Integer.valueof() or new Integer() methods to create an integer object.But with the jdk1.5 feature it is recommended to use Integer.valueOf().
Reason : In JDK1.5 the JVM caches Integer objects from range of -128 to 127 . So every time an integer object is create with value between the above mentioned range same object will be returned instead of creating the new object.
For the given statement
Integer i1 = 20.
The autoboxing features come into play which uses again the Integer.valueOf() method to create an object and every time will return same object.
Note: This will not happen for Integer i1 = new Integer(20). // Something similar to String pool
The Integer class has an inner class called IntegerCache with the following implementation.
private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
int h = 127;
if (integerCacheHighPropValue != null) {
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
Since its an inner class, so the 256 objects will not be created until it is called for the first time. Hence, initial loading of the first integer object will be slow as cache array with 256 objects will be created.
The valueOf() method implementation is :
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
HashCode and Equals
Use of hashCode() and equals().
Object class provides two methods hashcode() and equals() to represent the identity of an object. It is a common convention that if one method is overridden then other should also be implemented.
Before explaining why, let see what the contract these two methods hold. As per the Java API documentation:
- Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
- If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
- It is NOT required that if two objects are unequal according to the equals(Java.lang.Object) method, then calling the hashCode() method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
Now, consider an example where the key used to store the in Hashmap is an Integer. Consider that Integer class doesn’t implement hashcode() method. The code would look like:
map.put(new Integer(5),”Value1″);
String value = (String) map.get(new Integer(5));
System.out.println(value);
//Output : Value is null
Null value will be displayed since the hashcode() method returns a different hash value for the Integer object created at line 2and JVM tries to search for the object at different location.
Now if the integer class has hashcode() method like:
public int hashCode(){
return value;
}
Everytime the new Integer object is created with same integer value passed; the Integer object will return the same hash value. Once the same hash value is returned, JVM will go to the same memory address every time and if in case there are more than one objects present for the same hash value it will use equals() method to identify the correct object.
Another step of caution that needs to be taken is that while implementing the hashcode() method the fields that are present in the hashcode() should not be the one which could change the state of object.
Consider the example:
public class FourWheeler implements Vehicle {
private String name;
private int purchaseValue;
private int noOfTyres;
public FourWheeler(){}
public FourWheeler(String name, int purchaseValue) {
this.name = name;
this.purchaseValue = purchaseValue;
}
public void setPurchaseValue(int purchaseValue) {
this.purchaseValue = purchaseValue;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + purchaseValue;
return result;
}
}
FourWheeler fourWObj = new FourWheeler(“Santro”,”333333);
map.put(fourWObj,”Hyundai);
fourWObj.setPurchaseValue(“555555)
System.out.println(map.get(fourWObj));
//Output: null
We can see that inspite of passing the same object the value returned is null. This is because the hashcode() returned on evaluation will be different since the purchaseValue is set to ‘555555’ from ‘333333’. Hence we can conclude that the hashcode() should contain fields that doesn’t change the state of object.
One compatible, but not all that useful, way to define hashCode() is like this:
public int hashcode(){
return 0;
}
This approach will yield bad performance for the HashMap. The conclusion which can be made is that the hashcode() should(not must) return the same value if the objects are equal. If the objects are not equal then it must return different value.
Overriding equals() method
Consider the example:
public class StringHelper {
private String inputString;
public StringHelper(String string) {
inputString=string;
}
@Override
public int hashCode() {
return inputString.length();
}
public static void main(String[] args) {
StringHelper helperObj = new StringHelper(“string”);
StringHelper helperObj1 = new StringHelper(“string”);
if(helperObj.hashCode() == helperObj1.hashCode()){
System.out.println(“HashCode are equal”);
}
if(helperObj.equals(helperObj1)){
System.out.println(“Objects are equal”);
}else{
System.out.println(“Objects are not equal”);
}
}
public String getInputString() {
return inputString;
}
// Output:
HashCode are equal
Objects are not equal
We can see that even though the StringHelper object contains the same value the equals method has returned false but the hashcode method has return true value.
To prevent this inconsistency, we should make sure that we override both methods such that the contract between both methods doesn’t fail.
Steps that need to be taken into consideration while implementing equals method.
1. Use the == operator to check if the argument is a reference to this object. If so, return true. This is just a performance optimization, but one that is worth doing if the comparison is potentially expensive.
2. Use the instanceof operator to check if the argument has the correct type.
If not, return false. Typically, the correct type is the class in which the method occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equals contract to permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entry have this property.
3. Cast the argument to the correct type. Because this cast was preceded by an instanceof test, it is guaranteed to succeed.
4. For each “significant” field in the class, checks if that field of the argument matches the corresponding field of this object. If all these tests succeed, return true; otherwise, return false
5. When you are finished writing your equals method, ask yourself three questions: Is it symmetric? Is it transitive? Is it consistent?
The correct implementation if equals method for the StringHelper class could be:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final StringHelper other = (StringHelper) obj;
if (inputString == null) {
if (other.inputString != null)
return false;
} else if (!inputString.equals(other.inputString))
return false;
return true;
}
Saturday, April 30, 2011
Struts1 Vs Struts2
Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate
the need to access the HttpServetRequest or HttpServletResponse directly.
Programming the abstract classes instead of interfaces is one of design issues of struts1 framework that has been resolved in the struts 2 framework. Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2 , Actions are not container dependent because they are made simple POJOs. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is
not required. Any POJO object with an execute signature can be used as an Struts 2 Action object.
properties class type and the validation context.
4. Threading Model
In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts1 Actions and
requires extra care to develop. However in case of Struts2, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty
or impact garbage collection.)
5. Testability
Testing Struts1 applications are a bit complex. A major hurdle to test Struts1 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent, hence testability is quite easy in struts2.
Struts1 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input. However Struts 2 uses Action properties (as input
properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.
7. Expression Language
Struts1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can also use JSTL, however it supports a more powerful and flexible expression language called “Object Graph Notation Language” (OGNL).
In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2 uses a “ValueStack” technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.
Usually, Struts1 ActionForm properties are all Strings. Struts1 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common
object types and primitives.
Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with
different Actions as needed.
Thursday, April 14, 2011
StringBuffer vs String while concatenation
StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:
String str = new String ("Stanford "); str += "Lost!!"; If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Stanford "); str.append("Lost!!"); Developers usually assume that the first example above is more efficient because they think that the second example, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.
The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:
0 new #73 dup 4 ldc #2 6 invokespecial #12 9 astore_1 10 new #8 13 dup 14 aload_1 15 invokestatic #23 18 invokespecial #13 21 ldc #1 23 invokevirtual #15 26 invokevirtual #22 29 astore_1
The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Stanford "); Then, the bytecode at location 10 through 29 is executed for the concatenation:
str += "Lost!!";
Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.
After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.
In summary, the two lines of code above result in the creation of three objects:
- A
Stringobject at location 0 - A
StringBufferobject at location 10 - A
Stringobject at location 26
Now, let's look at the bytecode generated for the example using StringBuffer:
0 new #83 dup 4 ldc #2 6 invokespecial #13 9 astore_1 10 aload_1 11 ldc #1 13 invokevirtual #15 16 pop
The bytecode at locations 0 to 9 is executed for the first line of code:
StringBuffer str = new StringBuffer("Stanford "); The bytecode at location 10 to 16 is then executed for the concatenation:
str.append("Lost!!"); Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.
In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.
Sunday, April 10, 2011
Accessing Private Methods and Variables in Java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//Accessing Private methods using Reflection******************Fields can be also used
//in the same Way*********************************************
public class Test {
public static void main(String ag[])
{
A obj=new A();
try {
Class c=obj.getClass();
Method method=c.getDeclaredMethod("msg", null);
//System.out.println(method);
try {
method.setAccessible(true);
method.invoke(obj,null);//Calling Private method of a class.
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
////////////second class************Having Private methods
class A
{
private void msg()
{
System.out.println("In class A of private Mehod");
}
}
//Hi Guys we can access the private fields of a java class using reflection in the same way.
Thanks
Pankaj Kumar Singh
Saturday, January 15, 2011
Daemon Thread
Spring Boot Config Server and Config Client.
In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...
-
As we know that TreeSet by default store the unique value it doesn’t check case of the value that is being added. For example if...
-
We can extract text from pdf file using itext 2.1.6 PdfReader readerN = new PdfReader("pdfFilename"); OutputStream...
-
We mostly use hibernate ‘s sessionFactory.openSession() method which keeps track of all events of hibernate along with managing first ...