Java Basics
1. Printing "Hello, World!"
Objective: Write a simple Java program that prints "Hello, World!" to the screen.
Step-by-Step Instructions:
1. Create a new Java file: Name it HelloWorld.java.
2. Write the class declaration:
● In Java, all code must be inside a class.
3. Write the main method:
● The main method is the entry point of any Java program.
4. Print the message:
● Use System.out.println() to print a message to the screen.
5. Close the class and method:
● End the main method and the class.
Run the program. You should see Hello, World! printed to the screen.
Code Example:
2. Variables and Data Types
Objective: Learn how to declare and use variables in Java.
Step-by-Step Instructions:
1. Create a new Java file: Name it VariablesExample.java.
2. Write the class and main method:
● Define a class and the main method as shown in the previous exercise.
3. Declare and initialize variables:
● Java uses specific data types like int for integers, double for decimal numbers,
String for text, and boolean for true/false values.
4. Print the values of the variables:
5. Close the class and method:
6. Run the program. You should see the values of the variables printed to the screen.
Code Example:
3. Conditional Statements (if-else)
Objective: Learn how to use if-else statements to make decisions in your program.
Step-by-Step Instructions:
1. Create a new Java file: Name it IfElseExample.java.
2. Write the class and main method:
3. Ask the user for their age:
● Use Scanner to take input from the user.
4. Use an if-else statement to check if the user is an adult or a minor:
5. Close the class and method:
6. Run the program. Enter an age when prompted, and the program will tell you if you’re
an adult or a minor.
Code Example:
4. Loops (for loop)
Objective: Learn how to use for loops to repeat tasks.
Step-by-Step Instructions:
1. Create a new Java file: Name it ForLoopExample.java.
2. Write the class and main method:
3. Use a for loop to print numbers from 1 to 5:
4. Close the class and method:
5. Run the program. You should see the numbers 1, 2, 3, 4, and 5 printed on the screen.
Code Example:
5. Functions (Methods)
Objective: Learn how to create and use methods to organize code.
Step-by-Step Instructions:
1. Create a new Java file: Name it MethodExample.java.
2. Write the class and main method:
3. Create a method to greet the user:
4. Call the method from main:
5. Close the class and method:
6. Run the program. The program should greet both "Alice" and "Bob".
Code Example: