Variables in Java are containers for storing data values.
In Java, there are different types of variables, for example:
String
– stores text, such as “Hello World”. String values are surrounded by double quotesint
– stores integers (whole numbers), without decimals, such as 15 or -15float
– stores floating point numbers, with decimals, such as 1.99 or -1.99char
– stores single characters, such as ‘a’ or ‘Z’. Char values are surrounded by single quotesboolean
– stores values with two states: true or false
package com.java.basic;
public class VariablesExamples {
public static void main(String[] args) {
//create a variable that should store text
String name = "John";
System.out.println(name);
//create a variable that should store a number
int myNum = 15;
System.out.println(myNum);
//declare a variable without assigning the value, and assign the value later
int myNum2;
myNum2 = 15;
System.out.println(myNum2);
//change the value of myNum from 15 to 20
int myNum3 = 15;
myNum3 = 20; // myNum is now 20
System.out.println(myNum3);
/*
* If you don't want others (or yourself) to overwrite existing values,
* use the final keyword (this will declare the variable as "final" or
* "constant", which means unchangeable and read-only)
*/
final int myNum4 = 15;
//myNum4 = 20; // will generate an error: cannot assign a value to a final variable
//other types
int myNum5 = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
//Declare multiple variables
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
//one value to multiple variables
int a, b, c;
a = b = c = 50;
System.out.println(a + b + c);
}
}
All Java variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for naming variables are:
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter
- Names should start with a lowercase letter and it cannot contain whitespace
- Names can also begin with $ and _ (but we will not use it in this tutorial)
- Names are case sensitive (“myVar” and “myvar” are different variables)
- Reserved words (like Java keywords, such as
int
orboolean
) cannot be used as names
// Good -camelCase
int minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;