Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Introduction to JAVA
  5. Writing Simple Java Programs

Writing Simple Java Programs

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.

Steps:

  1. Write the program in a file named HelloWorld.java.
  2. Open the Command Prompt (Windows) or Terminal (Linux/Mac).
  3. Navigate to the directory where your .java file is saved.
  4. Compile the Java file using the Java compiler:
javac HelloWorld.java
  • This will generate a bytecode file: HelloWorld.class.

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.

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();
    }
  • 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.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *