Variables in Java are containers for storing data values. Each variable has a specific type that determines the kind of data it can store. In this tutorial, we’ll explore the basics of variables in Java.
In Java, you need to declare a variable with its type and optionally initialize it:
int number = 10; // Declares an integer variable and assigns a value
String name = "Alice"; // Declares a string variable
boolean isJavaFun = true; // Declares a boolean variable
Java supports several data types, including:
int
, double
, char
, boolean
, etc.String
).Here are some important rules for naming variables:
_
, or $
.myVar
and myvar
are different).Here’s a simple example using different types of variables:
public class VariablesExample {
public static void main(String[] args) {
int age = 25;
double salary = 45000.50;
String name = "Alice";
boolean isEmployed = true;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Employed: " + isEmployed);
}
}
Name: Alice
Age: 25
Salary: $45000.5
Employed: true
Experiment with different variable types and operations. Variables are a fundamental concept in Java and programming in general. Happy coding! Now you can learn about if else statements!