Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java integer is equal to character?

Tags:

java

I apologize if this question is a bit simplistic, but I'm somewhat puzzled as to why my professor has made the following the statement:

Notice that read() returns an integer value. Using an int as a return type allows read() to use -1 to indicate that it has reached the end of the stream. You will recall from your introduction to Java that an int is equal to a char which makes the use of the -1 convenient.

The professor was referencing the following sample code:

public class CopyBytes {
   public static void main(String[] args) throws IOException {

    FileInputStream in = null;
    FileOutputStream out = null;

    try {
        in = new FileInputStream("Independence.txt");
        out = new FileOutputStream("Independence.txt");
        int c;

        while ((c = in.read()) != -1) {
            out.write(c);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
 }
}

This is an advanced Java course, so obviously I've taken a few introductory courses prior to this one. Maybe I'm just having a "blonde moment" of sorts, but I'm not understanding in what context an integer could be equal to a character when making comparisons. The instance method read() returns an integer value when it comes to EOF. That I understand perfectly.

Can anyone shed light on the statement in bold?

like image 942
Steve Cordrey Avatar asked Feb 15 '23 01:02

Steve Cordrey


1 Answers

In Java, chars is a more specific type of int. I can write.

char c = 65;

This code prints out "A". I need the cast there so Java knows I want the character representation and not the integer one.

public static void main(String... str) {
    System.out.println((char) 65);
}

You can look up the int to character mapping in an ASCII table.

And per your teacher, int allows for more values. Since -1 isn't a character value, it can serve as a flag value.

like image 72
Jeanne Boyarsky Avatar answered Feb 17 '23 16:02

Jeanne Boyarsky