Java teaches you how to get started quickly

Posted by miz_luvly@hotmail.com on Tue, 02 Nov 2021 07:06:24 +0100

  Add Qianqian teacher vx to get the latest information    


The Java program consists of package+class. Package corresponds to the relative path of the directory and class corresponds to the file, as shown in

E:\Workspaces\MyEclipse 10\JavaStudy\src\com\happyframework\javastudy\hello\Hello.java

1 package com.happyframework.javastudy.hello;
2 
3 public final class Hello {
4     public static void hello(){
5         System.out.println("hello!");
6     }
7 }

There are the following rules about class:

  1. The name of the file must be consistent with the name of the class (public level class name).
  2. The file must contain only one public access basic class (it can contain multiple non-public classes).
  3. package name must be consistent with the directory.

Entrance method

App.java

1 public class App {
2     public static void main(String[] args) {
3         com.happyframework.javastudy.hello.Hello.hello();
4     }
5 }

Final project structure

 

  data type

8 atomic types

  1. Integer types: byte, short, int, and long.
  2. Decimal types: float and double.
  3. Character type: char.
  4. Boolean type: bool.

In addition to this are interface, class and array.

Constants of decimal type are double by default. Constants of float type need to be declared with F as suffix.

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7             float age = 28.0F;
 8             System.out.println(age);
 9     }
10 
11 }

operator

  1. Arithmetic operators: +, -, *, / and%, divide two integers, and the result is still an integer.
  2. Assignment operators: =, + =, - =, * =, / =,% =, & =, | =, ~ =, ^ =, < =, > > =, > > =, + +, and --.
  3. Comparison operators: = =,! =, <, < =, > And > =.
  4. Logical operators: & &, |, and!.
  5. Bitwise operators: &, |, ~, ^, <, > > and > >.

character string

String is a reference type with "value semantics". String constants implement "meta sharing mode". equals will be compared according to content, = = by address.

  1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         String x = "Duan Guangwei";
 8         String y = new String("Duan Guangwei");
 9         
10         System.out.println(x.equals(y)); // true
11         System.out.println(x == y); // false
12     }
13 
14 }

In order to modify strings efficiently, Java introduces StringBuffer.

1         {
2             StringBuffer sb = 
3                     new StringBuffer()
4                     .append("paragraph")
5                     .append("light")
6                     .append("Great");
7             
8             System.out.println(sb.toString());
9         }

array

Declarative syntax

DataType[] name or DataType name [].

Initialization syntax

DataType[] name = new DataType[length].

DataType[] name = new DataType[] { element1, element2, ...elementn }.

DataType[] name = { element1, element2, ...elementn }.

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         {
 8             String[] strs = { "paragraph", "light", "Great" };
 9 
10             for (String item : strs) {
11                 System.out.print(item);
12             }
13         }
14     }
15 
16 }

Multidimensional array

Only unequal length multidimensional array DataType [] [], no DataType[xxx, xxx].

control structure

  1. Conditions: if else, if else, switch case default, and ternary operator (?:).
  2. Loops: while, do while, for, and foreach.
  3. Labeled block.
1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         task: {
 8             int age = 25;
 9 
10             System.out.println("start");
11 
12             if (age < 30) {
13                 break task;
14             }
15 
16             System.out.println("end");
17         }
18     }
19 }

Recently, I think label is a good thing. At least there is one more choice.

method

All assignments and method calls in Java are processed "by value". The value of the reference type is the address of the object, and the value of the original type is itself.

Java supports variable length method parameters.

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         print("Duan Guangwei", "Duan Guangyu");
 8         print(new String[] { "Duan Guangwei", "Duan Guangyu" });
 9     }
10 
11     private static void print(String... args) {
12         for (String item : args) {
13             System.out.println(item);
14         }
15     }
16 }

class

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         Point point = new Point(100);
 8 
 9         System.out.print(point);
10     }
11 }
12 
13 class Point {
14     private int x = 0;
15     private int y = 0;
16 
17     public Point(int x, int y) {
18         this.x = x;
19         this.y = y;
20     }
21 
22     public Point(int x) {
23         this(x, x);
24     }
25 
26     public String toString() {
27         return "(x:" + this.x + ",y:" + this.y + ")";
28     }
29 }

Note: calling its own construction method is completed with this(xxx,xxx,...) and must be on the first line.

Static member

The structure similar to static construction method in Java is called static initialization code block, which corresponds to instance initialization code block, as shown in the following example:

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         System.out.println(Point.getValue());
 8         System.out.println(new Point());
 9     }
10 }
11 
12 class Point {
13     private static int value = 0;
14 
15     public static int getValue() {
16         return value;
17     }
18 
19     static {
20         value++;
21     }
22 
23     static {
24         value++;
25     }
26 
27     private int x = 0;
28     private int y = 0;
29 
30     {
31         this.x = 10;
32     }
33 
34     {
35         this.y = 10;
36     }
37 
38     public String toString() {
39         return "(x:" + this.x + ",y:" + this.y + ")";
40     }
41 }

inherit

Extensions is used for inheritance, abstract classes and abstract methods are declared by abstract, and (ChildType)instance is used for downward transformation to judge whether instanceof is used for a certain type, as shown in the following example:

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         printAnimal(new Animal());
 8         printAnimal(new Dog());
 9     }
10 
11     private static void printAnimal(Animal animal) {
12         if(animal instanceof Dog){
13             System.out.println("I am a " + (Dog) animal);
14         }
15         else
16         {
17             System.out.println("I am an " + animal);
18         }
19     }
20 }
21 
22 class Animal {
23     public String toString() {
24         return "Animal";
25     }
26 }
27 
28 class Dog extends Animal {
29     public String toString() {
30         return "Dog";
31     }
32 }

rewrite

Rewriting rules in Java are flexible, as follows:

  1. All instance methods except private modification can be overridden without explicit declaration.
  2. The rewriting method uses @ Override for annotation in order to explicitly express the concept of rewriting.
  3. Overridden methods can modify access modifiers and return types as long as they are compatible with the methods of the parent class (higher access levels and more specific return types).
  4. You can use final to mark a method as non rewritable.
  5. Use super(xxx, xxx) to call the parent class construction method in the construction method, and use super.method(xxx, xxx) to call the parent class method in the regular instance method.
  6. Java does not support overwrite (new).
1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         Animal animal = new Animal();
 8         Animal dog = new Dog();
 9 
10         animal.say();
11         dog.say();
12 
13         animal.eat(animal);
14         dog.eat(dog);
15         
16         System.out.println(animal.info());
17         System.out.println(dog.info());
18     }
19 }
20 
21 class Animal {
22     private String name = "Animal";
23 
24     protected void say() {
25         System.out.println("Animal" + " " + this.name);
26     }
27 
28     public void eat(Animal food) {
29         System.out.println("Animal eat " + food);
30     }
31 
32     public Object info() {
33         return "Animal";
34     }
35     
36     @Override
37     public String toString() {
38         return "Animal";
39     }
40 }
41 
42 class Dog extends Animal {
43     private String name = "Dog";
44 
45     @Override
46     public final void say() {
47         System.out.println("Dog" + " " + this.name);
48     }
49 
50     @Override
51     public final void eat(Animal food) {
52         super.eat(food);
53         
54         System.out.println("Dog eated");
55     }
56 
57     @Override
58     public final String info() {
59         return "Dog";
60     }
61 
62     @Override
63     public final String toString() {
64         return "Dog";
65     }
66 }

package

The package name corresponds to the directory path under the project path. For example, if the project path is C:\Study and a Java source file is located in C:\Study\com\happyframework\study\App.java, the package name of App.java must be com.happyframework.study, and the first line of App.java must be package com.happyframework.study.

Java supports three import syntax:

  1. Import type: import xxx.xxx.xxxClass.
  2. Import package: import xxx.xxx.xxx. *.
  3. Import static members: import static xxx.xxx. *.
 1 import static util.Helper.*;
 2 
 3 public class Program {
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         puts("Duan Guangwei");
10     }
11 }

Access level

Java supports four access levels: public, private, protected and default (default). Only public and default can be used for types and interfaces, and all can be used for member and nested types. The following is a brief explanation of protected and default.

  • protected modified members can only be accessed by themselves, subclasses and other types in the same package (excluding sub packages).
  • default modified types or members can only be accessed by themselves and other types in the same package (excluding sub packages).

Nested class

Java supports the following nested classes:

  1. nested class, which defines the type inside the type.
    1. static nested class, a nested class declared by static. static nested class can access static members of all external classes.
    2. inner class is a nested class without static declaration. inner class can access instance members of all external classes. inner class cannot define static members.

Code example

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         OuterClass outer = new OuterClass();
 8         OuterClass.InnerClass inner = outer.new InnerClass();
 9         OuterClass.InnerClass.InnerInnerClass innerInner = inner.new InnerInnerClass();
10         outer.show();
11         inner.show();
12         innerInner.show();
13         
14         OuterClass.StaticNestedClass staticNested=new OuterClass.StaticNestedClass();
15         OuterClass.StaticNestedClass.StaticNestedNestedClass staticNestedNested=new OuterClass.StaticNestedClass.StaticNestedNestedClass();
16         
17         staticNested.show();
18         staticNestedNested.show();
19     }
20 }
21 
22 class OuterClass {
23     int x = 1;
24     static int i = 1;
25 
26     void show() {
27         System.out.println(x);
28         System.out.println(i);
29     }
30 
31     class InnerClass {
32         int y = 2;
33 
34         void show() {
35             System.out.println(x);
36             System.out.println(y);
37         }
38 
39         class InnerInnerClass {
40             int z = 3;
41 
42             void show() {
43                 System.out.println(OuterClass.this.x);
44                 System.out.println(y);
45                 System.out.println(z);
46             }
47         }
48     }
49 
50     static class StaticNestedClass {
51         static int j = 2;
52 
53         void show() {
54             System.out.println(i);
55             System.out.println(j);
56         }
57 
58         static class StaticNestedNestedClass {
59             static int k = 3;
60 
61             void show() {
62                 System.out.println(i);
63                 System.out.println(j);
64                 System.out.println(k);
65             }
66         }
67     }
68 }

Special inner class: local class

 1 public class LocalClassExample {
 2 
 3     static String staticValue = "static value";
 4     String instanceValue = "instance value";
 5 
 6     public void test() {
 7 
 8         final String finalLocalValue = "final local value";
 9 
10         class LocalClass {
11             void test() {
12                 System.out.println(staticValue);
13                 System.out.println(instanceValue);
14                 System.out.println(finalLocalValue);
15             }
16         }
17 
18         LocalClass local = new LocalClass();
19         local.test();
20     }
21 }

In addition to the rules of inner class, local class can access local final variables, which is more improved in Java 8.

Special local class: anonymous class

1 public class Program {
 2 
 3     /**
 4      * @param args
 5      */
 6     public static void main(String[] args) {
 7         execute(new Action() {
 8             @Override
 9             public void execute() {
10                 System.out.println("Execute business logic");
11             }
12         });
13     }
14 
15     static void execute(Action action) {
16         System.out.println("Things start");
17         action.execute();
18         System.out.println("End of things");
19     }
20 }
21 
22 interface Action {
23     void execute();
24 }

constant

No more nonsense, just look at the code:

 1 public final class Program {
 2     static final String STATIC_CONSTANTS = "STATIC_CONSTANTS";
 3     final String INSTANCE_CONSTANTS = "INSTANCE_CONSTANTS";
 4 
 5     public static void main(String[] args) {
 6         final String LOCAL_CONSTANTS = "LOCAL_CONSTANTS";
 7 
 8         System.out.println(STATIC_CONSTANTS);
 9         System.out.println(new Program().INSTANCE_CONSTANTS);
10         System.out.println(LOCAL_CONSTANTS);
11         new Program().test("PARAMETER_CONSTANTS");
12     }
13 
14     public final void test(final String msg) {
15         System.out.println(msg);
16     }
17 }

One thing to note is that in only one case, Java constants are compile time constants (the compiler will replace them for you), and in other cases, they are run-time constants. In this case, statically typed constants and their values can be determined at compile time.

Interface

The Java interface can contain method signatures, constants and nested classes, as shown in the following example:

 1 public final class Program {
 2     public static void main(String[] args) {
 3         Playable.EMPTY.play();
 4 
 5         new Dog().play();
 6     }
 7 }
 8 
 9 interface Playable {
10     Playable EMPTY = new EmptyPlayable();
11 
12     void play();
13 
14     class EmptyPlayable implements Playable {
15 
16         @Override
17         public void play() {
18             System.out.println("have nothing to do");
19         }
20 
21     }
22 }
23 
24 class Dog implements Playable {
25 
26     @Override
27     public void play() {
28         System.out.println("Gnaw a bone");
29     }
30 
31 }

enumeration

Java enumeration is a class, which inherits from java.lang.Enum. Any type of definition can be defined in the enumeration. The construction method can only be private or package private. The enumeration members will be dynamically translated into enumeration instance constants by the compiler, as shown in the following example:

 1 public final class Program {
 2     public static void main(String[] args) {
 3         System.out.println(State.ON);
 4         System.out.println(State.OFF);
 5 
 6         for (State item : State.values()) {
 7             System.out.println(item);
 8             System.out.println(State.valueOf(item.name()));
 9         }
10     }
11 }
12 
13 enum State {
14     ON(1), OFF(0);
15 
16     int value = 1;
17 
18     State(int value) {
19         this.value = value;
20     }
21 }

The format of calling enumeration constructor is constant name (xxx, xxx). If the constructor has no parameters, only constant name is required, such as:

1 enum State {
2     ON, OFF
3 }

abnormal

Exceptions in Java are divided into checked and unchecked. Checked exceptions must be declared in methods or captured, which I think is better. Exceptions must also be part of the API, as shown in the following example:

 1 public final class Program {
 2     public static void main(String[] args) {
 3         try {
 4             test();
 5         } catch (Exception e) {
 6             System.out.println(e.getMessage());
 7         }
 8     }
 9 
10     public static void test() throws Exception {
11         throw new Exception("I am wrong!");
12     }
13 }

All exceptions that inherit exceptions (except runtime Exception and its descendants) are checked exceptions.

boxing and unboxing

Java provides the reference type corresponding to the original type. The version after 1.5 also provides automatic boxing and automatic unpacking. Combined with the latest version of generics, this can be almost ignored.

 1 import java.util.*;
 2 
 3 public final class Program {
 4     public static void main(String[] args) {
 5         ArrayList list = new ArrayList();
 6         
 7         list.add(1);
 8         int item1 = (Integer) list.get(0);
 9         
10         System.out.println(item1);
11     }
12 }

Note: Auto boxing and auto unpacking are syntax sugar provided by Java.

generic paradigm

Java generics are the syntax sugar provided by the compiler, which is officially called "type parameter erasure". First look at the syntax, and then summarize some rules:

generic method

Test code

1     static <T> void puts(T msg) {
 2         println(msg);
 3     }
 4 
 5     static void println(Object msg) {
 6         System.out.println("Object:" + msg);
 7     }
 8 
 9     static void println(String msg) {
10         System.out.println("String:" + msg);
11     }

Call generic method

1         System.out.println("generic method test");
2         puts("hello");
3         Program.<String> puts("hello");

The output is

1 generic method test
2 Object:hello
3 Object:hello

Generic class

Test code

1 class TestGenericClass<T> {
2     T value;
3 
4     void setValue(T value) {
5         this.value = value;
6     }
7 }

Calling code

1         System.out.println("generic class test");
2         System.out.println(t.value);

Output results

1 generic class test
2 1

generic interface

Test code

1 interface TestInterface<T> {
 2     void test(T item);
 3 }
 4 
 5 class TestInterfaceImp1 implements TestInterface<String> {
 6 
 7     @Override
 8     public void test(String item) {
 9         System.out.println(item);
10     }
11 }
12 
13 class TestInterfaceImp2<T> implements TestInterface<T> {
14 
15     @Override
16     public void test(T item) {
17         System.out.println(item);
18     }
19 }

Calling code

1         System.out.println("generic interface test");
 2         TestInterface<String> testInterface1 = new TestInterfaceImp1();
 3         testInterface1.test("hi");
 4         for (Method item : testInterface1.getClass().getMethods()) {
 5             if (item.getName() == "test") {
 6                 System.out.println(item.getParameterTypes()[0].getName());
 7             }
 8         }
 9 
10         TestInterface<String> testInterface2 = new TestInterfaceImp2<>();
11         testInterface2.test("hi");
12         for (Method item : testInterface2.getClass().getMethods()) {
13             if (item.getName() == "test") {
14                 System.out.println(item.getParameterTypes()[0].getName());
15             }
16         }

Output results

1 generic interface test
2 hi
3 java.lang.String
4 java.lang.Object
5 hi
6 java.lang.Object

Type parameter constraint

Test code

1 class Animal {
 2 }
 3 
 4 class Dog extends Animal {
 5 }
 6 
 7 class Base<T extends Animal> {
 8     public void test(T item) {
 9         System.out.println("Base:" + item);
10     }
11 }
12 
13 class Child extends Base<Dog> {
14 
15     @Override
16     public void test(Dog item) {
17         System.out.println("Child:" + item);
18     }
19 }

Calling code

1         System.out.println("bounded type parameters test");
2         Base<Dog> base = new Child();
3         base.test(new Dog());
4         for (Method item : base.getClass().getMethods()) {
5             if (item.getName() == "test") {
6                 System.out.println(item.getParameterTypes()[0].getName());
7             }
8         }

Output results

1 bounded type parameters test
2 Child:Dog@533c2ac3
3 Dog
4 Animal

Type wiping process

  1. Remove the type parameter from the generic definition.
class Base {
    public void test(T item) {
        System.out.println("Base:" + item);
    }
}

2. Replace T with the constraint type specified by extensions. The default is Object.

1 class Base {
2     public void test(Animal item) {
3         System.out.println("Base:" + item);
4     }
5 }

3. If a non generic type inherits or implements a generic base class or interface and is rewritten, the compiler will automatically generate some methods according to the situation.

 1 class Child extends Base {
 2     @Override
 3     public void test(Animal item) {
 4         this.test((Dog)item);
 5     }
 6     
 7     public void test(Dog item) {
 8         System.out.println("Child:" + item);
 9     }
10 }

4. Wipe out the calling code according to the actual parameters of the generic parameters.

1         System.out.println("bounded type parameters test");
2         Base base = new Child();
3         base.test(new Dog());
4         for (Method item : base.getClass().getMethods()) {
5             if (item.getName() == "test") {
6                 System.out.println(item.getParameterTypes()[0].getName());
7             }
8         }

What I said here is not necessarily correct, especially the constraint support of Java generics & (for ex amp le, multiple interfaces can be implemented by constraints), but the process is estimated to have little difference. I didn't look at the Java language specification, but here is only a general guess.

  Welfare at the end of the article
You can add teachers vx to get the latest information

  Don't forget to scan the code and get the [Java HD roadmap] and [full set of learning videos and supporting materials]

Topics: Java JavaEE Back-end