Monday, February 25, 2013

Java :: String ValueOf Vs String Concatenation

String ValueOf Vs String Concatenation

From stack over flow I found bellow answer, as conclusion:
"Never use (+ "") to convert values to string, instead use String.valueOf."




public void foo(){
int intVar = 5;
String strVar = intVar+"";    
}
This approach uses StringBuilder to create resultant String
public void foo();
  Code:
   0:   iconst_5
   1:   istore_1
   2:   new     #2; //class java/lang/StringBuilder
   5:   dup
   6:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   9:   iload_1
   10:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(I)Ljava/lan
g/StringBuilder;
   13:  ldc     #5; //String
   15:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
   18:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/la
ng/String;
   21:  astore_2
   22:  return

public void bar(){
int intVar = 5;
String strVar = String.valueOf(intVar);
}
This approach invokes simply a static method of String to get the String version of int
public void bar();
  Code:
   0:   iconst_5
   1:   istore_1
   2:   iload_1
   3:   invokestatic    #8; //Method java/lang/String.valueOf:(I)Ljava/lang/Stri
ng;
   6:   astore_2
   7:   return

Saturday, February 23, 2013

Java :: How to override equals

How to override equals

All what you need to do is add the following piece if code in your object:


@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (obj.getClass() != getClass())
return false;
YourObject rhs = (YourObject ) obj;
if (!rhs.getId().equals(getId())) // For Example
return false;
return true;
}


Have a nice day.

Wednesday, February 13, 2013

Java :: Variable Initialization

Variables initialization Advantages (In / out Constructor)

You can initialize a variable using the following:

  • Inside a constructor:

public Class Test() {
public int var;
  public Test()
{
    var = 10;
  }
}

  • Outside a constructor
public Class Test() {
         public int var = 10;
}


Advantages
Inside Constructor
Outside Constructor
One initialization even if you have multiple constructors

X
Can add exception handling to the initialization
X

More Readable

X
Faster Class Load
-
-


No major difference between both, developer use what you want!!
There is another types as static block will talk about later.

Have a nice day