Java Programming Fundamentals
Java Basics
Setting Up Your Workshop
Before you can write Java, you need two things: a toolkit and a workshop. The toolkit is the Java Development Kit (JDK), and the workshop is your Integrated Development Environment (IDE).
The JDK contains all the essential tools for programming in Java, including the compiler, which translates your human-readable code into something a computer can understand. The IDE is a software application that makes writing code much easier. It provides a text editor, tools for debugging, and ways to run your programs, all in one place.
Popular IDEs for Java include IntelliJ IDEA, Eclipse, and Visual Studio Code (with the right extensions). Once you have a JDK installed and an IDE set up, you're ready to start coding.
Your First Java Program
It's a tradition in programming to start with a program that just says hello. Let's look at the code for a classic "Hello, World!" program in Java.
public class HelloWorld {
public static void main(String[] args) {
// This line prints text to the console
System.out.println("Hello, World!");
}
}
This might look a bit complicated, but let's break it down.
-
public class HelloWorld { ... }: In Java, all code lives inside a class. You can think of a class as a blueprint or a container for your program's logic. We've named oursHelloWorld. -
public static void main(String[] args) { ... }: This is the main method. When you run a Java program, the computer looks for this exact line. It's the entry point, the place where your program officially begins. -
System.out.println("Hello, World!");: This is the instruction that does the work. It tells the system to print the text inside the parentheses to the console. Theprintlnpart means it also adds a new line at the end, like hitting the Enter key.
Storing Information
Programs need to store and manage information. We do this using variables. A variable is like a labeled box where you can keep a piece of data. Each variable has a data type, which tells the computer what kind of information it can hold.
Java has several built-in data types, called primitive types. Here are the most common ones you'll use:
| Data Type | Description | Example |
|---|---|---|
int | Stores whole numbers | 10, -5, 0 |
double | Stores decimal numbers | 3.14, -0.5 |
boolean | Stores true or false values | true, false |
char | Stores a single character | 'A', '!' |
There's also a very important non-primitive type called String (with a capital S), which is used for storing sequences of characters, like words and sentences.
Here’s how you declare a variable and give it a value:
// Declaring an integer variable named 'score'
int score;
// Assigning a value to it
score = 100;
// You can also do it in one line
String playerName = "Alex";
double temperature = 98.6;
boolean isGameOver = false;
Making Things Happen with Operators
Operators are special symbols that perform operations on your variables and values. You already know many of them from math.
Java uses arithmetic operators like
+(addition),-(subtraction),*(multiplication), and/(division). There's also the modulo operator,%, which gives you 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)
int remainder = a % b; // remainder is 1
We also use operators to compare values. These comparison operators always result in a boolean value (true or false).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
> | Greater than | 5 > 3 | true |
< | Less than | 5 < 3 | false |
>= | Greater than or equal to | 5 >= 5 | true |
<= | Less than or equal to | 5 <= 3 | false |
Controlling the Flow
So far, our code runs straight from top to bottom. But what if we want it to make decisions or repeat actions? That's where control structures come in.
The if statement lets your program execute a block of code only if a certain condition is true.
int score = 85;
if (score > 60) {
System.out.println("You passed!");
} else {
System.out.println("You need to study more.");
}
In this example, because score is greater than 60, the program will print "You passed!". If score were 50, it would print the message in the else block instead.
What if you need to do something over and over? For that, we use loops. The for loop is great when you know exactly how many times you want to repeat an action.
// This loop will run 5 times
for (int i = 1; i <= 5; i++) {
System.out.println("The count is: " + i);
}
This loop initializes a counter variable i to 1. It will continue running as long as i is less than or equal to 5, and it increments i by 1 after each cycle (i++).
The while loop is another option. It repeats a block of code as long as a condition remains true. It's useful when you don't know ahead of time how many repetitions are needed.
int fuel = 10;
while (fuel > 0) {
System.out.println("Engine is running.");
fuel = fuel - 1; // Decrease fuel
}
System.out.println("Out of fuel!");
Input and Output
We've already seen how to output text with System.out.println(). But how do we get input from the user? One common way is to use the Scanner class.
First, you need to tell your program that you want to use the Scanner. You do this by adding import java.util.Scanner; at the very top of your file. Then, you can create a Scanner object to read what the user types.
import java.util.Scanner; // Must be at the top
public class UserInput {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine(); // Read a line of text
System.out.print("Enter your age: ");
int age = input.nextInt(); // Read an integer
System.out.println("Hello, " + name + "! You are " + age + " years old.");
}
}
This program asks for a name and an age, reads the user's responses, and then uses that information to print a personalized greeting. This combination of input, processing, and output is at the heart of most computer programs.
Let's test what you've learned about Java's fundamental building blocks.
What is the primary role of the Java Development Kit (JDK)?
In a standard Java application, what is the exact signature of the main method, which serves as the program's entry point?
With these basics—variables, operators, and control flow—you have the tools to start writing simple but powerful programs in Java.