A simple Java program consists of:
- A class
- A main method – the entry point of execution
Syntax:
public class ClassName {
// fields, methods, and main go here
}
public static void main(String[] args) {
// Code starts running from here
}Example: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}- public class HelloWorld defines the class.
public static void main(String[] args)is the main method where the program starts.System.out.println("Hello, World!");prints a message to the console.
Compiling and Running Java Programs Using the Command Line
Steps:
- Write the program in a file named HelloWorld.java.
- Open the Command Prompt (Windows) or Terminal (Linux/Mac).
- Navigate to the directory where your .java file is saved.
- Compile the Java file using the Java compiler:
javac HelloWorld.java- This will generate a bytecode file: HelloWorld.class.
Compiling and Running Java Programs Using an IDE:
Popular Java IDEs:
- Eclipse
- VS Code
- IntelliJ IDEA
- NetBeans
- BlueJ
Steps (Generic for most IDEs):
- Open the IDE and create a new Java project.
- Create a new Java class file (e.g., HelloWorld).
- Write the code inside the class with a main method.
- Click “Run” or “Execute” button (usually a green play icon).
- The output appears in the console window of the IDE.
Using Scanner for Reading Input:
The Scanner class (from java.util package) is used to take user input from the keyboard.
Example:
import java.util.Scanner;
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create Scanner object
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt(); // Read an integer
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt(); // Read an integer
int sum = num1 + num2;
System.out.println("Sum: " + sum);
scanner.close();
}Using System.out.print() and System.out.println():
- System.out.print() prints text without moving to a new line.
- System.out.println() prints text and moves to the next line.
Example:
public class OutputExample {
public static void main(String[] args) {
System.out.print("Hello");
System.out.print(" World");
System.out.println("!");
System.out.println("This is on a new line.");
}
}Output:
Hello World!
This is on a new line.