Sean's Blog

心之所向,身之所往。

Back to Java Fundamentals

1. Types

Type Size (Bits) Default Value Range Example
byte 8 0 -128 to 127 byte b = 10;
short 16 0 -32,768 to 32,767 short s = 100;
int 32 0 -2,147,483,648 to 2,147,483,647 int i = 12345;
long 64 0L -2^63 to (2^63)-1 long l = 123456L;
float 32 0.0f ~7 decimal digits float f = 3.14f;
double 64 0.0d ~16 decimal digits double d = 3.14;
char 16 ‘\u0000’ 0 to 65,535 (Unicode) char c = 'A';
boolean 1 bit (logical) false true or false boolean b = true;

1.1 Common Errors and Pitfalls

Numeric Overflow

  • Cause: Exceeding the range of a numeric type.
  • Example:
    byte b = 127;
    b++; // Wraps to -128
    

Uninitialized Variables

  • Cause: Using a local variable without initializing it.
  • Example:
    int x;
    System.out.println(x); // Compilation Error
    

Missing Type Parameters

  • Cause: Not specifying type parameters in generics, leading to runtime issues.
  • Example:
    List list = new ArrayList(); // Raw type, can cause ClassCastException
    list.add(123);
    String str = (String) list.get(0); // Fails at runtime
    

1.2 String

public class Test {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = new String("Hello");

        System.out.println(s1 == s2); // true
        System.out.println(s1 == s3); // false
    }
}
  1. s1 == s2:
    • Both s1 and s2 reference the same string literal “Hello”, which is stored in the string pool.
    • Since both variables point to the same object in memory, s1 == s2 evaluates to true.
  2. s1 == s3:
    • s3 is created with the new keyword, which creates a new object in memory, even though it has the same content as s1.
    • Since s1 and s3 refer to different objects, s1 == s3 evaluates to false.

1.3 Integer

Use equals to compare whether objects are logically equal - two numbers has the same value in this case.


How to invoke a method in the jar?

We can use URLClassLoader to load classes from a given path.

      URL myJar = new File("jar/LibraryA-1.0-SNAPSHOT.jar").toURI().toURL();
      URLClassLoader clsLoader = new URLClassLoader(
              new URL[] {myJar},
              this.getClass().getClassLoader()
      );
      Class<?> loadedClass = clsLoader.loadClass("com.sean.liba.Main");
      Method method = loadedClass.getDeclaredMethod("print");
      Object instance = loadedClass.newInstance();
      method.invoke(instance);

      // Output: Hello World!

Let’s look at other use cases. What if you have two jars, and liba.jar deppends on another class in the libb.jar?

Take the above example, the print method has a dependency on the com.sean.libb.Caculator class. If we dont’t change the code, and run it again, you will get an error immediately.