2.1 Writing Your First Java Program:
- Let's take your first step into the world of Java programming by writing a simple program that displays a friendly message.
- Open up your preferred text editor or integrated development environment (IDE) and follow along!
public class MyFirstProgram {
public static void main(String[] args) {
System.out.println("Hello, Folks!");
}
}
- In this program, we have created a class called
MyFirstProgram
.
- Every Java program starts with a class definition.
- Inside the class, we have a method named
main
. This is where the program starts executing.
- The line
System.out.println("Hello, World!");
prints the message "Hello, World!" to the console. This is a simple way to display output in Java.
- To run this program, save it with a
.java
extension (e.g., MyFirstProgram.java
).
- Open a command prompt or terminal, navigate to the folder containing the file, and use the following commands:
javac MyFirstProgram.java // Compiles the program
java MyFirstProgram // Runs the program
2.2 Understanding Basic Syntax and Structure:
Java has a specific syntax and structure that you need to understand. Here are a few key points:
- Case Sensitivity: Java is case-sensitive, so
myVariable
and myvariable
are considered different variables.
- Blocks: Code in Java is organized into blocks, enclosed by curly braces
{}
. Blocks define the scope of variables and control flow structures like loops and conditional statements.
- Statements: Java programs are made up of statements. Each statement ends with a semicolon
;
.