In the last chapter, we made a Java file named Main.java and used this code to display "Hello World" on the screen:
public class Main { public static void main(String[] args) { // System.out.println("Abhiyantriki tutorials") ; System.out.println("Hello World"); } }
Explanation of the Example:
In Java, all code must be inside a class. In our example, we named the class "Main," and it's important to start class names with an uppercase letter.
Remember that Java is case-sensitive, so "MyClass" and "myclass" are considered different.
The Java file's name must match the class name. When saving the file, use the class name and add ".java" to the end of the filename.
Before running the example on your computer, ensure that Java is correctly installed. Refer to the "Get Started" chapter for Java installation instructions.
The expected output of the example is:
Hello World
The main() method is a necessary part of every Java program. It looks like this:
public static void main(String[] args)
Any code placed inside the main() method will run when you execute the program. You don't need to fully understand the keywords before and after main right now; you'll learn about them gradually throughout this tutorial.
For now, remember two key points:
Printing output in Java is typically done using the System.out.println() method. It allows you to display text and variables on the console. Here's a brief overview:
public class OutputExample { public static void main(String[] args) { System.out.println("Hello, World!"); // Prints "Hello, World!" int number = 42; System.out.println("The answer is: " + number); // Prints "The answer is: 42" } }
In Java, System.out.println() is a handy way to show information to users and debug your programs. You can print strings, numbers, and variables by combining them with the + operator within the parentheses.