Java — Variables & Data Types
A variable is a named storage location used to keep data while a program runs. Unlike Python, Java is statically typed, so every variable must have a data type before it can store a value.
In Java, we write the data type first, then the variable name, and finally assign a value using =:
public class Main {
public static void main(String[] args) {
String username = "Balaji";
int age = 25;
double height = 5.9;
boolean isDeveloper = true;
System.out.println(username);
System.out.println(age);
System.out.println(height);
System.out.println(isDeveloper);
}
}
Java has primitive data types for storing simple values. The most common types are:
| Type | Description | Example |
|---|---|---|
int | Whole numbers | 42 |
long | Very large whole numbers | 9000000000L |
double | Decimal numbers | 3.1415 |
char | One character inside single quotes | 'A' |
boolean | true or false | true |
String | Text inside double quotes | "Java" |
You can check a value's type indirectly through its declared type. Java checks the type during compilation.
public class Main {
public static void main(String[] args) {
int score = 99;
char grade = 'A';
boolean isOnline = false;
String language = "Java";
System.out.println(score);
System.out.println(grade);
System.out.println(isOnline);
System.out.println(language);
}
}
Type casting means converting a value from one data type to another. Smaller compatible types can usually be assigned to larger types automatically. Converting a larger type to a smaller type requires explicit casting.
public class Main {
public static void main(String[] args) {
int number = 10;
double largerNumber = number;
System.out.println(largerNumber);
double price = 19.99;
int wholePrice = (int) price;
System.out.println(wholePrice); // 19
}
}
- Names can contain letters, numbers, and underscores.
- A variable name cannot start with a number.
- Java variable names are usually written in
camelCase, such astotalPrice. - Java is case-sensitive:
ageandAgeare different names. - Do not use reserved keywords such as
class,int, orpublic.
Create a Java program that declares a product name, price, discount percentage, available quantity, and stock status. Print every value and calculate the final price after the discount.