Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

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

2924114Apr 3 2015 — edited Apr 3 2015

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.

Comments

TPD-Opitz

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

1 - 1
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 1 2015
Added on Apr 3 2015
1 comment
1,117 views