Monday, May 20, 2024

Simple Java Program | Hello World Example

 First Java Program:

Here's a simple "Hello, World!" program in Java:

ja
public class HelloWorld {
public static void main(String[] args)
 System.out.println("Hello, World!"); }
 }

Explanation:

  • public class HelloWorld: This line declares a class named HelloWorld. In Java, every executable program is defined within a class.
  • public static void main(String[] args): This is the main method. It's the entry point for the program. When you execute a Java program, the JVM (Java Virtual Machine) looks for this method to start execution.
  • System.out.println("Hello, World!");: This line prints "Hello, World!" to the console.

Requirements for Execution:

To execute this Java program, you need:

  1. Java Development Kit (JDK): You must have the JDK installed on your computer. The JDK includes tools for developing and running Java programs, such as the Java compiler (javac) and the Java Virtual Machine (JVM) to execute Java bytecode.

  2. Java Compiler: Use the javac command to compile your Java source code into bytecode. Save the above code in a file named HelloWorld.java. Open a command prompt or terminal and navigate to the directory containing HelloWorld.java, then run:

    javac HelloWorld.java

    This command will compile HelloWorld.java into HelloWorld.class.

  3. Java Runtime Environment (JRE): To execute the compiled bytecode, you need the JRE installed. The JRE includes the JVM, which is responsible for running Java bytecode.

  4. Execution: After compiling successfully, you can run the program using the java command followed by the name of the class containing the main method (without the .class extension). In this case:

    java HelloWorld

    This command will execute the HelloWorld class, and you'll see the output "Hello, World!" printed on the console.

Make sure your environment variables are set up correctly to point to the JDK and JRE directories. After ensuring these requirements are met, you can create and execute Java programs on your system.

No comments:

Post a Comment

JVM(Java Virtual Machine)

  The JVM (Java Virtual Machine) is an essential component of the Java Runtime Environment (JRE). Its primary function is to execute Java by...