Module 2: Java Fundamentals
Variables and Data Types
Store values using Java's primitive and reference types.
A variable is a named location used by a program to refer to a value. Java is statically typed, so a variable's type is declared and checked by the compiler.
int age = 23;
double price = 149.50;
char grade = 'A';
boolean isActive = true;
String name = "Swagat";
int, double, char, and boolean are primitive types. String is a reference type provided by the Java standard library.
Common primitive types#
| Type | Example | Typical use |
|---|---|---|
byte | byte count = 10; | Small integer values |
int | int total = 120; | Whole numbers |
long | long population = 8000000L; | Larger whole numbers |
float | float ratio = 2.5f; | Single-precision decimal values |
double | double average = 7.25; | Double-precision decimal values |
char | char initial = 'S'; | A single UTF-16 code unit |
boolean | boolean ready = false; | true or false |
Use double quotes for strings and single quotes for character literals. For a long literal that does not fit an int, use the L suffix. Float literals generally need an f suffix.
Declare and update a variable#
int score = 10;
score = 15;
score += 5;
System.out.println(score); // 20
The type remains int, while the value changes. Local variables must be assigned before they are read. Fields have default values, but you should not rely on those defaults for local variables.
Type conversion#
Some conversions happen automatically, such as from int to double. Converting a double to an int requires an explicit cast and discards the fractional part:
double amount = 9.8;
int wholeAmount = (int) amount; // 9
Practice#
Declare variables for a product name, quantity, price, and whether it is in stock. Choose a suitable type for each value and print them.