---
title: Java Basic Syntax
description: "## Basic Syntax Initial Code Analysis: hello.java ```java public class Hello { public static void main(String[] args) { System.out.println(\"Hello There~\"); } } ``` Main function & the entry point of the program. ```java def func(): pass if __name__ == \"__main__\":…"
url: "https://www.nullflag.com/support/kb/cpp_c_java_arm64_javascript/java_basic/java-basic-syntax/"
updated: "2025-10-30"
category: Java Basic Knowledge
---

# Java Basic Syntax

## Basic Syntax

Initial Code Analysis: hello.java

```java

                public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello  There~");
    }
}
```

Main function & the entry point of the program.

```java

                def func():
    pass

if __name__ == "__main__":
	func()
```

FileName

```javascript

                A file can contain at most one public class, and the file name must be the same as the public class name.
If the file contains multiple classes, the file name must still match the public class name.
If the file contains multiple classes but no public class, the file name can be any class name.
```

Class Naming

```java

                Use PascalCase with the first letter capitalized, e.g.：Hello、UserInfo、PersonApplication
```

Class modifiers: public, default (if omitted).
Member modifiers inside classes: public, private, protected, default (if omitted).
Static members can be called directly without instantiation.

```java

                class MyTest{

    public void f1(){
        System.out.println("f1");
    }

    public static void f2(){
        System.out.println("f2");
    }
}

public class Hello {

    public static void main(String[] args) {
        MyTest.f2();

        //1.Instantiate
        MyTest obj = new MyTest();
        // 2.Object call
        obj.f1();

    }
}
```

```java

                /**
 * @author calleng
 * @version 1.0
 * @date 2024/07/04 14:58
 * @desc
 */

class Person{
    public static void showInfo() {
        System.out.println("ningkong detail information");
    }

    public void doSomething(){
        // Instance method
        System.out.println("Instance method");
    }
}

public class Main {
    public static void main(String[] args) {
        Person.showInfo();  // 1. Static function direct call
          //1.Instantiate
        Person obj = new Person();    // Instantiate object obj = new Person();
         // 2.2. Object call
        obj.doSomething();   // Object calls doSomething
    }
}
```

```javascript

                class Person {
    public void f2() {
        //  Instance method
        System.out.println("I am the F1 function");
    }
}

public class Hello {
    public static void main(String[] args) {
        //  Instantiate object  obj = new Person();
        Person obj = new Person();

        // Object calls f2
        obj.f2();
    }
}
```

void indicates that a method does not return a value.
If a method does return a value, you must specify the return type in the method definition.
Method names should use camelCase naming convention.

```java

                class MyTest{

    public int f1(){  //  If there is a return value, the method definition must specify the return type.
        System.out.println("f1");

        return 123;
    }

    public static String f2(){
        System.out.println("f2");
        return "hahaha";
    }
}

public class Main {

    public static void main(String[] args) {

        MyTest obj = new MyTest();  // Instantiate object obj = new MyTest()
        int v1 = obj.f1();

        String v2 = MyTest.f2();
    }
}
```

Parameters
Parameters must explicitly indicate what type they are.

```java

                class MyTest {

    public int f1(int a1, int a2) {  // Parameters must explicitly specify their type.
        int result = a1 + a2;
        return result;
    }

}

public class Main {

    public static void main(String[] args) { //  main’s parameter type → String array, which is a container holding strings.
        MyTest obj = new MyTest();
        int v1 = obj.f1(1, 2);
    }
}
```

Supplement

```java

                Doesn’t the official Python source code also have definitions similar to Java?

def func(a1,a2):
	return a1 + a2

# Suggestion
def foo(a1: str a2:int) -> int
	return 1

foo(11,22)
```

## Comments

```java

                /**
 * Comment for this class
 */
public class Hello {

    /**
     * What does this method do ...
     * @param v1 size
     * @param v2 dimension
     * @return returns some value (xxx)
     */
    public static String getSign(int v1, String v2) {
        return "This is very hapy";
    }

    public static void main(String[] args) {
        // Single-line comment #
        // int age = 18;

        /* Multi-line comment
        String name = "Calleng";
        int size = 18;
         */
    }
}
```

## Variables and Constants

```java

                public class Hello {

    public static void main(String[] args) {
        String name = "Ning kong ";
        name = "calleng";

        int age = 19;   //Define variable
        age = 20;     // Can be modified later

        final int size = 18;  //Define constant, fixed value
    }
}
```

Output

```java

                v1 = [111,22]
v2 = 345
```

## Input and Output

```java

                import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        // Input
        Scanner input = new Scanner(System.in);
        String text = input.nextLine();

        // Output
        System.out.println(text);  // println means it will print with a new line
        // System.out.print(text);
    }
}
```

```java

                import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        // output
        System.out.print("Please Input the words：");

        // Input
        Scanner input = new Scanner(System.in);
        String text = input.nextLine();

        // output
        System.out.println(text);
    }
}
```

## conditional statement

```java

                public class Hello {

    public static void main(String[] args) {
        int age = 19;

        if (age < 18) {
            System.out.println("Teenager");
        } else if (age < 40) {
            System.out.println("Adult");
        } else {
            System.out.println("Senior");
        }
    }
}
```

```java

                public class Hello {

    public static void main(String[] args) {  // Conditional branching with switch
        int score = 85;

        switch (score / 10) {   // Divide by 10 to group ranges (80–89, 90–99, etc.)
            case 10:
            case 9:
                System.out.println("Grade: A");
                break;
            case 8:
                System.out.println("Grade: B");
                break;
            case 7:
                System.out.println("Grade: C");
                break;
            case 6:
                System.out.println("Grade: D");
                break;
            default:
                System.out.println("Grade: F");
                break;
        }
    }
}
```

## Loop Statements

### while loop

```java

                public class Hello {
    public static void main(String[] args) {
        int count = 0;
        while (count < 3) {
            System.out.println("Processing...");
            count += 1; // increment to avoid infinite loop
        }
    }
}
```

```java

                public class Hello {
    public static void main(String[] args) {
        int seconds = 3;
        while (seconds > 0) {
            System.out.println("Countdown: " + seconds);
            seconds--;
        }
        System.out.println("Go!");
    }
}
```

### do…while loop (executes at least once)

```java

                public class Hello {
    public static void main(String[] args) {
        int count = 0;
        do {
            System.out.println("Processing...");
            count += 1;
        } while (count < 3);
    }
}
```

### for loop

```java

                public class Hello {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println("Hello");
        }
    }
}
```

```java

                public class Hello {

    public static void main(String[] args) {
         String[] names = {"Alice", "Bob", "Child", "BaiDen"};
        // nameList.length   4
        // nameList[0]

        for (int idx = 0; idx < nameList.length; idx++) {
            String ele = nameList[idx];
            System.out.println("Index " + i + " -> " + item);
        }
    }
}
```

```java

                public class Hello {
    public static void main(String[] args) {
        // break: exit the loop immediately
        for (int i = 1; i <= 10; i++) {
            if (i == 5) break; // stop at 5
            System.out.print(i + " "); // 1 2 3 4
        }
        System.out.println();

        // continue: skip the current iteration
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) continue; // skip evens
            System.out.print(i + " "); // 1 3 5 7 9
        }
        System.out.println();
    }
}
```

## Data Types

### int type

- byte — 1 byte. Range: -128 ~ 127 (i.e., -2^7 ~ 2^7 - 1)
- short — 2 bytes. Range: -32,768 ~ 32,767
- int — 4 bytes. Range: -2,147,483,648 ~ 2,147,483,647
- long — 8 bytes. Range: -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807

```java

                public class Hello {
    public static void main(String[] args) {
        byte  v1 = 32;
        short v2 = 10_000;
        int   v3 = 22_221_331;
        long  v4 = 554_534_353_424L; // note the L suffix for long literals
    }
}
```

Reminder (RE context) In reverse engineering, some strings are stored/handled as byte arrays (often UTF-8).

```java

                name = "Ningkong"                    # Define a string containing Chinese characters
value = name.encode("utf-8")        # Encode to UTF-8 bytes
print(value)                        # b'xe9xb2x9cxe5xaex81'
info = [b for b in value]           # Store each byte (0–255) in a list
print(info)                         # [233, 178, 156, 229, 174, 129]
```

```java

                import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Hello {
    public static void main(String[] args) {
        // 1) Byte array → String (these are ASCII codes; result is a URL-like query string)
        byte[] data = {
            97,105,100,61,50,52,54,51,56,55,53,55,49,38,97,117,116,111,95,112,108,97,121,61,48,38,
            99,105,100,61,50,56,57,48,48,56,52,52,49,38,100,105,100,61,75,82,69,104,69,83,77,85,
            74,104,56,116,70,67,69,86,97,82,86,112,69,50,116,97,80,81,107,55,87,67,104,67,74,103,
            38,101,112,105,100,61,48,38,102,116,105,109,101,61,49,54,50,55,49,48,48,57,51,55,38,
            108,118,61,48,38,109,105,100,61,48,38,112,97,114,116,61,49,38,115,105,100,61,48,38,
            115,116,105,109,101,61,49,54,50,55,49,48,52,51,55,50,38,115,117,98,95,116,121,112,101,
            61,48,38,116,121,112,101,61,51
        };

        // Specify charset explicitly (UTF-8 here is fine for ASCII subset too)
        String dataString = new String(data, StandardCharsets.UTF_8);
        System.out.println("String: " + dataString);

        // 2) String → byte array (encodings)
        String name = "Ningkong";

        byte[] gbk = name.getBytes(Charset.forName("GBK"));
        System.out.println("GBK bytes:  " + Arrays.toString(gbk));

        byte[] utf8 = name.getBytes(StandardCharsets.UTF_8);
        System.out.println("UTF-8 bytes:" + Arrays.toString(utf8));
    }
}
```

![](https://support.nullflag.com/wp-content/uploads/2025/09/image-20220127173504514-7625739-1024x253.png)

Requirement (Reverse Engineering Context)
Task: In a certain app’s reverse engineering, you obtain a Java byte array like [-50, -28, -59, -26, -58, -21].
Convert this signed-Java-byte array into a string using Python.

```javascript

                Java byte range: -128 ~ 127 (signed)
Python byte range: 0 ~ 255 (unsigned)

Mapping idea:

  Java  0  1   2  3  4 .. 127 -128 -127 -126    -3  -2  -1
Python  0  1   2  3  4 .. 127  128  129  130 ...253 254 255

byte_list = [-50,-28,-59,-26,-58,-21]

“Convert the numbers into bytes and concatenate them into a bytearray.”
```

```python

                def java_bytes_to_str(jbytes, encoding="utf-8", errors="strict"):
    """
    Convert a list of signed Java bytes (-128..127) into a Python str
    using the specified encoding (e.g., 'utf-8', 'gbk').
    """
    # Map signed [-128..127] -> unsigned [0..255]
    unsigned = [(b if b >= 0 else b + 256) for b in jbytes]
    # Build a bytes-like object and decode
    return bytearray(unsigned).decode(encoding, errors)

# Examples:
gbk_list  = [-50, -28, -59, -26, -58, -21]
utf8_list = [-26, -83, -90, -26, -78, -101, -23, -67, -112]

print(java_bytes_to_str(gbk_list,  encoding="gbk"))
print(java_bytes_to_str(utf8_list, encoding="utf-8"))

# bytearray(...).decode(...) is valid; you can also use bytes(...).decode(...).

# If you’re unsure of the charset, try utf-8 first (Android strings are commonly UTF-8), otherwise test gbk, utf-16le, etc.
```

```python

                byte_list = [-50, -28, -59, -26, -58, -21]
bs = bytearray()
for item in byte_list:
    if item < 0:
        item += 256
    bs.append(item)

text = bs.decode('gbk')
print(text)
```

```python

                data_list = [-26, -83, -90, -26, -78, -101, -23, -67, -112]
bs = bytearray()
for item in data_list:
    if item < 0:
        item += 256
    bs.append(item)

text = bs.decode('utf-8')
print(text)
```

### Java side notes: char and String

```java

                char v1 = 'x';
char v2 = 'Ning';
```

```java

                String = "NingKong";
```

**Reminder:** A string is composed of **multiple characters** (not “multiple strings”).

### Reconstructing Java strings from bytes/chars

```java

                import java.io.UnsupportedEncodingException;

public class Hello {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String v1 = "NingKong";
        String v2 = new String("NingKong"); // same content

        // From raw bytes (assumed UTF-8)
        String v4 = new String(new byte[]{-26, -83, -90, -26, -78, -101, -23, -67, -112}, "UTF-8");

        // From raw bytes (GBK)
        String v5 = new String(new byte[]{-50, -28, -59, -26, -58, -21}, "GBK");

        // From chars
        String v6 = new String(new char[]{'Ning', 'Kong', 'Kang'});
    }
}
```

Common String APIs (quick reference):

```java

                public class Hello {
    public static void main(String[] args) {
        String origin = "This is a big question";     // Define original string

        char    c  = origin.charAt(5);     // Get character at index 5
        int     n  = origin.length();      // Get string length
        for (int i = 0; i < n; i++) {     // Iterate through each character
            char ch = origin.charAt(i);    // Get character at current position
        }

        String t  = origin.trim();         // Remove leading/trailing whitespace
        String lo = origin.toLowerCase();  // Convert to lowercase
        String up = origin.toUpperCase();  // Convert to uppercase
        String[] sp = origin.split(" ");     // Split by spaces
        String rep = origin.replace("big", "small"); // Replace word
        String sub = origin.substring(5, 10);   // Extract substring [5,10)
        boolean eq = origin.equals("This is a big question");  // String equality comparison
        boolean ct = origin.contains("question");   // Check if contains substring
        boolean sw = origin.startsWith("This");  // Check if starts with specified text
        String  cat = origin.concat("Hello"); // String concatenation
    }
}
```

```python

                name = 'Alice'
if name == 'funny':
    pass
```

String concatenation

```java

                import java.io.UnsupportedEncodingException;

public class Hello {

    public static void main(String[] args) {
        // "name=alice&age=29"
        StringBuilder sb = new StringBuilder();  // StringBuffer is thread-safe, StringBuilder is faster
        sb.append("name");
        sb.append("=");
        sb.append("alice");
        sb.append("&");
        sb.append("age");
        sb.append("=");
        sb.append("19");

        String dataString = sb.toString();

        System.out.println(dataString);
    }
}
```

```python

                data = []
data.append("name")
data.append("=")
data.append("18")
data_string = "".join(data)
```

![](https://support.nullflag.com/wp-content/uploads/2025/09/image-20220127174147151-7625739-1024x261.png)

![](https://support.nullflag.com/wp-content/uploads/2025/09/image-20220127173632438-7625739-1024x257.png)

![](https://support.nullflag.com/wp-content/uploads/2025/09/image-20220127173906405-7625739-1024x311.png)

### Array

Stores a fixed number of elements.

- It is a container — it can hold multiple items.
- Fixed length: once created, the size cannot be changed.
- Specific type: all elements must be of the same data type.

```java

                import java.util.Arrays;

public class Hello {
    public static void main(String[] args) {

        // Example 1: Create an int array with fixed length
        int[] numArray = new int[3]; // create a new int array of length 3
        numArray[0] = 123;   // assign value
        numArray[1] = 1;     // assign value
        numArray[2] = 999;   // assign value

        // Print array contents
        System.out.println(Arrays.toString(numArray));  // Output: [123, 1, 999]

        // Example 2: Create a String array with initialization
        String[] names = new String[]{"NingKong", "Alex", "Eric"};
        System.out.println(Arrays.toString(names));  // Output: [NingKong, Alex, Eric]

        // Example 3: Simpler way to create a String array
        String[] nameArray = {"NingKong", "Alex", "Eric"};
        System.out.println(Arrays.toString(nameArray));

        // Access elements
        System.out.println(nameArray[0]);   // Output: NingKong
        System.out.println(nameArray.length); // Output: 3

        // Loop through the array
        for (int idx = 0; idx < nameArray.length; idx++) {
            String item = nameArray[idx];
            System.out.println("Element at index " + idx + ": " + item);
        }
    }
}
```

Note: Once an array is created, its size cannot be changed. (In Java, arrays are of fixed length.)

In other languages, there are mechanisms for dynamic resizing, reallocation, and migration of data. For example, in Java, Python, and Go, developers often need to understand how arrays (or array-like structures) work in order to handle expansion and dynamic data growth properly.

### About Object

```javascript

                In Python, every class implicitly inherits from the object class. That means all classes are subclasses of object.

In Java, all classes also implicitly inherit from the Object class.

int v1 = 123;
String name = "NingKong";

A base class (or parent class) can be used to represent the type of its subclasses.

In other words, a parent class reference can point to an instance of a subclass.

This concept allows polymorphism,
making it possible to write code that can handle objects of many different types in a uniform way,
as long as they share the same parent.
```

```java

                import sun.lwawt.macosx.CSystemTray;

import java.util.Arrays;

public class Hello {

    public static void main(String[] args) {
        // String v1 = "wupeiqi";
        Object v1 = new String("NingKong");
        System.out.println(v1);
        System.out.println(v1.getClass());

        Object v2 = 123;
        System.out.println(v2);
        System.out.println(v2.getClass());
    }
}
```

```java

                In Java, all types inherit from the Object class.
That means a parent class reference (Object) can point to a child class object (like String or Integer).

public class Main {
    public static void main(String[] args) {
        int v1 = 123;
        Object v10 = 123;   // auto-boxed into Integer, stored as Object

        String v2 = new String("root");
        v2.trim();          // String-specific method

        Object v3 = new String("root");
        v3.hashCode();      // can only call methods from Object

        // Cast Object back to String
        String v4 = (String) v3;
        v4.trim();          // now we can call String-specific methods
    }
}

All classes in Java extend Object.

A variable declared as Object can store any object, but you can only use methods defined in Object (like hashCode(), toString(), equals() …).

To use child-class-specific methods (e.g., String.trim()), you must cast the Object reference back to its actual type.
```

```java

                import sun.lwawt.macosx.CSystemTray;   // (not needed here, can be removed)

import java.util.Arrays;

public class Hello {

    public static void main(String[] args) {
        // Declare an array: elements must be of type int
        int[] v1 = new int[3];

        // Declare an array: elements must be of type String
        String[] v2 = new String[3];

        // Declare an array: elements can be of type int/String (any Object)
        Object[] v3 = new Object[3];
        v3[0] = 123;        // autoboxed into Integer
        v3[1] = "NingKong";  // String
    }
}
```

So, if you want to declare an array that can hold mixed types, you can use Object in Java.

```java

                import java.util.Arrays;

public class Hello {

    public static void main(String[] args) {
        // v1 is explicitly a String object
        String v1 = new String("NingKong");
        String res = v1.toUpperCase();
        System.out.println(res);   // Output: NINGKONG

        // v2 is stored as Object, but its actual type is String
        Object v2 = new String("NingKong");
        String data = (String) v2;   // cast back to String
        System.out.println(data.toUpperCase());  // Output: NINGKONG
    }
}
```

```java

                import java.util.Arrays;

public class Hello {

    public static void func(Object v1) {
        // System.out.println(v1);
        // System.out.println(v1.getClass());  // check the runtime class
        // v1 instanceof Integer  // check specific type

        if (v1 instanceof Integer) {
            System.out.println("Integer type");
        } else if (v1 instanceof String) {
            System.out.println("String type");
        } else {
            System.out.println("Unknown type");
        }
    }

    public static void main(String[] args) {
        func(123);      // prints: Integer type
        func("123");    // prints: String type

        // Object array with mixed types
        Object[] data = new Object[]{"root", "alex", 123};

        // Force cast from Object to String
        String v2 = (String) data[0];
        System.out.println(v2);    // Output: root

        // Inspect actual runtime type
        Object v3 = data[0];
        System.out.println(v3.getClass().toString()); // Output: class java.lang.String
    }
}
```

- In Java, all classes inherit from Object, and Object represents all types.
- “Create relationships by yourself”

![](https://support.nullflag.com/wp-content/uploads/2025/09/image-20220127224643681-7625739-1024x296.png)

```java

                ArrayList v1 = new ArrayList();
LinkedList v2 = new LinkedList();
```

```java

                List v1 = new ArrayList();
List v2 = new LinkedList();
```

```java

                Object v1 = new ArrayList();
Object v2 = new LinkedList();
```

```java

                class Base {   // Methods in parent and child classes can be adapted and called
    public void f2() {
        System.out.println("Base--F2");
    }
}

class Dog extends Base {
    @Override
    public void f2() {
        System.out.println("Dog");
    }
}

class Cat extends Base {
    @Override
    public void f2() {
        System.out.println("Cat");
    }
}

public class Hello {
    // Base here is a generic reference for its subclasses.
    // The argument could be a Dog, or a Cat, or any other subclass of Base.
    public static void showInfo(Base obj) {
        obj.f2();  // Calls the subclass's version of f2 (polymorphism)
    }

    public static void main(String[] args) {
        Base v1 = new Base();
        showInfo(v1);   // Output: Base--F2

        Dog d = new Dog();
        showInfo(d);    // Output: Dog

        Cat c = new Cat();
        showInfo(c);    // Output: Cat
    }
}
```
