timerring

01 Variables, Operators, Expressions, Input and Output

January 3, 2024 · 3 min read
Tutorial
Java
If you have any questions, feel free to comment below. Click the block can copy the code.
And if you think it's helpful to you, just click on the ads which can support this site. Thanks!

Syntax Basics #

Variables #

  1. In Java, outputting a variable without assigning it a value causes an error.
  2. Built-in data types
TypeBytesExampleAdditional notes
byte1123
short212345$2^{16}=65536$
int4123456789$2^{32}=2147483648≈2.1*10^9$
long81234567891011L$2^{64}≈10^{18}$
float41.2FAbout 6 or 7 significant decimal digits; subsequent digits are imprecise approximations. To explicitly denote a float, append f or F.
double81.2, 1.2DAbout 15 or 16 significant decimal digits; subsequent digits are imprecise approximations. To explicitly denote a double, append d or D.
boolean1true, false
char2‘A’ASCII code correspondences: a-97 A-65 0-48
  1. Constants

Java’s final is equivalent to C’s const.

final int N = 110;
  1. Type conversion
    Explicit conversion: int x = (int)'A';
    Implicit conversion: double x = 12, y = 4 * 3.3;
    (First, the int is converted to double. Principle: prefer converting a type with a smaller range to one with a larger range.)
    (Explicit conversion (casting) can convert from a larger range to a smaller one; implicit conversion can only convert from a smaller range to a larger one.)

  2. Operators
    /: In Java and C, integer division truncates toward zero (-30/20=-1); in Python, integer division rounds down (-30/20=-2).
    %: In mathematical modulo, the result can only be positive, but in Java and C it can be negative.

  3. Expressions
    Comparing floating-point numbers:
    Direct comparison can be inaccurate: if(x==y). Usually, compare the absolute difference between the two numbers with a very small number: if(Math.abs(x-y)<1e-8).

  4. Input and output:
    Java names use camel case; for two words, capitalize the first letter of the second word.
    (1) Input method 1:
    Input uses the Scanner utility; first import it with import java.util.Scanner;
    Method 1 is less efficient and is used for smaller input sizes (fewer than 10 to the fifth power input items).

import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();  // Read the next string; next stops at whitespace (spaces, newlines, tabs, etc.)  
        int x = sc.nextInt();  // Read the next integer
        float y = sc.nextFloat();  // Read the next single-precision floating-point number
        double z = sc.nextDouble();  // Read the next double-precision floating-point number
        String line = sc.nextLine();  // Read the next line as a string
    }
}

(2) Input method 2:
When there are more than 10 to the fifth power input items, BufferedReader is generally used.
With BufferedWriter, integers must be converted manually from strings to int.

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        int z = Integer.parseInt(br.readLine());
        System.out.println(str);
        // If there are spaces, split the input manually first
        // Double quotes denote strings; single quotes denote characters   
        String[] strs = br.readLine().split(" ");
        int x = Integer.parseInt(strs[0]);
        int y = Integer.parseInt(strs[0]);
        System.out.println(x + y);
    }
}
  1. Output
    (1) Output method 1: slow
  • Both double and float use %f in Java, not %lf.
public class Main {
    public static void main(String[] args) throws Exception {
      // Appends a newline; can output strings, variables, numbers, etc., but cannot format output
        System.out.println(123);  // Output an integer + newline
        System.out.println("Hello World");  // Output a string + newline
        // Does not append a newline; otherwise like println, and cannot format output  
        System.out.print(123);  // Output an integer
        System.out.print("yxc\n");  // Output a string
        // Formatted output, like printf in C++
        System.out.printf("%04d %.2f\n", 4, 123.456D);  // Formatted output; both float and double use %f
        // %04d pads to four digits with leading zeros, commonly used for years; %4d pads to four positions with leading spaces; %-4d pads with trailing spaces
    }
}

Output formats for different variable types in System.out.printf():
(1) int: %d
(2) float: %f, with 6 decimal places by default
(3) double: %f, with 6 decimal places by default
(4) char: %c; a newline is also a character, represented by '\n'
(5) String: %s

(2) Output method 2: faster
Remember to flush the buffer manually at the end; otherwise, the output may not appear in some cases.
bw.flush(); // Flush the buffer manually

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        bw.write("Hello World\n");
        bw.flush();  // Flush the buffer manually
    }
}

<< prev | Density... Continue strolling 02 Conditional... | next >>

If you want to follow my updates, or have a coffee chat with me, feel free to connect with me: