In Java, variables are containers for storing data values. Every variable in Java has a data type, which determines the kind of data it can hold. Java is a statically-typed language, meaning you must declare the type of a variable before using it.
Java data types are categorized into two main types:
Java has eight primitive data types, which are not objects and represent simple values.
Type | Description | Example |
---|---|---|
int |
Integer values | int age = 25; |
double |
Decimal numbers (floating-point) | double pi = 3.14; |
boolean |
True or false values | boolean isOpen = true; |
char |
A single Unicode character | char grade = 'A'; |
byte |
Small integers (-128 to 127) | byte b = 100; |
short |
Larger than byte |
short s = 32000; |
long |
Very large integers | long population = 8000000000L; |
float |
Less precise decimals than double |
float temp = 36.6f; |
Note:
float
andlong
literals require a suffix (f
orL
).
Reference types store references (addresses) to objects rather than the actual data. Common examples include:
Strings: Sequences of characters.
String name = "Alice";
Arrays: Collections of elements of the same type.
int[] scores = {90, 85, 78};
Other reference types include objects created from classes.
You declare a variable by specifying the type followed by the variable name. You can also assign an initial value at the time of declaration.
int age = 30;
double price = 9.99;
boolean isAvailable = true;
char initial = 'J';
String greeting = "Hello, world!";
You can also declare multiple variables of the same type in one line:
int a = 5, b = 10, c = 15;
public class DeclareMultiple {
public static void main(String[] args) {
int x = 10, y = 20, sum;
sum = x + y;
System.out.println("Sum: " + sum);
}
}
public class ArithmeticExample {
public static void main(String[] args) {
double price = 19.99;
int quantity = 3;
double total = price * quantity;
System.out.println("Total cost: $" + total);
}
}
public class BooleanExample {
public static void main(String[] args) {
int age = 18;
boolean isAdult = age >= 18;
if (isAdult) {
System.out.println("You are an adult.");
} else {
System.out.println("You are not an adult.");
}
}
}
Java is type-safe, meaning that each variable must be declared with a specific type, and the compiler checks for type mismatches. This helps catch errors early during compilation rather than at runtime.
For example:
int x = 10;
String s = "Hello";
// x = s; // ❌ Compile-time error: incompatible types
Java supports two types of type conversion:
Implicit (Widening) Conversion – safe conversion from a smaller type to a larger type:
int a = 10;
double b = a; // int to double (safe)
Explicit (Narrowing) Conversion – converting from a larger type to a smaller type, which may lead to data loss:
double d = 9.78;
int i = (int) d; // Explicit cast: double to int
System.out.println(i); // Outputs 9
In Java, operators are special symbols that perform operations on variables and values. Understanding how to use them is key to writing functional, logical programs.
Java provides several types of operators:
These are used to perform basic mathematical operations.
Operator | Description | Example (a = 10, b = 3 ) |
---|---|---|
+ |
Addition | a + b → 13 |
- |
Subtraction | a - b → 7 |
* |
Multiplication | a * b → 30 |
/ |
Division | a / b → 3 |
% |
Modulus (remainder) | a % b → 1 |
Example:
int a = 10, b = 3;
System.out.println("Sum: " + (a + b));
System.out.println("Remainder: " + (a % b));
These return true
or false
depending on the comparison result.
Operator | Description | Example |
---|---|---|
== |
Equal to | a == b → false |
!= |
Not equal to | a != b → true |
> |
Greater than | a > b → true |
< |
Less than | a < b → false |
>= |
Greater or equal | a >= b → true |
<= |
Less or equal | a <= b → false |
Example:
int age = 18;
System.out.println(age >= 18); // true
Used to combine multiple boolean expressions.
Operator | Description | Example |
---|---|---|
&& |
Logical AND | true && false → false |
|| | Logical OR | true || false → true |
! |
Logical NOT | !true → false |
Example:
int age = 20;
boolean hasID = true;
if (age >= 18 && hasID) {
System.out.println("Entry allowed.");
} else {
System.out.println("Entry denied.");
}
Used to assign values to variables.
Operator | Description | Example |
---|---|---|
= |
Assign | x = 5 |
+= |
Add and assign | x += 2 → x = x + 2 |
-= |
Subtract and assign | x -= 3 |
*= |
Multiply and assign | x *= 4 |
/= |
Divide and assign | x /= 2 |
%= |
Modulus and assign | x %= 3 |
Example:
int score = 50;
score += 10; // score is now 60
System.out.println(score);
Java evaluates expressions using precedence rules, similar to math:
()
have the highest precedence.*
, /
, %
before +
, -
.&&
before ||
.=
, +=
, etc.) has the lowest precedence.Tip: Use parentheses to clarify complex expressions and ensure the correct order of evaluation.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = input.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char op = input.next().charAt(0);
System.out.print("Enter second number: ");
double num2 = input.nextDouble();
double result;
if (op == '+') result = num1 + num2;
else if (op == '-') result = num1 - num2;
else if (op == '*') result = num1 * num2;
else if (op == '/') result = num1 / num2;
else {
System.out.println("Invalid operator!");
return;
}
System.out.println("Result: " + result);
}
}
public class ConditionChecker {
public static void main(String[] args) {
int score = 85;
boolean passed = score >= 60;
boolean hasPerfectAttendance = true;
if (passed && hasPerfectAttendance) {
System.out.println("Eligible for reward!");
} else {
System.out.println("Not eligible.");
}
}
}
public class ExpressionDemo {
public static void main(String[] args) {
int a = 5, b = 10;
int result = (a + b) * 2; // Parentheses used for precedence
System.out.println("Result: " + result);
}
}
In Java, conditional statements let your program make decisions and execute specific code depending on whether a condition is true or false. The two main conditional control structures are:
if
/else if
/else
(used for flexible, complex conditions)switch
(used for multiple discrete values)if
StatementThe simplest form checks a condition and runs code if it’s true.
if (condition) {
// Code runs if condition is true
}
public class NumberCheck {
public static void main(String[] args) {
int num = 7;
if (num > 0) {
System.out.println("The number is positive.");
}
}
}
if
/ else
StatementThe else
block runs if the condition is false.
if (condition) {
// Runs if true
} else {
// Runs if false
}
public class SignChecker {
public static void main(String[] args) {
int num = -3;
if (num >= 0) {
System.out.println("The number is non-negative.");
} else {
System.out.println("The number is negative.");
}
}
}
if
, else if
, and else
You can chain multiple conditions using else if
.
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none are true
}
public class GradeEvaluator {
public static void main(String[] args) {
int score = 76;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}
This is useful when there are ranges or non-exact values to compare.
if
StatementsYou can place one if
inside another for more specific checks.
int age = 20;
boolean hasID = true;
if (age >= 18) {
if (hasID) {
System.out.println("Access granted.");
} else {
System.out.println("ID required.");
}
} else {
System.out.println("Access denied. Must be 18+.");
}
Nested if
is good when one condition depends on another.
switch
Statementswitch
is cleaner than multiple if
statements when you're checking a variable against specific constant values.
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Each case
is matched against the value. break
exits the switch after a match. Without it, execution "falls through" to the next case.
import java.util.Scanner;
public class MenuSystem {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Menu:");
System.out.println("1. Say Hello");
System.out.println("2. Add Numbers");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Hello!");
break;
case 2:
System.out.println("5 + 3 = " + (5 + 3));
break;
case 3:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid choice.");
}
}
}
if
and switch
Use if when: |
Use switch when: |
---|---|
Conditions involve ranges (score >= 90 ) |
You're checking one variable for matches |
Logic depends on multiple variables | Comparing exact values (like menu options) |
You need more complex boolean expressions | Values are constants (int , char , etc.) |
else if
public class SignClassifier {
public static void main(String[] args) {
int num = 0;
if (num > 0) {
System.out.println("Positive");
} else if (num < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
}
}
if
evaluates a condition. If it's true, the block runs.else if
allows additional checks if the previous ones failed.else
catches all remaining cases.switch
evaluates a single expression and executes the matching case.In Java, loops allow you to repeat a block of code multiple times based on a condition. This is especially useful when processing collections, validating input, or performing repetitive tasks like displaying menus or calculating values.
Java has three main types of loops:
for
loopwhile
loopdo-while
loopLet’s explore each with practical examples and learn when to use which.
for
LoopThe for
loop is used when you know in advance how many times you want to repeat a block.
Syntax:
for (initialization; condition; update) {
// code to repeat
}
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}
public class MultiplicationTable {
public static void main(String[] args) {
int number = 7;
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}
Use case: Best for count-controlled loops, like generating tables, repeating steps a fixed number of times, or iterating through arrays.
while
LoopThe while
loop runs as long as a condition is true. It’s ideal when you don’t know how many times you'll loop, but the condition controls when to stop.
Syntax:
while (condition) {
// code to repeat
}
import java.util.Scanner;
public class InputValidator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age;
System.out.print("Enter your age (0–120): ");
age = input.nextInt();
while (age < 0 || age > 120) {
System.out.print("Invalid. Please enter a valid age: ");
age = input.nextInt();
}
System.out.println("Age entered: " + age);
}
}
Use case: Ideal for condition-controlled loops, like checking for valid input or reading data until a stop condition is met.
do-while
LoopThe do-while
loop is similar to while
, but the block always runs at least once, regardless of the condition.
Syntax:
do {
// code to repeat
} while (condition);
import java.util.Scanner;
public class MenuLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Greet");
System.out.println("2. Show Time");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Hello!");
break;
case 2:
System.out.println("It's Java time!");
break;
case 3:
System.out.println("Goodbye!");
break;
default:
System.out.println("Invalid option.");
}
} while (choice != 3);
}
}
Use case: Best when you need the loop to run at least once, such as showing menus or retry prompts.
break
Exits the loop immediately:for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
}
// Output: 1 2 3 4
continue
Skips the current iteration:for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
// Output: 1 2 4 5
public class Test {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
}
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
}
}
public class PatternPrinter {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println(); // Move to the next line
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Loop Type | Best Used When… |
---|---|
for |
You know how many times to repeat (e.g., count 1–100) |
while |
Repeat until a condition becomes false (e.g., input check) |
do-while |
Run at least once before checking condition (e.g., menu) |