JAVA basic review notes

JAVA Foundation

1. Notes

1. Single line notes:
//
2. Multiline comments:
/* /
3. Document notes
/*
*
*/

2. Data type

long  num1=10L;//Use capital l to prevent L from being regarded as 1
float num2=20.1f;
char name ='country';
boolean flag=true; 
//boolean flag=false;

1. Integer expansion

Binary 0b
Octal 0
Hex 0x

2. Floating point number expansion

//float finite discrete rounding error is close to but not equal to
//It is best to completely avoid using floating-point numbers for comparison
//BigDecimal mathematical tools (for bank calculation)

float f=0.1f;
double d=1.0/10;
System.out.println(f==d);//false

float d1=2324343253423f;
float d2=d1+1;
System .out.println(d1==d2);//true

3. Character expansion

String sa=new String("Hello world");
String sb=new String("Hello world");
String sc="Hello world";
String sd="Hello world";
System.out.println(sa=sb);//false
System.out.println(sc=sd);//true
//New opens up a new address and compares the addresses, so they are not equal

3. Type conversion

//All data are converted to the same type of data before calculation
int i=128;
byte b=(byte)i;//out of memory
//Cast (type) variable name high -- low
//Automatic conversion low high

1. Precautions

  1. Boolean values cannot be converted
  2. Cannot convert an object type to an irrelevant type
  3. When converting high capacity to low capacity, force conversion
  4. There may be memory overflow or accuracy problems during conversion

JDK7 up new feature: numbers can be separated by underscores

//Pay attention to overflow when operating large numbers
int money=10_000_000;
int years=20;
int total=money*years;//-1474836480 calculation overflow
long total2=money*years;//The default is int. there is a problem before the conversion
long total3=money*((long)years);//First convert an integer to long

4. Variables

public class Variable{
  static int allClicks=0; //Class variable static keyword dependent class
  String str="Hello wrold";
  //Instance variable: must declare and initialize values. If not initialized, the default value is 0.0 
  //Boolean value: false by default;
  //All default values are null except the basic type;
  
  public void method(){
  int i=0;//local variable
  }
}

1. Variable naming specification

Constants: uppercase letters and underscores
Class name: initial capitalization and hump principle
Class member variable, local variable, method name: initial lowercase and hump principle

5. Constant

//Value that cannot be changed after initialization
final double PI=3.14;
//Constant names generally use uppercase characters

6. Operator

int a=3;
int b=a++;//The value of b is 4
//a increases automatically and then assigns value to b   
int c=++a;//The value of c is 4
//a is assigned to c first and then self incremented
int d=a;//The value of d is 5

//and (& &) or (|) negate (!)
/*
A=0011 1100
B=0000 1101
A&B=0000 1100 If both are true, they are true
A|B=0011 1101 One truth is true
A^B=0011 0001 Only one truth is true
~B=1111 0010  Reverse

<<  Shift left * 2
>>  Shift right / 2
0000 0000  0
0000 0010  2
0000 0100  4
0000 1000  8
0001 0000  16
(2<<3)=2*2*2*2=16
*/

a+=b; //a=a+b
//String connector+
int a=10;
int b=20;
System.out.println(""+a+b);//Output: 1020
System.out.println(a+b+"");//Output: 30

//x ? y: z
//If x==true, the result is y, otherwise z

7. Package mechanism

Documents included in analogy documents
Generally, the company inverted domain name is used as the package name: com.wang.xxx
Package members are imported using the "import" statement

8. Scanner object

Scanner scanner=new Scanner(System.in);
//Next() and nextline() of the Scanner class get the input string
/*
next():
1. End input after reading valid characters
2. Automatically remove spaces before entering valid characters
3. Only spaces after valid characters are entered as separators or terminators
4. Cannot get a string with spaces
nextLine():
1. End with Enter
2. Can get blank
3. */
//hasNext(),hasNextLine() to judge whether there is still input data
/*
Example:
while(scanner.hasDouble()){
System.out.println("scanner.nextDouble()");
} 
//This loop continues until the input data that is not of type double ends the loop
*/
//Run out close 
scanner.close();

9. Select structure

/*if(Boolean expression){

}else if(){

}...
...
else(){

}
*/

/*
switch(expression){ //expression Type: byte,short,int,char,String
case value:         //value Must be a string constant or literal
//sentence
break: 
case value:
//sentence
break: 
...
default:
//sentence
}
*/

10. Circulation structure

/*
while(Boolean expression){
//Cyclic content
}
//In most cases, you end the loop in a way that invalidates the expression
//In a few cases, such as server request response and listening, it needs to be executed all the time

for(Initialization; Boolean expression; update){
//Code statement
}

//multiplication table
for(int i=1;i<10;i++){
         for(int j=1;j<i+1;j++){
             System.out.print(i+"*"+j+"="+i*j+" ");
     }
         System.out.println();
     }
     
for(Declarative statements: expressions){
//Code statement
}
//Example: traversing array elements
int[] numbers={10,20,30,40,50};
for(int x:numbers){  
System.out.println(x);
}

break:Forced exit cycle
continue: Skip this cycle

//Example: Triangle
for(int i=1;i<=5;i++){
         for(int j=5;j>=i;j--){
             System.out.print(" ");
     }
         for(int j=1;j<=i;j++){
             System.out.print("*");
         }
         for(int j=1;j<i;j++){
             System.out.print("*");
         }
         System.out.println();
     }
*/

11. Methodology

A method only implements one function, which is conducive to later expansion

1. Method body

/*
Modifier return value type method name (parameter type parameter name){
...
Method body
...
return Return value;
}
*/
//JAVA has only value passing, no reference passing

2. Heavy load

Same method name, different parameter types or quantities:
When calling a method, the corresponding method is automatically called according to the corresponding parameter type and quantity

3. Variable parameters

public void test(double j, int... i){}
//You can have any number of arguments of type int
//Variable parameters must be at the end of all parameters

4. Recursion

It can be used without recursion, which takes up a lot of space
Recursive structure = recursive head + recursive body

//n factorial 
public static int f(int n){
if(n==1){
return 1;
}else{
return n*f(n-1);
}
}

12. Array

Declaration: datatype [] arrayrefvar; / / preferred method
dataType arrayRefVar [] / / the same effect but not the preferred method

New creation: datatype [] arrayrefvar = new datatyper [arraysize];

characteristic:

  1. The length is determined and once created, the size is immutable
  2. The element type must be the same
  3. A numeric variable is a reference type. An array can also be regarded as an object. Each element in the array is equivalent to the member variable of the object
  4. The array object itself is in the heap

Two dimensional array

int a[][]=new int[2][5];
int[][] array={{1,2},{3,4},{4,5}};

1. Arrays class

The methods in the Arrays class are static methods modified by statistics, which can be called directly with the class name

//Print array element Arrays.toString()
System.out.println(Arrays.toString(array));

//Sort array: ascending
Arrays.sort(array);
//......

13. Classes and objects

Non static methods can only be called by instantiating new (does not exist), and static methods can be called directly (already exists)

Class is an abstract data type, and object is a concrete instance of abstract concept

1. Create and initialize objects

  1. Use the new keyword to create objects: allocate memory space and perform default initialization and call constructors in the class

  2. The constructor in a class, that is, the constructor, must be called when creating an object, and must be the same as the class name and have no return type

Example:

 //Student class
 public class Student{
 //attribute field
 String name;
 int age;
 //Constructor (the essence of new is to call constructor)
 public Student(String name,int age){
 this.name=name;
 this.age=age;
 }
 //method
 public void study(){
 System.out.println("study");
 }
 }
 
 //instantiation 
 Student xiaoming=new Student("Xiao Ming",3);

2. Packaging

Private member variables can only be used by calling the get and set methods in the class

14. Succession

Extensions means extension. The subclass extends the parent class, and there is only single inheritance in JAVA

The subclass inherits the public method of the parent class

//When there are the same attributes
public void test(String name){
System.out.println(name);//name of the output parameter
System.out.println(this.name);//Default value of name in output class
System.out.println(super.name);//Output the name of the parent class
//The same method is the same, but the private method of the parent class cannot be called with super
}

Attention

  1. super calling a parent class constructor must be in the first instance of the constructor
  2. super must only appear in methods or constructors of subclasses
  3. super and this cannot call constructor at the same time

Method rewrite

Inheritance relationship is required, and the subclass overrides the method of the parent class

  1. Method names must be the same
  2. The parameter list must be the same
  3. Modifier: the scope can be expanded but not reduced: public > protected > defaulted
  4. Exception thrown: the scope can be reduced, but not expanded

The reference of the parent class points to the child class: create the parent class object and instantiate it with the child class object, so that the child class override method can be called

father f=new son();

//Type that cannot be overridden:

  1. static method: belongs to class, not instance
  2. final constant
  3. private method

15. instanceof and type conversion

instanceof: judge whether there is a relationship

//Object>Person>Teacher
//Object>Person>Student
Object object= new Student();
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false

Type conversion: parent-child
//High and low
Person obj=new Student();
/student Convert this object to Student Types can be used Student Type method
//((Student) obj) forcibly converts a parent class to a child class

Student student=new Student();
Person person=student;
//Converting a subclass to a parent class may lose some of its original methods

16. STATIC

Static variables: can be called directly with classes
Static method: it can be called by ordinary methods in a class, but static methods cannot call ordinary classes
Static code block:
static {}: load first

17. Abstract class

abstract keyword

  1. Abstract classes only define methods, only names, and can't new without implementation
  2. Method subclasses of abstract classes must be implemented
  3. Ordinary methods can be written in abstract classes
  4. Abstract methods must be written in abstract classes

18. Interface

implements
interface keyword instead of class
Common class: only concrete implementation
Abstract classes: concrete implementations and specifications (abstract methods) are available
Interface: only specification! I can't write my own method ~ professional constraints

  1. All definitions in the interface are abstract public
  2. A class that implements an interface must override all methods in the interface
  3. Interfaces can inherit more than one, separated by commas

19. Internal class

Write another class inside the class

public class Outer{

public void out(){}

class Inner{ 
public void in(){} 
}
}

//Instantiate the inner class through the outer class
Outer.Inner=outer.new Inner();
inner.in();

Internal class can obtain external private properties and methods

//Local inner class
public void method(){
class Inner{
public void in(){
}
}
}

class Apple{
public void eat(){}
}
//There is no name to initialize the class, so there is no need to save the instance to the variable
new Apple().eat();

20. Abnormal

try{
//try monitoring area
}catch{
//Catch exception on exception

}finally{
//Dealing with the aftermath: releasing and closing resources
}

//Actively throw exception
if(a==0){
throw new ArithmeticException();}
public void main() throws ArithmeticException{}

//Custom exception class extends Exception

Tags: Java

Posted on Sat, 25 Sep 2021 14:50:59 -0400 by Tom_LR