Java Variables
What is variables in Java?
Variables are containers for storing data values.
There are different types of variables in java
for example:
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
boolean - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and you can assign it a value at that time or after creation also.
Syntax
type variableName = value;
Syntax explain:
type: java's type like int, String etc.
variableName: name of variable like name, num
= : Equal sign is used to assign values
Example
String name = "John";
Variable and value
Create variable and assign value
int myNum = 15;
Create variable then assign value
int myNum;
myNum = 15;
Create variable and assign and re-assign value
int myNum = 15;
myNum = 20; // myNum is now 20
Note: Final Variables
Provident from overwrite values use final keyword and then cant re-assign any variable
Example:
final int myNum = 15;
myNum = 20; // error
Create multiple variable and assign value with sight data type
int a=12, b = 23;
Print Java Variables
It is used to combine both text and a variable, use the + character To combine both text and a variable,
Example:
String name = "John";
System.out.println("Hello " + name);
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y
Declare Many Variables
To declare more than one variable of the same type, you can use a comma-separated list:
Example:
Instead of writing:
int x = 5;
int y = 6;
int z = 50;
System.out.println(x + y + z);
You can simply write:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z); //61
One Value for Multiple Variables
You can also assign the same value to multiple variables in one line:
Example:
int x, y, z;
x = y = z = 50;
System.out.println(x + y + z);
Java Identifiers
All Java variables must be identified with unique names and These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Note: Better for names in order to create understandable and maintainable code:
Example:
int minutesPerHour = 60;
Rules for naming variables
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 _ (it we will be better to not use)
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like Java keywords, such as int or Boolean) cannot be used as names