Java Tutorial menu

Java Syntax, Output and Comments

Every Java program follows a few simple rules. Learn them once and you will read any Java code more easily.

The Structure of a Program

Example

java
public class Main {
  public static void main(String[] args) {
    System.out.println("Java is fun");
  }
}

The example explained

PartMeaning
public class MainCreates a class named Main. All Java code lives inside a class
{ }Curly braces mark the start and end of a block of code
public static void main(String[] args)The main method, where the program starts
System.out.println(...)Prints text to the screen and moves to a new line
;Ends a statement

Java Syntax Rules

  • Java is case sensitive: Main and main are different names
  • Every statement ends with a semicolon ;
  • Class names start with a capital letter by convention, like Main or Student
  • Text (a string) goes inside double quotes "like this"

Printing Output

Java has two common print methods:

  • println() prints and then moves to the next line
  • print() prints and stays on the same line

Example

java
public class Main {
  public static void main(String[] args) {
    System.out.print("Rs ");
    System.out.print(500);
    System.out.println(" only");
    System.out.println("Thank you for shopping");
  }
}
Output
Rs 500 only
Thank you for shopping

Printing Numbers

Numbers do not need quotes. Java can also do maths inside println:

Example

java
public class Main {
  public static void main(String[] args) {
    System.out.println(45);
    System.out.println(10 + 15);
    System.out.println("10 + 15");
  }
}
Output
45
25
10 + 15

Inside quotes, 10 + 15 is just text, so Java prints it as it is.

Comments

Comments are notes for people who read the code. Java ignores them.

  • A single-line comment starts with //
  • A multi-line comment starts with /* and ends with */

Example

java
public class Main {
  public static void main(String[] args) {
    // This prints a greeting
    System.out.println("Hello");

    /* The next line prints the shop name.
       It is written on two lines. */
    System.out.println("Bismillah General Store"); // shop in Orangi
  }
}
Output
Hello
Bismillah General Store

Use comments to explain why you wrote something, not what every line does. Clear names often make comments unnecessary.

Exercise

Exercise

Which line prints text and then moves to a new line?

Learn Java with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp