File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Addition or Concatenation?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Addition or Concatenation??" Watch "Addition or Concatenation??" New topic

Addition or Concatenation??

Piyush Sam

Joined: Jun 02, 2005
Posts: 24
What will be output of the following program?

System.out.println('A' + 'B');

1 A AB
2 65 131
3 A 131

Anser is A 131

The problem is Java's design blunder of using + to mean both addition and concatenation. Addition also promotes to int, which println displays differently from char.

Plz somebody explain in more detail.


Piyush Jain<br /> <br />Being happy doesn't mean everything's perfect. It means you've decided to see beyond the imperfections.
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Hi Sam
When you do a addition operation on a char it gets automatically casted to integers , so it will be a normal addition.

Ex : System.out.println ( "One" + "Two" + 1 + 2 ) = OneTwo12
S.O.P ( 1 + 2 ) = 3 // and not 12.

The problem is Java's design blunder of using +
You should not blame the design of java , when the concepts are not clear.

Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

Plz somebody explain in more detail.

Please make the extra effort to write out words such as "please". The extra keystrokes won't cost much in the way of time, and the enhanced clarity will be appreciated by those communicating on a forum with international readership.
I agree. Here's the link:
subject: Addition or Concatenation??
It's not a secret anymore!