In this lesson, we will delve into the concept of variables in Java, which are containers for storing data values. Understanding variables is fundamental to programming, as they allow us to store and manipulate data.
Types of Variables
In Java, there are several types of variables, each designed to hold different kinds of data:
- String: Stores text values, 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
orfalse
.
Declaring (Creating) Variables
To create a variable, you need to specify its type and assign it a value using the following syntax:
type variableName = value;
Where type
is one of Java’s variable types (e.g., int
, String
), and variableName
is the name of the variable (e.g., x
, name
). The equal sign (=
) is used to assign a value to the variable.
Example: Creating a String Variable
Create a variable called studentName
of type String
and assign it the value “Alice”. Then, use println()
to print the studentName
variable:
String studentName = "Alice"; System.out.println(studentName);
Example: Creating an int Variable
Create a variable called age
of type int
and assign it the value 25:
int age = 25; System.out.println(age);
Declaring Variables without Assigning Values
You can declare a variable without assigning a value initially and then assign the value later:
int score; score = 85; System.out.println(score);
Modifying Variable Values
If you assign a new value to an existing variable, it will overwrite the previous value:
int score = 85; score = 95; // score is now 95 System.out.println(score);
Final Variables
If you do not want a variable’s value to be changed after its initial assignment, you can use the final
keyword. This declares the variable as “final” or “constant”, making it unchangeable and read-only:
final int maxScore = 100; maxScore = 110; // This will generate an error: cannot assign a value to a final variable
Other Types of Variables
Here are examples of how to declare variables of different types:
int myNumber = 10; float myDecimal = 5.75f; char myChar = 'Z'; boolean isJavaFun = true; String myMessage = "Hello, Java!";