I take notes here as I learn Java SE. Some of these are really, really basic, while some are more advanced.

Fragmented Content

This post content may appear fragmented or disjointed for I only noted down things I think I need to look at a second time. This post is primarily meant for personal consumption, but some snippets might interest you.

About Java

  • History of Java
  • When Java developed from v1.1 to v1.2, the changes were great so they named it as Java 2; when it went from 1.4 to 1.5, they believed that this is another significant version so named it as Java 5. So, Java 2 refers to 1.2 to 1.4; Java 5 is 1.5; there is no Java 3 or 4.
  • The first Java version is Java 1.02.

Value Types

  • int cannot be used directly as boolean value; that is, while(1) is wrong (You cannot do that in C#, either; is this only allowed in C?).
  • Boolean value has its class name as boolean (it is bool in C#).
  • A byte value has 1 byte, a char and a short value have 2 bytes, int float 4 bytes, and long double 8 bytes (the same as C#).
  • Like other numerical type, byte is signed. It represents -128 to 127 (but byte is unsigned in C#, representing 0 to 255, which is quite an exception).
    • You can check the max and min value of each numeric type using the MIN_VALUE and MAX_VALUE of their wrapper classes (java.lang.Byte,java.lang.Character etc.).

Reference Types

  • We do not know how large a reference type variable is, or how it is implemented; indeed this varies from VM to VM - but on the same VM all reference types should have the same size.
  • We cannot perform calculation on reference types (unlike in C).
  • Array is a reference type - but do not think of array as a pointer to its first element (unlike in C).
  • Java also have a Garbage Collector that can recycle memory occupied by objects without any reference (C# does the same; in C, if you lose track of an object, you have what is known as a ‘memory leak’. The memory will still be allocated to the program as a whole, but nothing will be able to use it if you’ve lost the last pointer to it.)
  • Java is always pass-by-value, exactly as in C.
    • Passing an object in and out is really passing its reference (or pointer, or handle, or any term you like) in and out. This is not called pass-by-reference; we should say object references are passed by value.
    • == compares values. When == is used on reference type it compares whether the two reference handles (Hash codes) are the same. Use equals() to compare reference types. You cannot overload operators in Java, either.

Conversion

  • Conversion of primitive types
  • Boxing and Unboxing

Naming Rules

  • Follows basically the same naming rules in other language for your variables and functions in Java - but you can starts with $ as well.
  • Do not capitalize the first letter for Java methods (unlike in C#) - use Camel Case instead.
  • Why some packages starts with javax instead of java?

Flow Control

  • foreach in Java looks like this: for (TYPE name: nameArray) {}. Just replace the in in C# with :.
  • All conditional statements (if,switch,:?) have the same syntax for Java and C#.

Inheritance

  • Method overriding is marked by @override; when overriding, the method is child classes cannot have an more public access modifier than do in the parent class.
  • Object class has 4 methods: hashCode(), getClass() , equals() and toString() - you should override at least the last two.
  • Super() and This()
    • If the child constructor does not call super() (with parameter or parameterless) in the first line, the compiler will add this line to call the default parameterless super().
      • Calling the constructor of a child class will cause: child constructor method enters the call stack -> parent constructor method enters the call stack -> parent constructor method is executed -> child constructor method is executed.
      • If the parent class does not have a parameterless constructor, and if we do not specify any super() with parameters in the first line of child constructor, we get an error (This is true for C# as well).
      • As an alternative, you can call another constructor of the same class by putting this() at the first line. You cannot do both this() and super(). (In C#, this is much easier - all inheritance are marked with : - you also do not need to worry about the first line.)
  • Declare the constructor to be private for static classes to prevent an object from being initialized.

Nested Class

  • Static nested class
  • Internal class

Compilation

  • Without IDE: save your source file as “.java”; compile it with javac <file-name> command in CMD; run the compiled file with java <file-name> command.
    • Use -encoding UTF-8 to switch encoding method to UTF-8.
  • Source files:
    • A source file can contain only one public class and many non-public class. The name of the source file should be the same as that of that public class.
    • package statement should be the first row in a source file, if any; followed by import statement, if any. These two statement apply to all classes in the source file.

Memory Allocation

  • Static variables and Member variables (instance variables) are initialized with their default value (same as in C#), local variables are filled with garbage values and cannot be used without initialization.
  • You can limit the lifetime and scope of a local variable to just a block by surrounding a snippet of codes with {} (this is why local variables in for and if block is not accessible outside the block).
    • Nested block: All the variables of the outer block are accessible by the inner block but the variables within inner block are not accessible by the outer block.
  • JRE classes live on heap.

Execution Order

  • Static variables are initialized once before the first call of the static method / constructor of the same class.
  • Static initializers are run once when the class is loaded, before the Main() is called.
    • Overall order: parent class static block -> child class static block -> main starts -> parent constructor -> child constructor
    • All classes, including non-static ones, can have static variables and static blocks.
    • Cannot pass in our out anything, cannot use this() or super() in a static initializer.
    • Why bother using a static initializer? Check this.
  • Non-static initializers are executed when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super() constructor.

Keywords and Operators

  • Variables marked with final must be initialized when declaring or in a static initializer - they cannot be initialized in a non-static initializer.
  • A variable marked final means its value cannot be changed once initialized; a method marked final cannot be overridden; a class marked final cannot be inherited. Do not need to mark all methods of a final class as final - it cannot be inherited in the first place.
  • instanceof operator: <object> instanceof <class/interface> returns true iff there is any is-a relationship (the object is an instance of the class, its subclass, or a class that extends the interface). The object must not be a primitive type. Always use instanceof operator before down-casting.
  • Access modifier: protected is more public that the default access because it allows both in-package access and out-of-package access through inheritance.
  • assert keyword: when the program runs to an assertion like assert (boolean expression); the boolean expression should always be true; or else, an AssertionError would be thrown.
    • You could include some information for an assertion too: assert (boolean expression):"info";.
    • This is for the dev/debug/test parts of the cycle, not for production.
    • To enable the assert when running, use java -ea <file-name>.

Syntactic Sugar

Exception Handling

  • finally block will run, even if there is a return in try or catch block.
  • There can be 0 or many catch blocks.
    • If there is no catch block, a finally must follow the try block. In this case, the exception is still unhandled, and a throws must be used to delegate the exception.
    • If there are many catch blocks, the most specific exception type must be at the front.
  • In Java, all checked exception must be handled(with a try-catch block).

Numeric literals

  • 0b prefix for binary, 0 prefix for octal, and 0x for hexadecimal numbers.
  • A literal integer has int type; a literal decimal number has double type (suffix it with f to declare it as float).

String, StringBuilder

Enumeration

  • Each enum inherits from java.lang.Enum (in C#, each enum inherits from one of the integer numeric type.) Every enum constant represents an object, or a derived class of type enum.
    • You can have constructors and methods in enum declaration, as it is essentially a class.
    • When specifying enum constant, you can pass in parameters needed for its constructors (think of each enum constant as an object of the class); you can also override methods (think of each enum constant as a derived class of the class).

Untested Codes

This snippet of codes has not been tested yet and are thus for illustration of concepts only.

public enum Weekdays{
  Monday(1),
  Tuesday(2),
  Wednesday(3),
  Thursday(4),
  Friday(5) { public void shout() { System.out.println("Yeah, weekend coming!")}};

  int index;

  Weekdays(int dayIndex){
    this.index = dayIndex;
  }

  public void shout(){
    System.out.println("I'm %s whose index is %d.",this,this.index);
  }
}

public static void Main(String[] args){
  for(Weekdays day : Weekdays.values()){
    day.shout();
  }
}
//Output: 
//I am Monday whose index is 1.
//I am Tuesday whose index is 2.
//I am Wednesday whose index is 3.
//I am Thursday whose index is 4.
//Yeah, weekend coming!

Collections and Generics

Functional Programming

  • Use -> instead of the => in C#.

Reflection

Date, Time

I18N

Mathematics

Regular Expression

IO

XML and JSON

Database (JDBC)

Encryption

Threading

Networks

GUI (Swing)

RMI

Project Management (Maven)

Unit Test (JUnit)

Reference