Getting Started with Java

 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 ;.
    • Comments You can add comments to explain your code. Single-line comments start with //, while multi-line comments are enclosed between /* and /.

 2.3  Compiling and Running Java Programs: 

    • To run a Java program, you need to compile it first. The Java compiler (javac) translates your human-readable code into a machine-readable format called bytecode.
    • Once the program is compiled, you can run it using the Java Virtual Machine (java), which interprets the bytecode and executes your program.
    • Here's an example to demonstrate the compilation and execution process:
public class MyProgram {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 7;
        int sum = num1 + num2;
        System.out.println("The sum is: " + sum);
    }
}
    • Save the program as MyProgram.java, open a command prompt or terminal, navigate to the file's location, and execute the following commands:
javac MyProgram.java    // Compiles the program
java MyProgram          // Runs the program
    • The output will be: "The sum is: 12".
    • Keep in mind that when compiling and running Java programs, you need to ensure that you have the Java Development Kit (JDK) installed and configured on your system.


Pages 1,   ,  3,  4,  5,  6,  7,  8,  9