Java Basics
Welcome to the first part of the Learn Java series! In this section, we’ll introduce you to the basics of Java programming, covering core concepts like variables, data types, control structures, and more.
Setting Up Your Java Environment
Before we begin coding, make sure you have Java Development Kit (JDK) installed. You can download it from the official Oracle website. Once installed, ensure your environment variables are set up properly so that the javac
and java
commands can be accessed from the command line.
Variables and Data Types
In Java, variables are used to store data that can be manipulated by the program. Each variable has a specific data type that defines what kind of data it can store. Here’s an example of declaring and initializing variables:
int age = 25;
double salary = 55000.50;
String name = "John Doe";
In the example above:
int
is an integer data type for whole numbers.double
is used for floating-point numbers (numbers with decimals).String
is used for sequences of characters (text).
Control Structures
Java supports control structures like if-else statements, loops, and switch cases, allowing you to control the flow of your program. Below is an example of an if-else statement:
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
Writing and Running Your First Program
Let’s put everything together and write your first full Java program. Create a file named BasicExample.java
and add the following code:
public class BasicExample {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
System.out.println("Hello, " + name + "!");
System.out.println("You are " + age + " years old.");
}
}
To run the program, follow these steps:
- Open your terminal and navigate to the folder where
BasicExample.java
is saved. - Compile the program:
javac BasicExample.java
- Run the program:
java BasicExample
- You should see the following output:
Hello, Alice! You are 30 years old.
Conclusion
Congratulations! You’ve written and executed your first Java program. In the next section, we will dive deeper into Object-Oriented Programming (OOP) concepts, which are the foundation of Java’s design.