Variables in Java
In this tutorial, we will learn about variables in Java language. We will cover the basics of declaring and using variables, including naming conventions.
What are Variables
Variables in Java are used to store data values that can be manipulated during program execution. They have a data type that determines the kind of data they can hold, such as integers, strings, or boolean values.
Naming Variables
When naming variables in Java, follow these conventions:
- Start with a letter or an underscore (_).
- Subsequent characters can include letters, digits, or underscores.
- Avoid using reserved keywords as variable names.
- Use meaningful and descriptive names to enhance code readability.
Syntax
The syntax to declare variables in Java is:
data_type variable_name;
Example 1: Variable storing Integer Value
- Declare an integer variable named
num
. - Assign a value of 10 to the variable.
- Print the value of the variable.
Java Program
public class Main {
public static void main(String[] args) {
// Declare and initialize an integer variable
int num = 10;
// Print the value of the variable
System.out.println("The value of num is: " + num);
}
}
Output
The value of num is: 10
Example 2: Variable storing String Value
- Declare a string variable named
name
. - Assign the value "John" to the variable.
- Print the value of the variable.
Java Program
public class Main {
public static void main(String[] args) {
// Declare and initialize a string variable
String name = "John";
// Print the value of the variable
System.out.println("The value of name is: " + name);
}
}
Output
The value of name is: John
Example 3: Variable storing Boolean Value
- Declare a boolean variable named
isTrue
. - Assign the value
true
to the variable. - Print the value of the variable.
Java Program
public class Main {
public static void main(String[] args) {
// Declare and initialize a boolean variable
boolean isTrue = true;
// Print the value of the variable
System.out.println("The value of isTrue is: " + isTrue);
}
}
Output
The value of isTrue is: true