Home > JAVA > Java learning note – Fun with code 01

Java learning note – Fun with code 01

Today my friend asked me about char data type with plus (+) operator. This is his code:

public class App
{
public static void main( String[] args )
{
char a, b, c;
a = 'A';
b = '+';
c = '4';
System.out.println(a + b + c + d);
}
}

 

 

Output:
OutputChar02

And suddenly I remember one thing, “If either operand is a String, the + operator becomes a String concatenation operator. If both operand are numbers, the + operator is the addition operator”.

To prove that:

public class App
{
public static void main( String[] args )
{
char a, b, c;
a = 'A';
b = '+';
c = '4';
int d = 10;
System.out.println(a + b + c + d);
}
}

 

 

Output:
OutputChar01

And if we want to concate those char value:

public class App
{
public static void main( String[] args )
{
char a, b, c;
a = 'A';
b = '+';
c = '4';
System.out.println("" +a + b + c);
}
}

Output:
OutputChar03

Why I not using StringBuilder class? Because the compiler already doing that. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is.

"" +a + b + c
That compiles to the following:
new StringBuilder().append("").append(a).append(b).append(c).toString();

 

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: