Java course Lesson 1 of 6

Java from zero: a variable has a type

A Java variable has a type. name is a String, cents is an int, and ready is a boolean. The program prints latte $4.50 ready.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

A variable in Java holds one kind of value, and you write that kind in front of the name. int is a whole number. String is text. boolean is true or false. The compiler keeps the kinds apart. You can add two ints. You cannot add a String to a boolean.

The type is part of the variable#

Java stores the type on the variable, and the compiler refuses a later assignment that does not match. int and boolean are primitives: the bits are the value, and there is no object to call a method on. String is an object, which is why its name is capitalized and why it has methods. printf builds the cup label from the three values. cents / 100 is the dollars and cents % 100 is the leftover cents. cents is still an int afterward. cents = "latte" is rejected before anyone runs the program.

A variable holds one kind of value
  1. nameStringlatte
  2. centsint450
  3. readybooleantrue
public class Main {
    public static void main(String[] args) {
        String name = "latte";
        int cents = 450;
        boolean ready = true;
        String status = ready ? "ready" : "sold out";
        System.out.printf("%s $%d.%02d %s%n", name, cents / 100, cents % 100, status);
    }
}
latte $4.50 ready

The type comes first#

int cents = 450 makes cents and stores 450 cents, which is $4.50. The type is int, so a later line cannot store "latte" in cents. String is a class, which is why the S is uppercase. int and boolean are primitive types. They are not objects. They have no methods. String is an object, and it has methods such as length() and substring.

System.out.printf prints one line. %d prints an int and %02d prints the leftover cents as two digits. That conversion is only for the label. cents is still an int.

The type is checked before the program runs#

cents = "latte" does not compile. Java tells you the types do not match, and it tells you at compile time, before anyone runs the program. That is the point of writing the type down. The next lesson puts a String and an int together in a class and calls a method on the object.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.