Java – Syntax
First Java Program:
Although the “Hello World!” programme appears to be easy, it contains all of the core Java ideas that must be learned before moving on. To grasp all of these ideas, let’s dissect the “Hello World!” programme.
// Hello World! Example public class MyClass { public static void main(String[] args) { System.out.println("Hello World!"); } }
The following is the result of the aforementioned code:
Hello World!
The first line begins with //
and is a single line remark. Comments are usually added to computer code to make it easier to comprehend. When the compiler runs the code, it ignores it. For further information, please see the comment page.
In Java, every line of code must be contained within a class. MyClass is the name of the class in this example. It’s also a public class. A maximum of one public class can be found in any java application file. The name of the public class and the java programme file must be the same. The name of the java application file in this example is MyClass.java. Please keep in mind that Java is case-sensitive. In addition, the body of the class must be enclosed in curly brackets.
The Main Method()
Every public class in Java must have a main method that is invoked when the class is called. Please notice that the name of the public class and the java programme file must be the same.
System.out.println() and System.out.print()
In Java, there are two methods that may be used to print the output.
System.out.println()
prints the output on a new line.- The output of
System.out.print()
is printed on the same line.
Multiple variables can be used inside println()
or print(),
each separated by +.
public class MyClass { public static void main(String[] args) { System.out.println("Hello " + "World!."); System.out.println("Print in a new line."); System.out.println(); System.out.print("Hello " + "World!."); System.out.print("Print in the same line."); } }
The following is the result of the aforementioned code:
Hello World!.
Print in a new line.
Hello World!.Print in the same line.
Semicolons:
The semicolon is a statement terminator in a Java application. In Java, each statement must be terminated with a semicolon. It denotes that the current statement has ended and that the following statements are new statements. For instance, consider the following two statements:
System.out.println("Hello " + "World!."); System.out.println("Print in a new line.");
line change, “\n”
“\n” can be used to facilitate a line change within the system.out.println()
or system.out.print()
statements. “\n” directs the software to start a new line.
public class MyClass { public static void main(String[] args) { System.out.println("Hello \nWorld!."); System.out.print("Learning Java is fun.\nAnd easy too."); } }
The following is the result of the aforementioned code:
Hello
World!.
Learning Java is fun.
And easy too.
To run any of the above codes: Click Here.