AlgoCademy
Lesson
Code

Declare Variables in {lang}


In computer science, data is anything that is meaningful to the computer. Java provides a large number of data types, the most frequently used being:

  • int - represents integer numbers like 3 and -12
  • double - represents floating point numbers like 3.14
  • char - represents a single character like 'a', 'Z' or '?'
  • String - represents a sequence of characters like "John Doe"
  • boolean - represents one of two values: true or false

For example, computers distinguish between numbers, such as the number 12, and strings, such as "12", "dog", or "123 cats", which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.

Variables allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of these data types may be stored in a variable.

Variables are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer variables differ from mathematical variables in that they can store different values at different times.


Variable declaration:

To declare a variable, we must tell Java its type followed by its name, like so:

int year;

creates a variable called year. Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number.


Variable initialization:

It is common to initialize a variable to an initial value in the same line as it is declared.

String name = "AlgoCademy";

creates a new variable called name and assigns it an initial value of "AlgoCademy".


Variable assignment:

You can always change the value stored in a variable with the assignment operator(=):

// Initializing with 5:
int myVar = 5;

// Assigning the value 10:
myVar = 10;

First, this code creates a variable named myVar, equal to 5. Then, the code assigns 10 to myVar. Now, if myVar appears again in the code, the program will treat it as if it is 10.


Assignment
Follow the Coding Tutorial and let's create some variables.

Hint
Look at the year and name examples above if you get stuck.