Variables are elements used to store data so we can manipulate and use them in our program.
Unlike JavaScript and Python where the program can just figure it out, we have to be more specific in Java. Types include: String, int, boolean, double, char
String
int
boolean
double
char
This variable is used for text like words or sentences.
How do you declare a String variable?
String greeting = "Hello, world!";
NOTE: You must use double quotes for strings. And end every line with a semicolon (;).
This variable type is used to store whole numbers (no decimals).
How do you declare an int variable?
int age = 16;
This type of variable is used to store true or false values.
true
false
How do you declare a boolean variable?
boolean isStudent = true;
This type of variable is used to store decimal numbers Examples: 3.14, 9.81, 2.718
How do you declare a double variable?
double pi = 3.14159;
This type is used to store a single character. Characters must be enclosed in single quotes (' ').
How do you declare a char variable?
char grade = 'A';
String name = "Alice";
int score = 100;
boolean passed = false;
double temp = 36.6;
char initial = 'B';
conditionals are statements that control the flow of a program's execution based on whether a condition is true or false.
Basic if structure:
if (condition) { // code to run if condition is true }
Example:
int age = 18; if (age >= 18) { System.out.println("You can vote!"); }
Structure:
if (condition) { // runs if true } else { // runs if false }
int score = 45; if (score >= 50) { System.out.println("You passed!"); } else { System.out.println("You failed."); }
if (condition1) { // runs if condition1 is true } else if (condition2) { // runs if condition2 is true } else { // runs if neither is true }
int grade = 85; if (grade >= 90) { System.out.println("A"); } else if (grade >= 80) { System.out.println("B"); } else { System.out.println("C or lower"); }
==
a == b
!=
a != b
>
a > b
<
a < b
>=
a >= b
<=
a <= b
Loops are used to repeat a block of code multiple times until a condition is met.
Types:
for
while
for (initialization; condition; update) { // code to repeat }
for (int i = 0; i < 5; i++) { System.out.println("i is: " + i); // Output is: 0 1 2 3 4 }
while (condition) { // code to repeat }
int i = 0; while (i < 5) { System.out.println("i is: " + i); i++; }
Print even numbers from 2 to 10 using a loop:
for (int i = 2; i <= 10; i += 2) { System.out.println(i); }