Results 1 to 4 of 4
  1. #1
    Allspark is offline Member
    Join Date
    Sep 2010
    Posts
    21
    Rep Power
    0

    Default Why do I get this output?

    Java Code:
    public class testing
    {
    public static void main(String[] args)
    	{
    		final int a = 2, b = 3;
    	
    		System.out.println(a + "2");
    		
    		[COLOR="Red"]System.out.println(a + '2');[/COLOR]
    		
    		System.out.println("2" + a + b);
    		
    		System.out.println("2" + (a + b));
    		
    	
    	System.exit(0);
    	}
    }
    output is
    22
    52
    223
    25

    How does the red highlighted code work? Thanks!
    - Winners compare their achievements with their goals, while losers compare their achievements with those of other people. -

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,401
    Rep Power
    25

    Default

    System.out.println(a + '2');
    chars can be converted by the compiler to their ASCII value. If you lookup the ASCII codes table you will see that the int value of '2' is 50.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,236
    Rep Power
    19

    Default

    Quote Originally Posted by Norm View Post
    chars can be converted by the compiler to their ASCII value.
    There's no conversion involved. The Java primitive char is an integral type.
    Types, Values, and Variables

    db

  4. #4
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Darryl.Burke View Post
    There's no conversion involved. The Java primitive char is an integral type.
    Types, Values, and Variables
    Well, there is some conversion happening but it happens during compile time; b.t.w. literal chars are converted to their Unicode code point values, not their ASCII code values (which is totally moot because ASCII is a subcode of Unicode).

    kind regards,

    Jos

Similar Threads

  1. output
    By yrollgayanth in forum New To Java
    Replies: 5
    Last Post: 12-30-2009, 05:05 PM
  2. Where is output.txt?
    By Jessaurum in forum New To Java
    Replies: 3
    Last Post: 11-18-2009, 06:14 AM
  3. Java, output string, getting correct output? HELP!
    By computerboyo in forum New To Java
    Replies: 2
    Last Post: 02-25-2009, 11:44 PM
  4. how to c the output
    By pro85 in forum Java Applets
    Replies: 1
    Last Post: 02-11-2009, 09:09 AM
  5. Why the output is always zero
    By mehrotra.chitij in forum New To Java
    Replies: 12
    Last Post: 04-25-2008, 04:05 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •