Differences between new Integer(123), Integer.valueOf(123) and just 123

new Integer(123) will create a new Object instance for each call. According to the javadoc, Integer.valueOf(123) has the difference it caches Objects… so you may (or may not) end up with the same Object if you call it more than once. For instance, the following code: public static void main(String[] args) { Integer a = … Read more

Override valueof() and toString() in Java enum

You can try out this code. Since you cannot override valueOf method you have to define a custom method (getEnum in the sample code below) which returns the value that you need and change your client to use this method instead. public enum RandomEnum { StartHere(“Start Here”), StopHere(“Stop Here”); private String value; RandomEnum(String value) { … Read more

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int. If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore: Integer k = Integer.valueOf(Integer.parseInt(“123”)) … Read more