Java Programming Fundamentals
Java Basics
The Anatomy of a Java Program
Every Java program has a specific structure it must follow to run correctly. Let's start with the classic first program anyone writes: one that simply prints "Hello, World!" to the screen.
public class HelloWorld {
public static void main(String[] args) {
// This line prints text to the screen
System.out.println("Hello, World!");
}
}
Let's break this down. Every Java application needs a class. Think of it as a container for your program. Here, our container is named HelloWorld.
Inside the class, we have a main method. This is the entry point of your program. When you run the code, the Java Virtual Machine (JVM) looks for this exact main method and starts executing the code inside it. The code inside the curly braces {} is what gets run.
Notice a few key syntax rules:
- Curly Braces
{}: These define blocks of code. Themainmethod's code is inside its braces, and themainmethod is inside theHelloWorldclass's braces. - Semicolons
;: Every statement in Java must end with a semicolon. It's like the period at the end of a sentence. - Case Sensitivity: Java is case-sensitive.
HelloWorldis different fromhelloworld.
Storing Information
Programs need to store and manage information. We do this using variables. A variable is a container that holds a value. Before you can use a variable, you must declare it, which means giving it a name and specifying what type of data it will hold.
variable
noun
A named storage location in memory that holds a value. The value can be changed during program execution.
Java has several built-in data types, often called primitive types. They are the fundamental building blocks for data.
| Data Type | Description | Example |
|---|---|---|
int | Stores whole numbers | 10, -5, 0 |
double | Stores decimal numbers | 3.14, -0.001 |
boolean | Stores true or false values | true, false |
char | Stores a single character | 'A', '!' |
String | Stores a sequence of characters | "Hello Java" |
Note that String is technically not a primitive type, but it's so common that it's best to learn it from the start. String values are always enclosed in double quotes ("), while char values are in single quotes (').
Here's how you declare a variable and assign it a value:
// Declare an integer variable named 'score'
int score;
// Assign a value to it
score = 100;
// You can also declare and assign in one line
double price = 19.99;
boolean isLoggedIn = true;
String userName = "Alex";
// Print the value of a variable
System.out.println(userName);
Making Things Happen
Variables are not very useful on their own. We need operators to perform actions on them. Java has several kinds of operators for different tasks.
Arithmetic Operators: Used for mathematical calculations.
+(addition),-(subtraction),*(multiplication),/(division), and%(modulo, which gives the remainder of a division).
int a = 10;
int b = 3;
int sum = a + b; // sum is 13
int difference = a - b; // difference is 7
int product = a * b; // product is 30
int quotient = a / b; // quotient is 3 (integer division drops the remainder)
int remainder = a % b; // remainder is 1
Comparison Operators: Used to compare two values. The result is always a boolean (true or false).
== (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).
int playerAge = 21;
boolean canDrink = playerAge >= 21; // canDrink is true
int myNumber = 5;
boolean isTen = myNumber == 10; // isTen is false
Logical Operators: Used to combine boolean expressions.
&& (AND) is true only if both sides are true. || (OR) is true if at least one side is true. ! (NOT) inverts a boolean value.
boolean hasKeystone = true;
boolean hasGold = false;
// To open the door, you need the keystone AND 100 gold.
boolean canOpenDoor = hasKeystone && (goldAmount >= 100); // false
// To get a discount, you are a member OR have a coupon.
boolean getsDiscount = isMember || hasCoupon; // depends on other variables
Making Decisions and Repeating Actions
Programs often need to execute different code based on certain conditions or repeat a block of code multiple times. This is called control flow.
Conditional Statements
The if statement runs a block of code only if a condition is true. You can add an else block to run code if the condition is false. For multiple conditions, you can chain them with else if.
int grade = 85;
if (grade >= 90) {
System.out.println("Excellent!");
} else if (grade >= 80) {
System.out.println("Good job.");
} else {
System.out.println("You can do better.");
}
This code will print "Good job." because the first condition (grade >= 90) is false, but the second one (grade >= 80) is true.
Loops
Loops let you execute a block of code repeatedly. The for loop is great when you know exactly how many times you want to repeat.
// This loop prints numbers 1 through 5
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
The for loop has three parts in its parentheses, separated by semicolons:
- Initialization:
int i = 1runs once at the very beginning. - Condition:
i <= 5is checked before each repetition. If it's true, the loop runs. If false, it stops. - Increment:
i++runs after each repetition. It's shorthand fori = i + 1.
The while loop is simpler. It keeps running as long as its condition is true. It's useful when you don't know ahead of time how many repetitions are needed.
int diceRoll = 0;
// Keep rolling until we get a 6
while (diceRoll != 6) {
// In a real program, you'd generate a random number
diceRoll = (int)(Math.random() * 6) + 1;
System.out.println("You rolled a " + diceRoll);
}
System.out.println("You got a 6! You win!");
Now that you've got the essentials of variables, operators, and control flow, let's test your knowledge.
What is the name of the method that serves as the entry point for every Java application?
In Java, every statement must end with a semicolon (;).
These building blocks are the foundation for all the powerful and complex applications you'll learn to build in Java.