Java Collections


Garbage collection
- Reference Counting vs Reachability Chain
- Mark and Copy vs Copying
- Young Generation vs Old Generation
- There are four kinds of GC roots in Java:
Local variables are kept alive by the stack of a thread. This is not a real object virtual reference and thus is not visible. For all intents and purposes, local variables are GC roots. Active Java threads are always considered live objects and are therefore GC roots. This is especially important for thread local variables. Static variables are referenced by their classes. This fact makes them de facto GC roots. Classes themselves can be garbage-collected, which would remove all referenced static variables. This is of special importance when we use application servers, OSGi containers or class loaders in general. We will discuss the related problems in the Problem Patterns section. JNI References are Java objects that the native code has created as part of a JNI call. Objects thus created are treated specially because the JVM does not know if it is being referenced by the native code or not. Such objects represent a very special form of GC root, which we will examine in more detail in the Problem Patterns section below.
JVM Architecture
JVM Memory

- Method area :In method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource.
- Heap area :Information of all objects is stored in heap area. There is also one Heap Area per JVM. It is also a shared resource.
- Stack area :For every thread, JVM create one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which store methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminate, it’s run-time stack will be destroyed by JVM. It is not a shared resource.
- PC Registers :Store address of current execution instruction of a thread. Obviously each thread has separate PC Registers.
- Native method stacks :For every thread, separate native stack is created. It stores native method information.
Out Of Memory vs Stack Overflow
Process of compile and run 运行期环境代表着Java平台,开发人员编写Java代码(.java文件)(source code),然后将之编译成字节码(.class文件)(byte code),再然后字节码被装入内存,一旦字节码进入虚拟机,它就会被解释器解释执行
Three Pillar of OOP
Polymorphism:
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Encapsulation:
It’s a protective barrier that keeps the data and code safe within the class itself.
Benefit: The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our code.
Abstraction:
It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves the maintainability of the system.
Inheritance
create new classes that share some of the attributes of existing classes. It is the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
Limitation: since inheritance inherits everything from the super class and interface, it may make the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation.
Thread
- sleep, yield, wait
- yield -- ready state
- sleep -- waiting state
- The code
sleep(2000)puts thread aside for exactly two seconds. The codewait2000, causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify or notifyAll call. The method wait is defined in the class Object and the method sleep is defined in the class Thread.
- Implement Multithread: Class Thread vs Runnable When you implements Runnable , you can save a space for your class to extend any other class in future or now. Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.
- Callable vs Runnable
- Runnable from Java 1.0 does not return a result and cannot throw a checked exception.
- Callable from Java 1.5 to handle user's cases
Synchronized, lock, reentrantLock
-
Two important features of locks and synchronization.
- Mutual Exclusion: It means that only one thread or process can execute a block of code (critical section) at a time.
- Visibility: It means that changes made by one thread to shared data are visible to other threads. Java’s synchronized keyword guarantees both mutual exclusion and visibility. If we make the blocks of threads that modifies the value of shared variable synchronized only one thread can enter the block and changes made by it will be reflected in the main memory. All other thread trying to enter the block at the same time will be blocked and put to sleep. In some cases we may only desire the visibility and not atomicity. Use of synchronized in such situation is an overkill and may cause scalability problems. Here volatile comes to the rescue. Volatile variables have the visibility features of synchronized but not the atomicity features. The values of volatile variable will never be cached and all writes and reads will be done to and from the main memory. However, use of volatile is limited to very restricted set of cases as most of the times atomicity is desired. For example a simple increment statement such as x = x + 1; or x++ seems to be a single operation but is s really a compound read-modify-write sequence of operations that must execute atomically.
Thread Pool
ways Thread can enter waiting state
- sleep() or wait()
- I/O blocking
- unsuccessful to acquire object's lock
- Thread's
start()vsrun()
Afterstart(),run()will be invoked by JVM when the thread is initially executed. - BlockingQueue vs Semaphore
Reference vs Value
- equals vs ==
- Shallow comparison : use
==checks two Object references - Deep Comparison: check Object's data members
- Shallow comparison : use
- HashCode vs equals: Collections such as HashMap and HashSet use the hashcode value of an object to determine how the object should be stored in the collection, and the hashcode is used again to help locate the object in the collection.
Hashing retrieval is a two-step process.- Find the right bucket (using hashCode())
- Search the bucket for the right element (using equals())
- instanceof Vs getClass( )
- instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.
- getClass() == ... tests whether the types are identical.
deep copy vs shallow copy

immutable vs mutable
- Immutable means that once the constructor for an object has completed execution that instance can't be altered
- Especially when dealing with concurrency, there are no locking issues with objects that never change
- String is immutable it can safely be shared between many threads ,which is considered very important for multithreaded programming.
- Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
- Make all fields final and private.
- Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
Exception vs Error
- Error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error.
- Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.

- try catch finally
- It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block or a finally block.
checked or unchecked
Unchecked: It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. eg. Error, Runtime Exception, NullPointerException
Checked: It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. 3. Exception Order(what order catch statements for FileNotFoundException and IOException)eg. IOException The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
- throw vs throws
- throws: method might throw one of the listed type exceptions keyword. only for checked exception. Without throws, Checked exception cannot be handled where as checked exception can be propagated with throws.
- throw: explicitly throw an custom exception from a method or any block of code. either checked or unchecked.
Keywords
- final, finally and finalize
- finalize: The garbage collector invokes an object's finalize method when it detects that the object has become unreachable.
- final
- final class: Final classes are created so the methods implemented by that class cannot be overridden. It can’t be inherited.
- Final variables: we cannot change the value of a final variable once assigned
- Final Method: A final method cannot be overridden
- HashMap & HashTable & ConcurrentHashMap
ConcurrentHashMap uses multiple buckets to store data. This avoids read locks and greatly improves performance over a HashTable, both are thread safe. - Array vs Arrays
- Array class provides static methods to dynamically create and access Java arrays.
- Arrays contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.
- Collection vs Collections
- Collection是java.util下的Interface,它是各种集合结构的父接口,继承于它的接口的主要有set和List,提供关于集合的一些操作,比如插入、删除、判断一个元素是否是其成员,遍历等。
- Collections是java.utis下的类,是针对集合类的一个工具类,提供一系列静态方法,实现对集合的查找、排序、替换、线程v安全(将非同步的集合转换成同步的)等操作。
- Interface vs Abstract Class
- Interfaces are rules (rules because you must give an implementation to them that you can't ignore or avoid, so that they are imposed like rules)
- Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules (means given signature of methods).
- Abstract classes may contain abstract declarations, concrete implementations, or both
- Abstract declarations are like rules to be followed and concrete implementations are like guidelines (you can use it as it is or you can ignore it by overriding and giving your own implementation to it).
- Using abstract classes if any of these statements apply to your situation:
- In java application, there are some related classes that need to share some lines of code then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
- You can define non-static or non-final field(s) in abstract class, so that via a method you can access and modify the state of Object to which they belong.
- You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- Using interfaces if any of these statements apply to your situation:
- It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
- A class can implement more than one interface. It is called multiple inheritance.
- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
- Static vs Nonstatic
- Static Block: It is used to initialize the static data member, It is excuted before main method at the time of classloading.
- Static Variables: go in a particular pool in JVM memory called Metaspace
- Since static variables belong to a class, they can be accessed directly using class name and don’t need any object reference
- static variables can only be declared at the class level
- static fields can be accessed without object initialization
- Static Method:To access/manipulate static variables and other static methods that don’t depend upon objects and static methods are widely used in utility and helper classes
- static methods in Java are resolved at compile time. Since method overriding is part of Runtime Polymorphism, so static methods can’t be overridden
- abstract methods can’t be static
- static methods cannot use this or super keywords
- The following combinations of the instance, class methods and variables are valid:
- Instance methods can directly access both instance methods and instance variables
- Instance methods can also access static variables and static methods directly
- static methods can access all static variables and other static methods
- static methods cannot access instance variables and instance methods directly; they need some object reference to do so
- Static Class:?? Singleton be helped??
- static nested classes do not have access to any member of the enclosing outer class; it can only access them through an object’s reference
- Java programming specification doesn’t allow us to declare the top-level class as static; only classes within the classes (nested classes) can be made as static
- Inner Class vs Nested Class
- When a class is defined within a scope of another class, then it becomes inner class.
- If the access modifier of the inner class is static, then it becomes nested class.
Java vs C++
Comparator vs Comparable
- Comparator provides a way for you to provide custom comparison logic for types that you have no control over.
- Comparable allows you to specify how objects that you are implementing get compared.
- Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use
Comparator. - Otherwise you can use
Comparable.
- public static void main(String[] args)
- public − it is the access specifier.
- static − it allows main to be called without instantiating a particular instance of a class.
- void − it affirns the compiler that no value is returned by main.
- main − this method is called at the beginning of a Java program.
- String args[ ] − args parameter is an instance array of class String
- JIT compiler(Just In Time Compiler) JIT compiles the bytecode of that method into native machine code, compiling it "just in time" to run
- Unicode, ASCII, UTF-16 and UTF-8
- Unicode -- 16 bits
- ASCII -- 7/8 bits
- UTF-16 -- 16 bits or large bit pattern
- UTF-8 -- 8/16/18 bits
- Serialization or Deserialization
- state of an object --> a byte stream
- restoring these objects
- >> vs >>>
- The >> operator carries the sign bit when shifting right.
- The >>> zero-fills bits that have been shifted out.
- Iterator vs Enumration Enumeration and Iterator are two interfaces in java.util package which are used to traverse over the elements of a Collection object. ... But using Iterator, you can also remove an element while traversing the Collection.
- Autoboxing vs Unboxing Two situation will trigger compiler applies
- Passed as a parameter to a method that expects a value of the corresponding XX type
- Assigned to a variable of the corresponding XX type.