Skip to content

Variables

Chris Ward edited this page Oct 7, 2022 · 1 revision

Variables need a type

In python we could just say name = 'Chris', or age = 23. We didn't have to say what type of variable it is. For Java, this is a requirement. The types that we most use are 'int', 'float', and 'String'.

int age = 23
float temperature = 98.1
String name = "Chris"
  • int is an integer, a number with no decimals.
  • float is a number that can have decimals
  • String (note the capital letter) is a class that holds characters like letters and numbers.

Variables work much the same as in python, where you can use them to hold values and use them later. We have some conventions we use when we create names of variables.

First, most variables use camel-case. That means they start with a lowercase letter, and each word would get a capital to start:

int age = 23;
int myAge = 23;
int internalBodyTemperature = 98.1;

One other kind of variable we want to mention is a constant. This is still a variable, but it doesn't change. Constants are all uppercase letters with underscores.

int NORMAL_BODY_TEMPERATURE = 98.1;
int MAX_SIZE = 100;

We have a few nice things we can do with constants though. We can actually say that this can't change. We use 'final'.

final int NORMAL_BODY_TEMPERATURE;

We also usually put 'static' there too. This tells the compiler that there will only be one of these. We will bring this up again with classes.

static final int NORMAL_BODY_TEMPERATURE = 98.1;

One last thing. Variables can also be hidden from other classes and programs. If you are making a constant, like the normal body temperature, or on the robot, like MAX_SPEED, or NUMBER_OF_WHEELS, you might want others to use this too. To make it visible you use 'public'.

public static final int MAX_SPEED = 10;

You might remember that we saw 'public' and 'static' when we were looking at the first hello world program. We will talk more about these when we get to classes.

For now, lets see how Java does loop d loops

Clone this wiki locally