Java Basic Learning Note
1. Java Synax
1.1 Data Type
1.1.1 Java Integer Types
Type | Storage |
---|---|
Int | 4 bytes |
long | 8 bytes |
short | 2 bytes |
byte | 1 byte |
1.1.2 Floating-Point Type
Type | Storage |
---|---|
float | 4 bytes |
double | 8 bytes |
Usage scenoria: (1) the library required (2) store a very large number floating-type value
Error: (1) Postive infinity (2) negative infinity (3) NaN: not a number (0/0, or like square root(-5))
1.1.3 Char Type
Now, Char type can present Unicode characters, and the value of Char type can be expressed as hex values(From \u0000-\uFFFF).
1.1.4 Boolen Type
Logical Value: (1) True (2)False(default)
1.1.5 String
(1) Initialization
String e = ""; // an empty string
String e = "Hello";
(2) SubString
String s = e.substring(0, 3);
(3) Concatenation
String expletive = "Expletive";
String PG13 = "deleted";
String message = expletive + PG13;
int age = 13;
String rate = "PG" + age;
//"PG13"
use “+” to concatenate two strings.
Join Method
join(CharSequence delimiter, CharSequence... elements)
String all = String.join(" / ", "S", "M", "L", "XL");
//"S / M / L / XL"
Repeat
string.repeat(count);
String repeated = "Java".repeat(3);
//"JavaJavaJava"
(4) Length And code point
get Length
s.length()
String greeting = "Hello";
int n = greeting.length();
get code unit at poisition n
s.charAt(n)
char first = greeting.charAt(0);
// first is 'H'
n between 0-string.length
(5) Build Strings
use StringBuilder to create String
StringBuilder builder = new StringBuilder();
builder.append(ch); // appends a single character
builder.append(str); // appends a string
1.1.6 Array
(1) Declare Array
// declare integer variable array
int [] a;
//initialize: int[n] means the length of the array is n
int [] a = new int[100];
//or
var a =new int[100];
(2) Array elements
int []a = new int[100];
for (int i = 0; i < 100; i++){
a[i] = i;
}
// means filling array with 0-99. eg. a[0]=0. a[1]=1,..., a[99]=99
access array element(a.length)
for (int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
(3) Copy
When use the new variable to copy one array value, actually two variable will refer to one same array.
int[] luckyNumbers = smallPrimes;
luckyNumbers[5] = 12;
// now smallPrimes[5] is also 12
when changing the element value of the copied variable, the original array will change.
Copy a new array
Arrays.copyOf(array, array.length(length you want copy));
you can copy the array with twice(or length you want) the size of the original length, and the additional element will filled with 0. So the array can’t contain the boolean value.
(4) Two - demensional Array
int [][] a = new int[i][j];
1.2 Variable and Constants
1.2.1 Declare and initializing Variables
int a;
a = 12;
//or
int a = 12;
1.2.2 Constants
(1) use final to express Constant
final int a = 12;
constant can use in the multiple methods in the one class (class constant)
(2) use static final
public static final int a = 12;
In order other mehtod in the same class, declear the constant outside the main method
Declare the constant with public, other methods in other classes can use it
1.3 Operator
1.3.1 Arithmetic Operators
public class synax {
public static void main(String[] args){
int a = 3;
int b = 2;
float a_float = 3.0F;
int c,d,e,f,h;
float g;
c = a+b;
d = a-b;
e = a*b;
f = a/b;
g = a_float/b;
h = a%b;
System.out.printf("%d,%d,%d,%d,%f,%d",c,d,e,f,g,h);
}
}
The result is as follows:
(1) when use division(/), if the type of two variables is int, the operator will give the result of integer. if two arguements are floating-point type, it will give float type.
(2) the % means modulus(Integer remainder)
int a = 5;
b = ++a;
c = a++;
1.3.2 Mathematic function:
can use Math class to do operation.
Math.sin
Math.cos
Math.tan
Math.atan
Math.atan2
Math.exp //E^x
Math.log
Math.log10
Math.PI //π
Math.E //e
1.3.3 Convert
int n = 123456789;
float f = n; //f is 1.23456792E8
//or
float n = 3.50
int n_i = (int) n; //n_i = 3
1.3.4 Assignment
x = x+4
=
x += 4
int x =1;
x += 4;
int y = x;
1.3.5 Conditional Operator
x < y ? x : y
? means if the condition is true, then first expression(x), otherwise, the second expression(y)
1.3.6 Switch Expression(case)
String seasonName = switch (seasonCode) {
case 0 -> "Spring";
case 1 -> "Summer";
case 2 -> "Fall";
case 3 -> "Winter";
default -> "???";
};
Multiple Label for each case
int numLetters = switch (seasonName) {
case "Spring", "Summer", "Winter" -> 6;
case "Fall" -> 4;
default -> -1;
};
1.3.7 Logic Operator
Operator | Example | Meaning |
---|---|---|
& | expression1 & expression2 | true only if both expression1 and expression2 are true |
| | expression1 | expression2 | true if either expression1 or expression2 is true |
! | !expression | true if expression is false and vice versa |
&& | expression1 && expression2 | true only if both expression1 and expression2 are true |
|| | expression1|| expression2 | true if either expression1 or expression2 is true |
Short Circuit Logic:
when use the a&&b or a||b to get a value, there may exists short circuit logic: it means only check first expression, ignore the second one.
//short circuit logic(||)
int a = 0;
int b = 0;
if (++a>0 || ++b>0){
System.out.printf("%d,%d",a,b);
}
//short circuit logic(&&)
int a = 0;
int b = 0;
if (++a<0 && ++b>0){
System.out.printf("%d,%d",a,b);
}
else{
System.out.printf("%d,%d\n",a,b);
System.out.println("short circuit logic &&");
}
1.3.8 Bitwise Operation
Firstly, it should transfer the Decimal to Binary
Operator | Effect and Example |
---|---|
&(AND) | when the value of the same position of two argument is both 1, then return 1, otherwise,return 0. Example: 4&5(0100&0101=0100)=4 |
|(OR) | either value of the same position of two argument is 1, then return 1, otherwise,return 0. Example: 4|5(0100|0101=0101)=5 |
^(XOR) | if value of the same position of two argument is same, then return 0, otherwise,return 0. Example: 4^5(0100&0101=0001)=1 |
~(NOT) | if value of the position of the argument is 1, then return 0, otherwise,return 0. Example: ~4(0100->1011), ~5(0101->1010) |
<< (Bit left shift) | From the last left position and left shift all bits towards the left by a certain number of specified bits. Example: 9<<2(0000 1001<<2 = 0010 0100)=36 |
>>(Signed Right Shift) | From the last right position and right shift all bits towards the right by a certain number of specified bits. then fill the right side with sign value. Example: 9>>2(0000 1001>>2 = 0000 0010)=2 Example: -9(9:0000 1001, one’s complement:1111 0110, two’s complement: one’s complement+1 = 1111 0111); -9>>2(1111 0111-> 1111 1101). binary(signed):(1111 1101-> 1111 1100->1000 0011)=-3 |
>>>(Unsigned Right shift) | Logic right left(don’t care the signed number, just right shift all bits and fill 0 in the right) Example: -9(1111 0111)>>>2=in 32-bite(111111111111111111111111111101) |
int a=-9;
int b=9;
int c = a>>2;
int d = a>>>2;
System.out.println(Integer.toBinaryString((c));
System.out.println(Integer.toBinaryString((d));
System.out.println(a>>>2);
System.out.println(a>>>2);
If the value is postive, the >>> and >> have no difference between the result of them.
1.2 Control Flow
1.2.1 If-else
if (condition){
//consequence 1
}
else{
//consequence2
}
int a = 10;
int b = 11;
if(a >= b){
System.out.println("a >= b");
}else{
System.out.println("a < b");
}
If- Else if - Else
int a = 10;
int b = 11;
if(a > b){
System.out.println("a > b");
}
else if(a = b){
System.out.println("a = b");
}
else{
System.out.println("a < b");
}
1.2.2 Switch
Multiple Condition
switch(week){
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("No Else");
break;
}
1.2.3 Loop
1.2.3.1 While
while(Boolean){
}
//when the boolean is true, the statements in the while will be excuted until the boolean is false, the loop will end
// use break to exit the whole loop early.
do{
}
while();
Difference: do-while will excute the statement at least once, but in the while, if the first time the condition is false, then it won’t excute
1.2.3.2 Determinate loops(for)
//example
int sum = 0;
for (int i =1; i <= 10; i++){
sum += i;
}
System.out.println(sum);
// output = 58
For-Each(array, set)
for (variable: collection){
statement
}
int array[] = {7, 8, 9};
for (int arr : array) {
System.out.println(arr);
}
/*
7
8
9
*/
Example
for (int i = 3; i > 0; i--){
System.out.println("Counting down . . . " + i);
}
int j = 3;
while (j > 0) {
System.out.println("Counting down . . . " + j);
j--;
}
1.2.3.3 Stop the loop
(1)Break
Exit the whole loop
for(int i = 0;i < 10;i++){
if(i == 5){
break;
}
}
/*
0
1
2
3
4
*/
(2) Continue
Exit the current statement, back to condition statememt(while loop: back to boolean condition)
for(int i = 0;i < 3;i++){
if(i == 1){
continue;
}
System.out.println(i);
}
}
/*
0
2
*/
(3) Return
use Return to return from the method to the statement that called the method
public void getName() {
return name;
}
2. Ojectives and Classes
2.1 Classes
2.1.1 Definition
A class specifies how objects are made. it’s an abstraction of a series of objects
(1)Encapsulation
Combine the data and behavior in the package and hide the implementation detail
Instance Fields: bits of data in an object
Methods: procedures that operate on the data
(2) Inheritance
Expanding a class to obtain another class
(3) initialization
ClassName: use Camel-Case to name a class:
class ClassName{
//body
}
//create
ClassNmae classname = new ClassName();
(4)object
The behavior of an object is defined by the methods that you can call.
A change in the state of an object must be a consequence of method calls.
(5) Identifying Class
OOP(Object-Oriented Programming):
Identify classes and then add methods to each class.
Method: look for nouns in theproblem analysis. Methods, on the other hand, correspond to verbs
Example:
some of the nouns of order-processing system:Item; Order; Shipping address…
So, the classes may include: Item; Order and so on
2.1.2 Define Class
class ClassName{
field1
field2
...
constructor1
constructor2
...
method1
method2
...
}
Example: Employee
class Employee {
// instance fields
private String name;
private double salary;
private LocalDate hireDay;
// constructor
public Employee(String n, double s, int year, int month, int day){
name = n;
salary = s;
hireDay = LocalDate.of(year, month, day);
}
// a method
public String getName(){
return name;
}
// more methods . . .
}
when use Public Method, it means any method in any class can call this Method
The Private keyword makes sure that the only methods that can access these instance fields are the methods of the Employee class itself. No outside method can read or write to these fields.
(2)Declare Local Variable
use Var(without specifying the type), type provided by inferring from the intial value
Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
=
var harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
the var keyword can only be used with local variables insidemethods. You must always declare the types of parameters and fields.
2.1.3 Constructor
• A constructor has the same name as the class.
• A class can have more than one constructor.
• A constructor can take zero, one, or more parameters.
• A constructor has no return value.
• A constructor is always called with the new operator
use different constructors
class Apple {
//fields
int sum;
String color;
//four different constructor
public Apple(){}
public Apple(int sum){}
public Apple(String color){}
public Apple(int sum,String color){}
}
2.1.4 Overloading
Overloading allow different method with same name, but it should have different parameters list.
The Requirements of Overloading:
(1)name of Methods is same
(2)the list of parameters is different(like: different type of input, different number of input)
(3)only type of return of method is different, can’t meet the requirement of overloading
public int getApple(int num){
return 1;
}
public String getApple(String color){
return "color";
}
2.1.5 Static
use static to declare
2.1.5.1 Static Fields
class Employee{
private static int id;
}
Non-Static
private int id;
2.1.5.2 Static Constant
public class Math {
. . . public static final double PI = 3.14159265358979323846;
. . .
}
2.1.5.3 Static Method
public static int advanceId() {
int r = nextId;
// obtain next available id
nextId++;
return r;
}
2.1.5.4 Main Method
public static void main(String[] args) {
// construct objects here . . .
}
2.2 Inheritance
2.2.1 Subclass
use extends to denote inheritance
Example: define a Manager class (subclass)that inherit from the Employee class(superclass)
public class Manager extends Employee {
//added methods and fields
}
2.2.2 Overriding
inheriate the subclass from the class, and if need to change some methods from the class. then supply a new method to override the superclass method
Example:
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + bonus;
}
(1)Because salary is private field in the superclass, so the subclass can’t access it, it needs to call the method of superclass
(2)Because getslary() also exists in the Manager Class, So use super to get the superclass’s getslary()
Requirement:
(1)The methods of overriding should be same of superclass.(include: type of return value; Method Name; Parameters list)
(2)can use @Override to note
(3)the access permission of the overriding method of subclass can’t lower than methods of superclass
2.2.3 Subclass Constructor
public Manager(String name, double salary, int year, int month, int day)
{
super(name, salary, year, month, day);
bonus = 0;
}
2.2.4 Destruction of objects
In Java, the management and destruction of objects is controlled by JVM(Java virtual machine)
2.2.4.1 Scope of Object
use block{} to define Scope
{
int a = 11;
{
int b = 12;
}
}
variable a is effective in the two block, but b is onlt effective in the it’s own block
but can’t define two variable with same name in difference scope.
{
int x = 11;
{
int x = 12; //error
}
}
2.2.5 This and Super
2.2.5.1 This
this can represent current object and call methods and fields or point to the current object
(1)
Exmaple:
public class Apple {
int i = 0;
Apple eatApple(){
i++;
return this;
}
public static void main(String[] args) {
Apple apple = new Apple();
apple.eatApple().eatApple();
}
}
because return this in the eatApple(), so it is called twice(apple.eatApple().eatApple()😉, it means whatever the object call eatApple(), it can return themself.
(2)Use this in the constructor to modify the properties
public class Apple {
private int num;
public Apple(int num){
this.num = num;
}
public static void main(String[] args) {
new Apple(10);
}
}
In the main method, it gives 10 to the argument. and give the value to the global variable(num), so the num is 10
(3)this(parameters)
It means call other constructors and give it parameters.
Tip:
this() should be the first line of the constructor.
(4)super
a.super.object
it can use super.object to use the members of the superclass
b.super(parameters)
use super() to call constructors of superclass
Difference
Keywords | this | super |
---|---|---|
calls method | call the properities, constructors, methods of current class | call the properities, constructors, methods of superclass |
calls position | the first line of constructor | the first line of constructor |
number of calls | one constructoer can be called only once | one constructoer can be called only once |
2.2.6 access control permissions
2.2.6.1 Encapsulation
four access permission: Public, Protected, default, private
Class | private | default | protected | public |
---|---|---|---|---|
the same class | Yes | Yes | Yes | Yes |
classes in one package | Yes | Yes | Yes | |
subclass | Yes | Yes | ||
classes in other package | Yes | |||
2.2.6.2 Inheritance
Key words: Extend
if subclass doesn’t have it’s own methods, it will use features of superclass.
2.2.6.3 Polymorphism (多态)
Requirement of Polyporphism:
(1)Inheritance
(2)override the methods of superclass
(3)superclass reference points to child class objecta subclass object
public class Fruit {
int num;
public void eat(){
System.out.println("eat Fruit");
}
}
public class Apple extends Fruit{
@Override
public void eat() {
super.num = 10;
System.out.println("eat " + num + " Apple");
}
//main method
public static void main(String[] args) {
Fruit fruit = new Apple();
fruit.eat();
}
}
Fruit fruit = new Apple();
Object of Fruit use the object of Apple, because Apple is inheriated from Fruit.
2.2.6.4 Static
(1)Using Static to delcare the static method, the method can be called with ClassName. MethodNmae.
(2) there is no keyword This in the static method.
(3)in the Static method, it can’t access the non-static variables and methods
2.2.6.5 Final
(1) use final to delcare class, this calss can’t be inheriated
(2) use final to declare the method, thsi method can’t be override by other subclass.
(3)use final to delcare variables, first is to delcare the type of data, it means the value of the data type can’t be changed.
second, declare reference type,it means it can’t be pointed to other object after initialization.
2.2.6.6 Upcasting and Downcasting
(1) Upcasting
typecasting the child object to a parent object, it’s can be implicit
(2) Downcasting
typecasting of a parent object to a child object. Downcasting cannot be implicit.
2.2.6.7 Composition
Composition defines a class as the sum of its parts.
Example:
public class SoccerPlayer {
private String name;
private Soccer soccer;
}
public class Soccer {
private String soccerName;
}
In the SoccerPlayer, it refers the Soccer class and call the properities and methods.
Difference between Composition and Inheritance:
Features | Composition | Inheritance |
---|---|---|
Relationship | has-a | is-a |
Coupling | low-coupling | high-coupling |
Polymorphism | don’t include polymorphism and upcasting | inheritance is the basis of polymorphism and can use upcasting |
period | binded in the run period | inheritance is binded in the compile period |
High coupling and low cohesion.
2.3 Interface and Abstract class
2.3.1 Interface
keyword: interface
define a interface
public interface Job{}
define the inner
public interface Job {
void writewell();
}
Tip:
(1) interface is an abstract class, it just define the method, but not give the implementation of the method
(2) only two access permission are available: Public and Default
default only include the package access permission
(3) Implement
use implements to implementate the method of interface
class WriteWell implements Job{
@Override
public void writewell(){
System.out.println("Java is vary well");
}
}
one interface can have multiple implementation
(4) interface can’t be instanced and no constructors in it.
2.3.2 Abstract Class
Example: interface Dog: dog can be abstracted to white, small dog. and implmentation class could be specific class.
public interface Dog {
void FurColor();
}
abstract class WhiteDog implements Dog{
public void FurColor(){
System.out.println("Fur is white");
}
abstract void Smallbody();
}
(1) if there is an abstract method in the class, the class definitely is abstract class;
use Abstract to declare the method, the method is abstract method, and the class include abstract method, it is abstract class. Implmentation classes have the implmentation detail.
(2)abstract classes ont only have abstract methods, it can include specific methods
(3) Abstract Class isn’t as the same strict as the interface, Constructor, abstract methods, fields and method, static methods and fields can be define in the abstract class.
(4) as the same as interface, the abstract class can’t be instanced, only specific class can be instanced.
2.3.3 Inner Class
(1)inner class can be defined inside another class.
public class OuterClass {
private String name ;
private int age;
class InnerClass{
public InnerClass(){
name = "cxuan";
age = 25;
}
}
}
(2) Inner classes can be hidden from other classes in the same package.
(3) inner classes have the access permission of outclass, even the private data
inner class can implementate the multiple inheritance.
(4) Methods of inner class:
a. local inner class
//define the class in the method
b.member inner class
// define the class in the scope
c. annoymous inner class
//the annoymous class that implementate the interface
//expand the class with the non-default constructors
//excute the initialization of the fields
//construcate by initialization of instance
2.3.4 Proxy
if class A want to call the method of class B, A can create a object of B in the class(instead of call the method directly), and use the proxy to call the mthod of class B.
//use newProxyInstance method to create a proxy object of the Proxy class
// three parameters: (1)a class loader; (2)an array of class objects, one for each interace to be implemented; (3)an invocation handler
public class Destination {
public void todo(){
System.out.println("control...");
}
}
public class Device {
private String name;
private Destination destination;
private DeviceController deviceController;
public void control(Destination destination){
destination.todo();
}
}
public class DeviceController {
private Device name;
private Destination destination;
public void control(Destination destination){
destination.todo();
}
}
2.4 Exception
2.4.1 Throwable
Throwable is the superclass of the all errors and exceptions
2.4.1.1 RuntimeException
Example:
No. | Exception Name | Exception Description |
---|---|---|
1 | ArrayindexOutOfBoundsException | index of Array out of bound |
2 | NullPointException | NullPoint |
3 | IllegalArgumentException | Illegal Argument |
2.4.1.2 UncheckedException
No. | Exception Name | Exception Description |
---|---|---|
1 | NoSuchFieldException | no specified field in the class |
2 | NoSuchMethodException | no specified method in the class |
3 | IllegalAccessException | can not access the class |
4 | ClassNotFoundException | can not find the class |
2.4.1.3 Keywords about Exception
(1)Throws and throw
Exception is also an obejct, use throws and throw to define the throwing exception
static void cacheException() throws Exception{
throw new Exception();
}
throw used in the method, and means throw exception. it mainly do the specific action to throw exception
Throws is used after the declartion of method, it means throw the exception and processed by the user that call this method. It mianly declares this method will throw the type of exception
(2) try, finally, catch
try-catch: catch the exception when the code may throw the exception
static void cacheException() throws Exception{
try {
System.out.println("1");
}catch (Exception e){
e.printStackTrace();
}
}
try-finally: no matter the code excuted with exception or not, the code of finally will be excuted.
static void cacheException() throws Exception{
for (int i = 0; i < 5; i++) {
System.out.println("enter: i=" + i);
try {
System.out.println("execute: i=" + i);
continue;
} finally {
System.out.println("leave: i=" + i);
}
}
}
2.4.2 Error
Suppose an error occurs while a Java program is running. The error might be caused by a file containing wrong information, a flaky network connection, or use of an invalid array index or an object reference that hasn’t yet been assigned to an object.
and Sometimes JVM may occur problems when the program is running.
Consider the sorts of problem:
(1)User input errors:In addition to the inevitable typos, some users like to blaze their own trail instead of following directions. Suppose, for example, that a user asks to connect to a URL that is syntactically wrong. Your code should check the syntax, but suppose it does not. Then the network layer will complain.
(2)Device errors. Hardware does not always do what you want it to. The printer may be turned off. A web page may be temporarily unavailable. Devices will often fail in the middle of a task. For example, a printer may run out of paper during printing.
(3)Physical limitations. Disks can fill up; you can run out of available memory
(4)Code errors. A method may not perform correctly. For example, it could deliver wrong answers or use other methods incorrectly. Computing an invalid array index, trying to find a nonexistent entry in a hash table, or trying to pop an empty stack are all examples of a code error.
2.4.2.1 OutOfMemoryError
Java memory model
(1)It consists of data area shared by all threads and thread-isolated data area.
(2)the program counter can’t occur the OutOfMemoryError. and each thread of it is private.
(3)Method area, VM Stack, Native Method Stack and heap may occur the OutOfMemoryError
(4)Heap: if the heap don’t have enough memory to allocate the instance and can’t expend memory, it will occur OutOfMemoryError
(5) Method Area: when the method area can’t meet the requirement of allocation of memory, it will occur OutOfMemoryError.
2.4.2.2 StackOverflowError
Stack of VM: if the depth of stack requested by thread is higher than the depth allowed of VM, it will occur the StackOverflowError. If VM can’t dynamic extend memory, it will occur OutOfMemoryError.
3.Collection
3.1 Framwork
3.2 Iterable Interface
The Iterator interface has four methods:
public interface Iterator<E> {
E next();
boolean hasNext();
void remove();
default void forEachRemaining(Consumer<? super E> action);
}
3.2.1 For-each Loop
The Collection interface extends the Iterable interface. Therefore, you can use the “for each” loop with any collection in the standard library.
Instead of writing a loop, can call the forEachRemaining method. The lambda expression is invoked with each element of the iterator, until there are none left.
Example:
List<Object> list = new ArrayList();
for (Object obj: list){}
iterator.forEachRemaining(element -> do something with element);
use for-each to loop through array
Object[] list = new Object[10];
for (Object obj: list){}
use iterator to traversal
for(Iterator it = coll.iterator(); it.hasNext(); ){
System.out.println(it.next());
}
3.2.2.Interfaces in the Collections Framwork
3.2.2.1 List
It inheriated from the Collection, it’s the superclass of ArrayList, LinkedList and so on.
3.2.2.2 Set
Set interface provides extra rules. it also provides extra standards for (add, equals,hashCode)Methods.
3.2.2.3 Queue
It keeps the order of access before processing
3.2.2.4 SortedSet
It inheriated from the Set interface. Use Compariable to sort the elements or use Comparator to make the sort rule when creating elements. the Interator in the Set will traversal the set with the Ascending elements.
3.2.2.5 Map
Map is an object that can support Store the Key-Value. but It can’t include the repeated key, and each key can map to most one value. It insteads of Directory Class, Directory is an abstract class, not a interface.
3.2.3 Concrete Collections
3.2.3.1 Array List
It implementate the expendable array(dynamically reallocated array)
public class ArrayList<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, java.io.Serializable {...}
(1) ArrayList can implementate the operations of list, and it provides the inner method to store list. However, ArrayList isn’t a container of thread safe, in order to ensure the thread safety, we can use the list with threadsafe.
List list = Collections.synchronizedList(new ArrayList(...))
(2) It has fail-fast system, when the collection changes of constructs, it may trigger fail-fast, and throw the exception.
ConcurrentModificationException
3.2.3.2 Vector
(1) It is based on the array and it’s the container of thread safety. It locks each inner methods to avoid the safety problem of multithreading.
(2) The efficiency of accessing element of Vector is much lower than ArrayList.
(3) The length of array will expand 100% when the vector expand the length, but for ArrayList, the array will only expand 50%.
3.2.3.3 LinkedList
LinkedList is a Doubly linked list, it can store any elements(null).
(1)all operation of LinkedList all are doulby link.
(2) if multithreading concurrent access linkedlist, and at least one thread change the structure of linkedlist, then the linked list should have Extrinsic Lock. Or use
List list = Collections.synchronizedList(new LinkedList(...))
3.2.3.4 Stack
Stack is the container that Last In First Out, It inheritanced from Vector.
(1) pop
to pop an element from the stack
(2)push
to put it the stack an element, and put it in the top of the stack
(3) empty
to check whether the stack is empty or not.
(4) peek
fetch the first element of the Stack or the element present at the top of the Stack.
(5) search
search for an element in the stack and get its distance from the top
3.2.3.5 HashSet
The implementation class of Set inteface, it will supported by HashMap(Hashset is an instance of HashMap)
It can’t ensure the order of iteration of collection
It allow NULL element
(1) If multithreading concurrent access the HashSet, and at least one thread change the set, it must do extrinstic Lock. or override with
Collections.synchronizedSet()
(2) it supports
fail-fast
3.2.3.6 TreeSet
TreeSet implementated by the NavigableSet of TreeMap.
(1) add.remove()
the complexity: Log(n)
TreeSet.remove(Object O)
//The parameter O is of the type of Tree set and specifies the element to be removed from the set.
(2) Contains()
The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided.
the complexity: Log(n)
Tree_Set.contains(Object element)
(3) use extrinstic Lock if multithreading concurrent access and at least one thread changes set, or
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...))
(4) provided with fail-fast
3.2.3.7 LinkedHashSet
It inheriated from set.
(1)LinkedHashSet is the implementation of HashMap and LinkedList of Set interface.
LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted.
(2)It defines the order of insertation of elements
(3)Two parameters: initial capacity and load factor
the number of iterations isn’t affected by capacity
(4)to ensure safety
Collections.synchronizedSet
(5)fail- fast
3.2.3.8 PriorityQueue
(1) PriorityQueue is the implentation class of AbstractQueue. Depands on the constructor, the elements of it can use nature ordering or use comparator in the constructor.
(2) PriorityQueue don’t allow Null element
(3) the head of queue points that the last element.
(4) there is a inner capacity that control the size of array that stored the elements in the queue.
(5) if want in-order traversal
Arrays.sort(pq.toArray())
(6) safe thread
PriorityBlockingQueue
3.2.3.9 HashMap
(1) use the hashtable to store elements and allow the null key- vlaue
(2) HashMap isn’t a safe threading, but Hashtable is a container with safe threading
(3) Fall-fast
(4) Initial capacity and load factor
(5) create a thread safety HashMap
Collections.synchronizedMap(new HashMap(...))
3.2.3.10 TreeMap
(1) Red-Black Tree implementated by NavigableMap.
this map use key nature ordering or use Comparator to sort
(2)ContainsKey(), get(), put(), remove()
Time complexity: log (n)
(3) Thread safety
SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...)) ̶
(4) fail-fast
3.2.3.11 LinkedHashMap
(1) it’s the implementation of Hashtable and LinkedList.
a linked list of the entries in the set, it defines the traversal order( insertion order).
(2)create the LinkedHashMap with
//constructor
LinkedHashMap(int,float,boolean)
the trraversal order is the order of last visit
(3) Override
removeEldestEntry(Map.Entry)
(4)It may have one null key and multiple null values
(5)two parameters: Inital Capacity and load factor
(6)thread safety
Map m =
Collections.synchronizedMap(new LinkedHashMap(...))
(7)It is non-synchronized.
(8)fail-fast
3.2.3.12 Hashtable
(1)It implementate the hashtable and it can stores key/value pair in hash table. any non-null object can be used as key and value
(2) fail- fast
(3)Hashtable is thread safety. If need multithreading and high concurrency, use
ConcurrentHashMap
3.2.3.13 IdentityHashMap
(1) it isn’t a general Map implementation. and requires using equals Method to compare objects
(2)it’s not ordered, and to ensure thread safety
Collections.synchronizedMap(new IdentityHashMap(...))
(3) fail-fast
3.2.3.14 WeakHashMap
(1) It’s an implementation of the Map interface that stores only weak references to its keys.(implementated by Map of Hashtable, and take weak Key.)
(2)An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use
(3) support Null value and Null Key
(4)fail-fast
(5)don’t allow repeat
(6)it usually used as cache
3.3 Collections Class
3.3.1 Synchronization Wrappers(同步包装)
The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. There is one static factory method for each of the six core collection interfaces(Collection, Set, List, Map, SortedSet and SortedMap):
public static Collection synchronizedCollection(Collection c);
public static Set synchronizedSet(Set s);
public static List synchronizedList(List list);
public static Map synchronizedMap(Map m);
public static SortedSet synchronizedSortedSet(SortedSet s);
public static SortedMap synchronizedSortedMap(SortedMap m);
3.3.2 Immutable collections
It will stop the action that try to change the collection and giev the exception(UnsupportedOperationException)
Usage Scenorias:
(1) the collections which can not be modified once they are created. In this case, it’s better to not get the reference of collection to keep Immutability.
(2) immutable collections only offer read access through their API to access the data structures for some Clients.
Clients can read and have fully access permission with the method, but can’t edit:
public static Collection unmodifiableCollection(Collection<? extends T> c);
public static Set unmodifiableSet(Set<? extends T> s);
public static List unmodifiableList(List<? extends T> list);
public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m);
public static SortedSet unmodifiableSortedSet(SortedSet<? extends T> s);
public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends
V> m);
3.3.3 Collections with Thread safety
(1)(java.util.concurrent) provides that collections with thread safety can change when do traversal
(2)design Iteraator to use fail-fast and throw ConcurrentModifificationException.
some Implementation Classes
CopyOnWriteArrayList
ConcurrentHashMap
CopyOnWriteArraySet
3.3.4 Features of Different Collection Class
Array | Sort | Random Access | Key-Value | Repeat Element | Null Element | Thread safety |
---|---|---|---|---|---|---|
ArrayList | Y | Y | N | Y | Y | N |
LinkedList | Y | N | N | Y | Y | N |
HashSet | N | N | N | N | Y | N |
TreeSet | Y | N | N | N | N | N |
HashMap | N | Y | Y | N | Y | N |
TreeMap | Y | Y | Y | N | N | N |
Vector | Y | Y | N | Y | Y | Y |
HashTable | N | Y | Y | N | N | Y |
ConcurrentHashMap | N | Y | Y | N | N | Y |
Stack | Y | N | N | Y | Y | Y |
CopyOnWriteArrayList | Y | Y | N | Y | Y | Y |
4.Generic Programming(泛形)
4.1 Generic Class
crete generic type class:
Example:
//use parameter to denote generic
public class GenericDemo<T>{
//value The type of variables is T, and the type is external assigned.
private T value;
public GenericDemo(T value) {
this.value = value;
}
public T getValue(){
//the type of return is T of generic method (getKey), the type is external assigned.
return value;
}
public void setValue(T value){
this.value = value
}
}
4.2 Generic Interface
//the defination and usage of generic interface are similar as Generic Class
public interface Generator<T> {
public T next();
}
4.3 Gneric Method
public class GenericMethods {
public <T> void f(T x){
System.out.println(x.getClass().getName());
}
}
4.4 Generic Wildcards(通配符)
List is an generic list, to present the parent of different generic lists, generic wildcards can be used.
Generic wildcards can be denoted as (?), it can present any type of element. For example:
public static void main(String[] args) {
List<String> name = new ArrayList<String>();
List<Integer> age = new ArrayList<Integer>();
List<Number> number = new ArrayList<Number>();
name.add("superorange");
age.add(22);
number.add(77);
generic(name);
generic(age);
generic(number);
}
public static void generic(List<?> data) {
System.out.println("Test superorange :" + data.get(0));
}
.
(1) Upper Bound wildcards:
<? extends ClassType>
It presents all subclass of the ClassType.
(2) Lower Bound wildcards:
<? super A>
it can denote all superclass of the ClassType
You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.
5.Reflection
5.1 Functions
(1) Determine the class to which any object belongs
(2) Construct an object of any class when running
(3) Determine all variables and method of any class
(4)call the method of any object when running
Package to implementate Reflection system: Java.lang.reflect
Example of Reflection:
public class Person {
public String name;//name
public int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String showInfo() {
return "name=" + name + ", age=" + age;
}
}
public class Student extends Person implements Study {
public String className;//Class
private String address;//Address
public Student() {
super();
}
public Student(String name, int age, String className, String address) {
super(name, age);
this.className = className;
this.address = address;
}
public Student(String className) {
this.className = className;
}
public String toString() {
return "name: " + name + ",age: " + age + ",className: " + className + ",֘Addrress:"
+ address;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class TestRelect {
public static void main(String[] args) {
Class student = null;
try {
student = Class.forName("com.cxuan.reflection.Student");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// get all public fields of the object
Field[] fields = student.getFields();
for (Field f : fields) {
System.out.println(f);
}
System.out.println("---------------------");
// get all fields of the object(not include the inherited)
Field[] declaredFields = student.getDeclaredFields();
for (Field df : declaredFields) {
System.out.println(df);
}
// get all public methods of the object
Method[] methods = student.getMethods();
for (Method m : methods) {
System.out.println(m);
}
// get all public methods of the object
Method[] declaredMethods = student.getDeclaredMethods();
for (Method dm : declaredMethods) {
System.out.println(dm);
}
// get all public constructors of the object
Constructor[] constructors = student.getConstructors();
for (Constructor c : constructors) {
System.out.println(c);
}
System.out.println("---------------------");
// get all constructors of the object
Constructor[] declaredConstructors = student.getDeclaredConstructors();
for (Constructor dc : declaredConstructors) {
System.out.println(dc);
}
Class c = Class.forName("com.cxuan.reflection.Student");
Student stu1 = (Student) c.newInstance();
//First method: Instance Default method, call set to value
stu1.setAddress("nottingham");
System.out.println(stu1);
//second method: get all constructor
Constructor<Student> constructor = c.getConstructor(String.class,int.class,String.class, String.class);
Student student2 = (Student) constructor.newInstance("name",22,"No.6","nottingham");
System.out.println(student2);
//Extract method and excute method
Method show = c.getMethod("showInfo");//get the method called showInfo
Object object = show.invoke(stu2); //call the method called showInfo
}
}
5.2 Class
The class that holds this information is called, somewhat confusingly, Class. The getClass() method in the Object class returns an instance of Class type.
Employee e; . . . Class cl = e.getClass();
5.3 Method Class
invoke(Object obj, Object... args)
Passing the object and the method that parameters calls this object
5.4 ClassLoader
Class loaders are responsible for loading Java classes dynamically to the JVM (Java Virtual Machine) during runtime.
6.enumeration
6.1 Enum
In java, use keywork enum to express enumeration.
Example:
public enum Family {
FATHER,
MOTHER,
SON,
Daughter; }
In the example, it has 4 value, because type of enumeration is constant, so use Upper Letter to present them; the reference of enumeration:
public class EnumUse {
public static void main(String[] args) {
Family s = Family.FATHER;
}
}
6.2 Features of enumerations
Compiler can add the toString() automatically, so that we can get the name of the instance of the enum.
and use ordinal() to declare the statement order of the enum.
and use values() to show the value of the order.
public static void main(String[] args) {
for(Family family : Family.values()){
System.out.println(family + ", ordinal" + family.ordinal());
}
}
enum can use the static import package, thus using the constant directly, instead of inputing the enum_ClassName.constant.
//enum
//static
Example:
The example imports all the constants of the Family, it also be used to indicate the specific constant.
6.3 Enum Class
Keyword enum implicit inheritance with Enum class
Enum Class is located in the java.lang package
In the class, it can use isEnum to verify the type is enum or not
isEnum()
6.4 EnumSet
EnumSet can be used as the alternative to Enum, because the efficiency is higher.
6.5 EnumMap
EnumMap is a special Map, it asks the value of the key from an enum.
EnumMap can be used as the fast search of the key because it is fast
7. I/O
7.1 Classification of I/O
classification based on operation on I/O:
classification based on objects on I/O:
7.2 File Class
File Class can operate the file or the directories in the file system, it can operate them with oriented objects.
Example: deleting the file, creating the file or get the description of file and so on
public static void main(String[] args) {
File file = new File("D:\\file.txt");
try{
f.createNewFile();//create the file
//two constants of file
//delimiter(character used to seperate the directory names) is specific to the system:
//windows(\), linux(/)
//character used to seperate the directory is specific to the system:
//windows(;), linux(:)
//delete file
File file = new File(fileName);
if(f.exists()){
f.delete();
}else{
System.out.println("file doesn't exist");
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
Example: Operation to Directory
class FileDemo{
public static void main(String[] args) {
String fileName = "D:"+ File.separator + "filepackage";
File file = new File(fileName);
f.mkdir();
//list all files
String[] str = file.list();
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
Three Methods to create the file
File(String directoryPath);
File(String directoryPath, String filename);
File(File dirObj, String filename);
in the example, directoryPath is the directory name of file, and filename is the name of file, dirObj is the object of the File.
File file = new File("D:\\java\\file1.txt"); // \\means escape character
System.out.println(file);
File file2 = new File("D:\\java","file2.txt");//adapted to multiple files(parent path and children path)
System.out.println(file2);
File parent = new File("D:\\java");
File file3 = new File(parent,"file3.txt");//parent and child path for File Class
System.out.println(file3);
7.3 Summary of File Class
Method | Description of Method |
---|---|
public String getName() | return tha name of file or directory of the path |
public String getParent() | return the string of the parent path of this path |
public String getPath() | transfer the name of the path to the string of the path |
public boolean isFile() | verify the file is a standard file or not |
public boolean equals(Object obj) | verify the name of path is equal to the specific obejct or not |
public String[] list() | return the string array of |
public boolean mkdir() | create the directory of the path |
public String getAbsolutePath() | The function returns an array of string denoting the files in a given abstract pathname |
public boolean exists() | verify the file that this path expressed exists or not |
7.4 Basic Classes of I/O
four basic abstract classes: InputStream, OutputStream, Reader, Writer
Basic Method: read(), write()
The detail of the I/O streams can check the following link:
https://docs.oracle.com/javase/tutorial/essential/io/index.html
8.Annotation
(1) @Override
The mark of the overriding, it usually used after the subclass inherited from superclass. It can mark in the overrided sub- method.
(2) @SuppressWarnings
This annotation is used to ignore the warning of compiler
(3) @Retention
identify the storage method.
(4) @Documented
identify the annotation is included in the JavaDoc or not.
(5) @Target
Mark this annotation to describe the scope of the object modified by the annotation, which can be used for packages, types, type members, method parameters and local variables.
public enum ElementType {
TYPE,
FIELD,
METHOD,
PARAMETER,
CONSTRUCTOR,
LOCAL_VARIABLE,
ANNOTATION_TYPE,
PACKAGE,
TYPE_PARAMETER,
TYPE_USE
(6) @Inherited
mark which annotation class that the annotation inherited from.
9.null
9.1 Case Sensitive
null is keyword, and like public,static, final. they are sensitive, so null can’t be written as Null, NULL.
public class AccessModifierNull{
Object object = Null;
Object object1 = null;
}
9.2 Default
The default of reference types is null.
The default value of data types is as follows:
Type | Default |
---|---|
boolean | false |
char | /u0000 |
byet | (byte)0 |
short | (short)0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
9.3 speical value
null can be assigned to any type, and it can be transfered to any type
public static void main(String[] args) {
String str = null;
Integer itr = null;
Double dou = null;
Integer integer = (Integer) null;
String string = (String)null;
System.out.println("integer = " + integer);
System.out.println("string = " + string);
}
null can be only assigned to reference variables, can’t be assignede to basic type variables.
public static void main(String[] args) {
int i = 0;
Integer itr = null;
System.out.println(itr == i);
}
when use reference variable with null value, instanceof will return false.
public static void main(String[] args) {
Integer isNull = null;
//instanceof = isInstance method
if(isNull instanceof Integer){
System.out.println("isNull is instanceof Integer");
}else{
System.out.println("isNull is not instanceof Integer");
}
}
9.4 Null-Safe
public class NullSafeMethod {
private static String number;
public static void main(String[] args) {
String s = String.valueOf(number);
String string = number.toString();
System.out.println("s = " + s);
System.out.println("string = " + string);
}
}
number is not assigned, so it defaults to null.
String.value(number)
//haven't throw null exception
toString()
//throw null exception
9.5 null judgement
//use == or != to compare null value
//can't use other mathematic or logic operation, such as < or >
public class CompareNull {
private static String str1;
private static String str2;
public static void main(String[] args) {
System.out.println("str1 == str2 ? " + str1 == str2);
System.out.println(null == null);
}
}
in Java, null==null will return true