Java Programming Fundamentals: Core Syntax and Data Types

Java Programming Fundamentals: Core Syntax and Data Types

Overview of Java Essentials

Escape Characters in Java

Character Description
\t Tab character for alignment
\n Line feed newline
\\ Backslash character
\" Double quote character
\' Single quote character
\r Carriage return

Example implementation:

public class EscapeDemo {
    public static void main(String[] args) {
        System.out.println("Beijing\t Tianjin\t Shanghai");
        System.out.println("jack\nsmith\nmary");
        System.out.println("C:\\Windows\\System32\\cmd.exe");
        System.out.println("Teacher Han says:\"Study Java seriously, it's promising\");");
        System.out.println("Teacher Han says:'Study Java seriously, it's promising'");
        System.out.println("Han Shunping Education\r Beijing");
    }
}

Comments in Java

  • Single-line comments: //
  • Multi-line comments: /* */
  • Documentation comments: /** */

Documentation comments can be processed by JDK tools like javadoc to generate HTML documentation.

Example:

/**
 * @author Han Shunping
 * @version 1.0
 */
public class CommentExample {
    public static void main(String[] args) {
        // Single line comment
        /* Multi-line comment */
        int value1 = 10;
        int value2 = 30;
        int sum = value1 + value2;
        System.out.println("Result=" + sum);
    }
}

Code Conventions

  • Use Javadoc-style comments for classes and methods
  • Add explanatory notes for non-documentation comments
  • Indent using tabs, shift+tab for reverse indentation
  • Insert spaces around operators and assignment signs
  • Use UTF-8 encoding for source files
  • Keep lines under 80 characters

Identifier Naming Rules

  • Composed of letters, digits, underscore, or dollar sign
  • Cannot start with a digit
  • Reserved words cannot be used as identifiers
  • Case sensitive, no length limit
  • No spaces allowed

Naming conventions:

  • Package names: all lowercase (e.g., com.hsp.crm)
  • Class names: PascalCase (e.g., StudentInfo)
  • Variable and method names: camelCase (e.g., studentName)
  • Constants: uppercase with underscores (e.g., MAX_SIZE)

Binary Representation

For signed integers:

  • Most significant bit represents sign: 0 for positive, 1 for negative
  • Positive numbers have identical original, inverse, and complement codes
  • Negative number inverse code: keep sign bit, invert other bits
  • Negative number complement code: add one to inverse code
  • Zero has zero inverse and complement codes
  • Java uses signed integers
  • Calculations use complement representation

IntelliJ IDEA Shortcuts

  • Delete line: Ctrl+Y (customizable to Ctrl+D)
  • Copy line: Alt+Shift+Down Arrow
  • Code completion: Alt+/
  • Toggle comment: Ctrl+/
  • Import class: Alt+Enter
  • Format code: Ctrl+Alt+L
  • Run program: Alt+R
  • Generate code: Alt+Insert
  • Show class hierarchy: Ctrl+H
  • Navigate to method definition: Ctrl+B
  • Generate variable name: Type .var
  • Surround code block: Ctrl+Alt+T
  • Show all shortcuts: Ctrl+J
  • Iterator loop: itit
  • Enhanced for loop: I
  • Replace all occurrences: Ctrl+R
  • Global replace: Ctrl+Shift+R
  • Document comment: Ctrl+Shift+/
  • Method documentation: Type /** then Enter
  • Find class/interface: Ctrl+N
  • Find implementations: Ctrl+Alt+B
  • Convert to uppercase: Shift+Ctrl+U

Variables in Java

Key Points

  • Represents memory location with a name and type
  • Must be declared before use
  • Values can change within same data type range
  • Cannot have duplicate names in same scope
  • Consists of name, value, and type

Usage of Plus Operator

  • When both operands are numeric, performs addition
  • When either operand is string, performs concatenation
  • Left-to-right evaluation order

Example:

public class PlusOperator {
    public static void main(String[] args) {
        System.out.println(100 + 98); // Output: 198
        System.out.println("100" + 98); // Output: 10098
        System.out.println(100 + 3 + "hello"); // Output: 103hello
        System.out.println("hello" + 100 + 3); // Output: hello1003
    }
}

Data Types in Java

Java data types fall into two categories:

  • Primitive types: byte, short, int, long, float, double, char, boolean
  • Reference types: classes, interfaces, arrays

Integer Types

Used to store whole numbers like 12, 30, 3456.

Details:

  • Fixed ranges and sizes independent of OS
  • Default integer literal type is int
  • Long literals require suffix L or l
  • Use int unless larger values are needed
  • Bit is the smallest storage unit, byte is basic storage unit (8 bits)

Example:

public class IntegerDetails {
    public static void main(String[] args) {
        int n1 = 1; // 4 bytes
        long n2 = 1L; // Correct declaration
    }
}

Floating Point Types

Represent decimal numbers like 123.4, 7.8, 0.12.

Details:

  • Fixed ranges and sizes independent of OS
  • Default floating point literal type is double
  • Float literals require suffix F or f
  • Two forms: decimal and scientific notation
  • Prefer double for better precision

Example:

public class FloatDetails {
    public static void main(String[] args) {
        float f1 = 1.1F; // Correct
        double d1 = 1.1; // Correct
        double d2 = 1.1f; // Correct
        double d3 = .123; // Equivalent to 0.123
        System.out.println(d3);
        System.out.println(5.12e2); // Output: 512.0
        System.out.println(5E-2); // Output: 0.0512
        double precise = 2.1234567851;
        float approx = 2.1234567851F;
        System.out.println(precise);
        System.out.println(approx);
        
        double num1 = 2.7;
        double num2 = 8.1 / 3;
        System.out.println(num1);
        System.out.println(num2);
        
        if (Math.abs(num1 - num2) < 0.000001) {
            System.out.println("Values are approximately equal");
        }
    }
}

Character Type

Represents single characters, two bytes in size (can hold Chinese characters).

Details:

  • Character literals enclosed in single quotes
  • Escape sequences with backslash
  • Internally stored as Unicode integer
  • Can assign integer values to char variables
  • Supports arithmetic operations

Example:

public class CharDetails {
    public static void main(String[] args) {
        char c1 = 97; // Outputs 'a'
        System.out.println(c1);
        char c2 = 'a';
        System.out.println((int)c2); // Outputs 97
        char c3 = '韩';
        System.out.println((int)c3); // Outputs 38889
        char c4 = 38889;
        System.out.println(c4); // Outputs '韩'
        System.out.println('a' + 10); // Outputs 107
        char c5 = 'b' + 1;
        System.out.println(c5); // Outputs 'c'
    }
}

Boolean Type

Only accepts true or false values, occupies 1 byte.

Example:

public class BooleanExample {
    public static void main(String[] args) {
        boolean passed = true;
        if (passed) {
            System.out.println("Passed the exam");
        } else {
            System.out.println("Failed the exam");
        }
    }
}

Type Conversion

Automatic Conversion

Smaller precision types automatically convert to larger ones:

char → int → long → float → double

byte → short → int → long → float → double

Details:

  • Mixed operations promote to largest type
  • Assigning larger to smaller requires explicit casting
  • byte, short, char do not convert to each other automatically
  • These three types convert to int during calculations
  • boolean does not participate in conversion
  • Result type promotes to maximum operand type

Example:

public class AutoConversion {
    public static void main(String[] args) {
        int n1 = 10;
        float d1 = n1 + 1.1F; // Works
        byte b1 = 10; // Within range
        byte b2 = 1;
        byte b3 = 2;
        int s1 = b2 + b3; // Promotion to int
        byte b4 = 1;
        short s2 = 100;
        int num = 1;
        float f1 = 1.1F;
        double result = b4 + s2 + num + f1; // Promotes to double
    }
}
Explicit Conversion

Manual conversion from larger to smaller types using parentheses.

Details:

  • Required when converting from large to small type
  • Parentheses affect only nearest operand
  • char can hold int constants but not variables
  • byte, short, char calculate as int

Example:

public class ExplicitConversion {
    public static void main(String[] args) {
        int x = (int)(10 * 3.5 + 6 * 1.5); // Casts result to int
        char c1 = 100; // Valid
        int m = 100;
        char c2 = (char)m; // Requires cast
        System.out.println(c2); // Outputs 'd'
    }
}
String Conversion
  • Primitive to String: append empty string ""
  • String to primitive: use wrapper class parse methods

Example:

public class StringConversion {
    public static void main(String[] args) {
        int n = 100;
        float f = 1.1F;
        double d = 4.5;
        boolean b = true;
        String s1 = n + "";
        String s2 = f + "";
        String s3 = d + "";
        String s4 = b + "";
        System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);
        
        String s5 = "123";
        int num1 = Integer.parseInt(s5);
        double num2 = Double.parseDouble(s5);
        float num3 = Float.parseFloat(s5);
        long num4 = Long.parseLong(s5);
        byte num5 = Byte.parseByte(s5);
        boolean bool = Boolean.parseBoolean("true");
        short num6 = Short.parseShort(s5);
        System.out.println(num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5 + " " + num6 + " " + bool);
        System.out.println(s5.charAt(0));
    }
}

Operators in Java

Arithmetic Operators

Operate on numeric values.

Details:

  • Integer division truncates fractional part
  • Modulo operation equivalent to a - a/b * b

Example:

public class ArithmeticOps {
    public static void main(String[] args) {
        System.out.println(10 / 4); // Outputs 2
        System.out.println(10.0 / 4); // Outputs 2.5
        double d = 10 / 4;
        System.out.println(d); // Outputs 2.0
        System.out.println(10 % 3); // Outputs 1
        System.out.println(-10 % 3); // Outputs -1
        System.out.println(10 % -3); // Outputs 1
        System.out.println(-10 % -3); // Outputs -1
        
        int i = 10;
        i++;
        ++i;
        System.out.println("i=" + i); // Outputs 12
        
        int j = 8;
        int k = j++;
        System.out.println("k=" + k + "j=" + j); // Outputs 8 9
    }
}

Assignment Operators

Assign computed values to variables.

  • Basic: =
  • Compound: +=, -=, *=, /=, %=

Details:

  • Right-to-left evaluation
  • Left side must be a variable
  • Compound operators perform implicit casting

Example:

public class AssignmentOps {
    public static void main(String[] args) {
        int n1 = 10;
        n1 += 4; // Equivalent to n1 = n1 + 4
        System.out.println(n1); // Outputs 14
        n1 /= 3; // Equivalent to n1 = n1 / 3
        System.out.println(n1); // Outputs 4
        
        byte b = 3;
        b += 2; // Equivalent to b = (byte)(b + 2)
        b++; // Equivalent to b = (byte)(b + 1)
        System.out.println(b);
    }
}

Relational Operators

Compare values and return boolean results.

Example:

public class RelationalOps {
    public static void main(String[] args) {
        int a = 9;
        int b = 8;
        System.out.println(a > b); // true
        System.out.println(a >= b); // true
        System.out.println(a <= b); // false
        System.out.println(a < b); // false
        System.out.println(a == b); // false
        System.out.println(a != b); // true
        boolean flag = a > b;
        System.out.println("flag=" + flag);
    }
}

Logical Operators

Connect multiple conditions.

  • &&: Short-circuit AND
  • &: Non-short-circuit AND
  • ||: Short-circuit OR
  • |: Non-short-circuit OR
  • !: NOT
  • ^: XOR

Difference between && and &:

  • &&: If first condition is false, second is not evaluated
  • &: Both conditions are always evaluated

Similar for || vs |

Number Systems

Integer representations:

  • Binary: Starts with 0b or 0B
  • Decimal: Standard 0-9
  • Octal: Starts with 0
  • Hexadecimal: Starts with 0x or 0X

Example:

public class NumberSystems {
    public static void main(String[] args) {
        int binary = 0b1010;
        int decimal = 1010;
        int octal = 01010;
        int hex = 0X10101;
        System.out.println("binary=" + binary);
        System.out.println("decimal=" + decimal);
        System.out.println("octal=" + octal);
        System.out.println("hex=" + hex);
        System.out.println(0x23A);
    }
}

Bitwise Operators

Seven bitwise operators:

  • &: AND
  • |: OR
  • ^: XOR
  • ~: NOT
  • >>: Signed right shift
  • <<: Signed left shift
  • >>>: Unsigned right shift

Ternary Operator

Syntax: condition ? expression1 : expression2

If condition is true, returns expression1, otherwise expression2.

Example:

public class TernaryOp {
    public static void main(String[] args) {
        int a = 10;
        int b = 99;
        int result = a > b ? a++ : b--;
        System.out.println("result=" + result);
        System.out.println("a=" + a);
        System.out.println("b=" + b);
    }
}

Operator Precedence

Higher precedence operators evaluate first.

From highest to lowest:

  1. Parentheses ()
  2. Unary operators +, -, !, ~
  3. Multiplicative *, /, %
  4. Additive +, -
  5. Shift <<, >>, >>>
  6. Relational <, >, <=, >=
  7. Equality ==, !=
  8. Bitwise AND &
  9. Bitwise XOR ^
  10. Bitwise OR |
  11. Logical AND &&
  12. Logical OR ||
  13. Conditional ?:
  14. Assignment =, +=, -=, etc.

Tags: java programming fundamentals Syntax data-types

Posted on Sat, 22 Aug 2026 16:35:12 +0000 by uniboy86