首页 > 代码库 > [Java Basics] Stack, Heap, Constructor

[Java Basics] Stack, Heap, Constructor

Good about Java:

friendly syntax, memory management[GC can collect unreferenced memory resources], object-oriented features, portability.

Stack

Stores method invocations, local variables(include object reference, but the object itself is still stored in heap).

If you look at the stack trace, the top method is the one being called, and once it is finished, it will be removed out of the stack.

Heap

Stores all objects(include instance variables in the class).

.hashcode() returns the memory address of the object, so no same hashcode for two objects.

But when the Class is value object, you could override .hashcode() and .equals().

Constructor

Default parameterless constructor: only generated by compiler when there is no your constructor.

Parent constructor: if parent class has default constructor, compiler will automatically call it without .super(). But if not, or you want to call the parent constructor with parameters, you need to call .super() explicitly.

Overloaded constructor: use .this(...) at the first line. 

File I/O

There are two streams: Character stream & Binary stream

Character stream: 

to read/write human readable files, like .txt .xml .html

Class: FileReader/Writer, more advanced: BufferedReader/Writer

Binary stream: 

to read/write machine readable files, like .exe .class .obj

Class: FileInput/OutputStream, more advanced for Object: ObjectInput/OutpoutStream(.writeObject() method).

Immutable Class

Instance could not be modified.

How to: private final fields, final class, no setter methods, ensure exlusive access to mutable components.