Computer Science Researcher • Educator • Programming Instructor
A variable in Java is a container that stores a value. You can store numbers, text, decimals, and many other types of data. Variables allow your program to remember information.
To create a variable, you must write:
dataType variableName = value;
public class Main {
public static void main(String[] args) {
int age = 20;
System.out.println("My age is " + age);
}
}
public class Main {
public static void main(String[] args) {
int year = 2025;
double temperature = 36.5;
String name = "Khalid";
boolean isStudent = false;
System.out.println(year);
System.out.println(temperature);
System.out.println(name);
System.out.println(isStudent);
}
}
public class Main {
public static void main(String[] args) {
int score = 50;
System.out.println("Old score: " + score);
score = 80; // value updated
System.out.println("New score: " + score);
}
}
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 7;
int total = x + y;
System.out.println("Total = " + total);
}
}
public class Main {
public static void main(String[] args) {
int age = 30; // correct
int Age = 40; // correct but different
int _value = 100; // correct
// int 2number = 50; WRONG
// int student name = 20; WRONG
System.out.println(age);
System.out.println(Age);
System.out.println(_value);
}
}
public class Main {
public static void main(String[] args) {
String firstName = "Khalid";
String lastName = "Khattak";
String fullName = firstName + " " + lastName;
System.out.println("Full name: " + fullName);
}
}
If you want a variable that cannot change later, use final.
public class Main {
public static void main(String[] args) {
final double PI = 3.14159;
System.out.println("Value of PI: " + PI);
// PI = 5; // ERROR: cannot change final variable
}
}
public class Main {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
public class Main {
public static void main(String[] args) {
int marks = 90;
System.out.println("You scored: " + marks + " marks.");
}
}
final