Nanfeng

Notes on software development, code, and curious ideas

Java Syntax Basics

Your first Java program

1
2
3
4
5
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

Java is case-sensitive: HelloWorld and helloWorld are different identifiers.

Classes and source files

class declares a class, and public makes it accessible from other packages subject to Java’s access rules. A public top-level class must be stored in a file with the same name, so the example belongs in HelloWorld.java.

Class names conventionally use upper camel case:

1
2
3
public class StudentRecord {
// Fields, constructors, and methods go here.
}

The main method

For a conventional standalone application, the JVM begins with:

1
2
3
public static void main(String[] args) {
// Program instructions
}

System.out.println() writes a value followed by a line terminator.

Identifiers

Identifiers name classes, variables, methods, interfaces, and other program elements. A Java identifier:

  • may begin with a Unicode letter, _, or $;
  • may contain digits after the first character;
  • is case-sensitive;
  • cannot be a keyword or reserved literal.

Although $name and _value can be legal, ordinary application code typically uses names such as studentName, calculateTotal, and OrderService.

Comments

Single-line comments begin with //:

1
2
// Print a greeting.
System.out.println("Hello");

Block comments use /* ... */:

1
2
/* This explanation can span
more than one line. */

Documentation comments begin with /** and can be processed by Javadoc:

1
2
3
4
5
6
7
8
9
/**
* Returns the sum of two integers.
* @param left first value
* @param right second value
* @return the sum
*/
public int add(int left, int right) {
return left + right;
}

Comments should explain intent and constraints rather than restating obvious code. Blank lines are ignored by the compiler and can help separate logical sections.

Keywords

Words such as class, public, private, static, final, if, else, switch, for, while, new, return, try, catch, throw, extends, and implements have language-defined meanings and cannot be used as identifiers. Java keywords are lowercase.

+