Skip to content

Java Crash Course

About Java

Java is a widely used computer programming language known for its cross-platform, object-oriented, and generic programming features. It is extensively applied in enterprise-level web application development and mobile application development.

Environment Installation

Refer to JDK.

Basic Syntax

Main Function

Similar to C/C++, Java requires a function (referred to as a method in object-oriented programming) as the entry point for program execution.

The format of Java's main function is fixed, as follows:

1
2
3
4
5
class Test {
    public static void main(String[] args) {
        // Program code
    }
}

A packaged Java program (typically named *.jar) can contain many such functions. However, when running the program, only one of these functions will be executed, as defined in the Jar's Manifest file. This knowledge is generally not required in OI competitions.

Comments

Like C/C++, Java uses // and /* */ to comment single lines and multiple lines, respectively.

Basic Data Types

Type Name Meaning
boolean Boolean type
byte Byte type
char Character type
double Double-precision floating-point
float Single-precision floating-point
int Integer type
long Long integer type
short Short integer type
null Null

Variable Declaration

1
2
3
4
int a = 12; // Declare a as integer type and assign it the value 12
String str = "Hello, OI-wiki"; // Declare string variable str
char ch = 'W';
double PI = 3.1415926;

final Keyword

final means the result is final and unchangeable. A variable modified by final can only be assigned once and cannot be changed thereafter.

1
final double PI = 3.1415926;

Arrays

1
2
3
// An integer array with ten elements
// Syntax: dataType[] variableName = new dataType[arraySize]
int[] ary = new int[10];

Strings

  • String is a built-in class in Java.

1
2
3
4
5
6
// The simplest way to construct a string variable is as follows
String a = "Hello";

// A string variable can also be constructed from a character array
char[] stringArray = { 'H', 'e', 'l', 'l', 'o' };
String s = new String(stringArray);

Packages and Importing Packages

Classes (Class) in Java are placed within packages (package). Duplicate class names are not allowed within the same package. The first line of a class typically specifies which package the class belongs to. For example:

1
package org.oi-wiki.tutorial;

The naming convention for packages is generally: top-level domain of project owner.second-level domain of project owner.project name.

Use the import keyword to import classes that are not in the same package as the current class. For example, the Scanner class used below:

1
import java.util.Scanner;

To import all classes under a package, simply replace the class name before the semicolon in the statement with *.

Input

Command-line input can be handled via the Scanner class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package org.oiwiki.tutorial;

import java.util.Scanner;

class Test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in); // System.in is the input stream
        int a = scan.nextInt();
        double b = scan.nextDouble();
        String c = scan.nextLine();
    }
}

Output

Variables can be formatted for output.

Symbol Meaning
%f Floating-point type
%s String type
%d Integer type
%c Character type

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Test {
    public static void main(String[] args) {
        int a = 12;
        char b = 'A';
        double s = 3.14;
        String str = "Hello world";
        System.out.printf("%f\n", s);
        System.out.printf("%d\n", a);
        System.out.printf("%c\n", b);
        System.out.printf("%s\n", str);
    }
}

Control Statements

Java's flow control statements are essentially the same as those in C++.

Selection

  • if

1
2
3
4
5
6
7
class Test {
    public static void main(String[] args) {
        if ( /* condition */ ){
            // Code executed when the condition is true
        }
    }
}

  • if...else

1
2
3
4
5
6
7
8
9
class Test {
    public static void main(String[] args) {
        if ( /* condition */ ) {
            // Code executed when the condition is true
        } else {
            // Code executed when the condition is false
        }
    }
}

  • if...else if...else

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Test {
    public static void main(String[] args) {
        if ( /* condition */ ) {
            // Code executed when condition is true
        } else if ( /* condition2 */ ) {
            // Code executed when condition2 is true
        } else {
          // Code executed when none of the above conditions are true
        }
    }
}

  • switch...case

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Test {
    public static void main(String[] args) {
        switch ( /* expression */ ){
          case /* value 1 */:
              // Code executed when the expression matches value 1
              break; // Without break, the program will continue sequentially until a break is encountered
          case /* value 2 */:
              // Code executed when the expression matches value 2
              break;
          default:
              // Code executed when the expression does not match any listed values
        }
    }
}

Loops

  • for

The for keyword has two usage patterns. The first is the ordinary for loop, structured as follows:

1
2
3
4
5
6
7
class Test {
    public static void main(String[] args) {
        for ( /* initialization */; /* loop condition */; /* step executed after each iteration */ ) {
            // Code executed while the loop condition is true
        }
    }
}

The second is similar to C++'s foreach, used to iterate over data in arrays or collections. It essentially hides the loop variable from the first pattern. The structure is as follows:

1
2
3
4
5
6
7
class Test {
    public static void main(String[] args) {
        for ( /* elementTypeX */ /* elementNameY */ : /* collectionZ */ ) {
            // In each iteration of this block, elementY will be one element from collectionZ.
        }
    }
}

  • while

1
2
3
4
5
6
7
class Test {
    public static void main(String[] args) {
        while ( /* condition */ ) {
            // Code executed while the condition is true
        }
    }
}

  • do...while

1
2
3
4
5
6
7
class Test {
    public static void main(String[] args) {
        do {
          // Code to execute
        } while ( /* loop condition */ );
    }
}

Notes

Class Name Must Match File Name

Creating a Java source program requires the class name to match the file name for successful compilation; otherwise, the compiler will report that the class cannot be found. Typically, this file name is specified by the specific OJ.

Example:

Add.java

1
2
3
4
5
class Add {
    public static void main(String[] args) {
        // ...
    }
}

In this file, the class name must be Add for compilation to succeed.