Java review
I'm going to use Java for the first time in a while, so I've summarized what I reviewed as a memorandum. It would be helpful if you could point out any mistakes ...
Java overview
--Developed by Sun Microsystems in the early 1990s
--Sun Microsystems was acquired by Oracle in 2010
--The catch phrase is "Write Once, Run Anywhere"
- ** The compiler ** converts the source code
.java
file to bytecode .class
, and ** JVM ** interprets and executes the bytecode.
--Initially, the version was 1. *, but now it is represented by an integer such as 6, 7, and 8.
- 1.0 -> 1.1 -> 2.0 -> 1.3 -> 1.4 -> 5.0 -> 6 -> 7(GAE) -> 8(AWS Lambda)
Object-orientation
- Replace the actual movement of things with the program as it is
- Reduces the impact on existing code when adding features
--Java code consists of classes, and classes consist of states (instance variables) and functions (methods).
- Create an instance from a class
- Methods are common to instances, instance variables are unique
- Passing data to the method (argument) by value
- Methods can be overloaded (different arguments with the same method name)
- Instance variables have default values (not local variables)
- Prevent unauthorized manipulation of instance variables
- Declare the instance variable with
private
, and operate the instance from the getter method and setter method declared with public
.
--Inheritance
- Inherit when a class has an IS-A relationship
- Cat is an Animal.
class Cat extends Animal {}
--There is a Has-A relationship as something similar
- Since inheritance is one-way, superclass methods can be used from subclasses, but not the other way around.
- Override allows superclass methods to be overridden
- merit
--DRY: Inheritance can be deduplicated by using a common method in a superclass from multiple subclasses.
--Polymorphism: Subclass assignment is possible by specifying a superclass as the type when declaring method arguments and variables.
--Even if you add a new subclass, it will be available without modifying the corresponding code.
- Precautions when using inheritance-Subclasses should be more specific than superclasses
--Superclasses that do not need to be instantiated should be abstracted with ʻabstract
--If you want to force a subclass to implement logic, use ʻabstract
to make it an abstract method.
- In this case, it needs to be an abstract class
--Do not use for the purpose of reusing methods, use when IS-A relationship occurs
--The superclass is called first, the subclass constructor is called later, and the order cannot be changed.
--Java prohibits multiple inheritance that inherits more than one class
- If multiple inherited superclasses have the same method name, the question of which one to prioritize
- However, multiple implementations of the interface are possible
- ʻObject` is a superclass of all classes
--Has equals, hashCode, getClass, toString as methods
--These can be overwritten, especially when comparing objects (equals, hashCode) and debugging (toString).
- Complete abstract classes, all methods become abstract methods
- Used to add common functions to multiple classes in inheritance relationship (IS-A relationship)
- ArrayList and HashSet classes have no inheritance relationship, but both implement an Iterable interface that allows repeated access to elements.
- Specifying an interface as a method argument or return type allows assignment of an instance of the class to be implemented.
variable
- Variables can be divided into primitive types (int, double, boolean) and reference types
- Reference type variables store references to objects in the heap area
- Arrays containing primitive types (int [], etc.) are also reference type variables
- Be careful when comparing, "==" for primitive types, "equals" for reference types ("==" if you want to know if they are the same object reference))
- Variables can be cast (type conversion)
--Cast from int to double is possible
--Double to int use Math library to specify decimal handling
- Primitive types have a corresponding wrapper object
--Integer object for int type
--Because you can specify an object in the generics, ʻArrayList
will result in a compile error and ʻArrayList <Integer>
will result in the correct type declaration.
--Automatically convert wrapper object <-> primitive types
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1); //Insert int type data
int i = list.get(o); //Receive as an int type variable
- Has invariance of String
--Every time you concatenate strings in a loop, a new object is created in the String pool
--It has been pointed out that the overhead of creating objects and the problem that the String pool is not garbage collected.
--Concatenation with StringBuffer / StringBuilder # append is recommended
Access level
- There are Public, Private, Default, Protected
- Commonly used are Public and Private
- Public: Available from any code
- Private: Only available from your class
- Default: Only available from your own package class
- Protected: Available from subclasses of other packages in addition to the class of your own package
Garbage collection
- The memory area used by Java is divided into a stack and a heap.
- Methods and local variables (variables declared within methods) are stored on the stack
--Added to the stack when a method calls a new method
--Get off the stack when the method returns a return value
- Objects are stored in the heap
- Objects are subject to garbage collection when all references are gone
static
- Static methods do not require an instance (eg Math class methods)
- If you create a class with the constructor set to
private
, you will not be able to create an instance.
- In static methods, instance variables and normal methods cannot be used, but static variables can be used.
--Static variables are variables that have the same value in all instances of the class
--Constants can be defined with
static final
exception
- Raise an exception to inform the user of the method that the method could not be completed successfully under certain conditions
- All exceptions are class objects that inherit from the Exception type
- RuntimeException is caused by a flaw in the logic of the program rather than by an unexpected situation.
--NumberFormatException in Integer # parseInt is due to the fact that the argument string is not a number, which should be eliminated in the logic before calling
--A try / catch block is not required for exceptions that inherit RuntimeException (unchecked exceptions)
- Polymorphism: If you specify Exception for catch, you will receive all exceptions.
try {} catch(Exception e) {}
--Not recommended, but effective because it is convenient for test code etc.
- The order of the catch statements is important and the subclass should be written above
try {
} catch(Cat e) {
} catch(Animal e) {
- If you do not handle exceptions, you can avoid it by specifying throws when declaring the method.
IO
- FileWriter's write method accesses the disk every time it is executed, resulting in poor performance.
- When writing with BufferedWriter, a certain amount of memory is stored, and when the capacity is full, writing is performed, so disk access decreases.
--Use flush () to force a write
- Use BufferedReader to read
thread
- Divide the CPU in time to make multiple processes appear to be parallel at the same time
- To start a thread, create an object of a class that implements Runnable interface.
- There are three thread states: executable, block (Sleep, IO), and running.
--Each state is managed and determined by the thread scheduler.
- Problems occur when multiple threads access the same object
--Locking to object access can be done by attaching synchronized method to only one thread to access at the same time.
--Be careful of deadlock when using
data structure
-
SET: Used when it is important that there are no duplicate elements
- HashSet, TreeSet
--Duplicates using hashCode () and equals (), so override if necessary
-
List: Used when the arrangement of elements is important
- ArrayList, LinkedList
--You can sort with Collections.sort
-
Map: Used when you want to find an element by key
-
Polymorphism
--Note the difference between the following two
--When assigning a collection whose elements are instances of a superclass
public void barkAll(ArrayList<Animal> user) {}
--When assigning a collection whose elements are subclass instances (using wildcards)
public void barkAll(ArrayList<? extends Animal> user) {}
Package and JAR
- Make classes with the same name available by separating the classes into packages
- Package name is customarily the reverse of the domain
- Class files can be organized in JAR
--You can create an executable JAR file by specifying Main-Class in Manifest.txt.