Forum Stats

  • 3,872,043 Users
  • 2,266,370 Discussions
  • 7,911,037 Comments

Discussions

Why print char 0 (zero) plus String does not work?

2924114
2924114 Member Posts: 2
edited Apr 3, 2015 4:26PM in New To Java

Hi guys,

I have a simple doubt. I was studying and create some code to check the result and I found out a strange situation.

Whats wrong with this code? Why it does not print anything?

char = 0; //integer value

System.out.println( c +" String ");

and why this next works very well?

char = 1; //integer value

System.out.println( c +" String ");

I know that char is stored as a positive integer and assign with 0 is different of assign with '0'.

Thanks for any help.

Answers

  • TPD-Opitz
    TPD-Opitz Member Posts: 2,465 Silver Trophy
    edited Apr 3, 2015 4:26PM
    b84d6217-63ff-4b01-ac20-dedb366b9b09 wrote:
    
    Hi guys,
    
    I have a simple doubt. I was studying and create some code to check the result and I found out a strange situation.
    
    

    since you postsd uncompilable code we cannot tell what's really goning on in your example. please always post an SSCCE. http://sscce.org

    Whats wrong with this code? Why it does not print anything?
    
    char = 0; //integer value
    System.out.println( c +" String ");
    

    You ran in the beginners trap of not distinguishing between numbers as they are used by the Computer and human readable characters.

    Java converts numbers to human readable characters when ever it can. But when you declare a variable of type char than you are telling the JVM you want to do this conversion yourself.

    According to the ASCII Standard the decimal value 0 is a non printable character.

    and why this next works very well?
    
    char = 1; //integer value
    System.out.println( c +" String ");
    

    this is also "not working".  depending on the terminal you use you may get something to see but according to the ASCII Standard it should also not print to Screen.

    I know that char is stored as a positive integer and assign with 0 is different of assign with '0'.
    

    But you are not Aware that

    char c;

    is different from

    int c;

    public class CharPlusStringTest {
     @Test
    public void test0() {
      char c= 0; //integer value
      System.out.println( ">"+c +"< String ");
    } @Test
    public void test1() {
      char c= 1; //integer value
      System.out.println( ">"+c +"< String ");
    } @Test
    public void test3() {
      int c= 1; //integer value
      System.out.println( ">"+c +"< String ");
    }
    }

    bye

    TPD

This discussion has been closed.