Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Ever Java Program Incorrect Output

Tags:

java

Sorry for really stupid question, I'm learning a new language and taking this code:

public class Exercise01 {
    int i;
    char c;

    public static void main(String[] args) {

        Exercise01 E = new Exercise01();
        System.out.println("i = " + E.i);
        System.out.println("c = [" + E.c + "]");
    }
}
/* Output:
i = 0
c = [
*/

Why the output does not produce "]" character? Has it something to do with Unicode?

PostEdited: the variable E.c was not initialized for experimentation purpose.

like image 599
Sophie Sperner Avatar asked Sep 05 '11 17:09

Sophie Sperner


People also ask

What are the 3 errors in Java?

The most common causes of runtime errors in Java are: Dividing a number by zero. Accessing an element in an array that is out of range. Attempting to store an incompatible type value to a collection.

What are the 2 common errors of Java programming?

The types of errors encountered when a software developer develops a Java application can be split into two broad categories: compile time errors and runtime errors. As the name implies, compile time errors occur when the code is built, but the program fails to compile.

What is the most common error in Java?

“cannot find symbol” This is a very common issue because all identifiers in Java need to be declared before they are used.

What are the errors in Java programming?

In Java, an error is a subclass of Throwable that tells that something serious problem is existing and a reasonable Java application should not try to catch that error. Generally, it has been noticed that most of the occurring errors are abnormal conditions and cannot be resolved by normal conditions.


2 Answers

It may be that the place your program is outputting to, a console or a window, is getting confused by the U+0000 character which is the value of E.c.

It works fine for me.

Initialize E.c and try again.

like image 76
Ray Toal Avatar answered Sep 28 '22 09:09

Ray Toal


You are trying to print the null character as your char c hasn't need initialised. i.e. \0 Interestingly you can't copy and paste this character easily as most C code sees this as an end of string marker.

I see the ] when I run the code.

Try changing your code with

char c = '?';

gives me an output of

i = 0
c = [?]

One way to reproduce this problem is to run on unix

java Main | more

which outputs

i = 0
c = [
like image 42
Peter Lawrey Avatar answered Sep 28 '22 10:09

Peter Lawrey