【JAVA】Basic syntax


Self-study materials:
[Java Tutorial] Novice Tutorial
[Crazy God Talks about Java] Java zero-based learning video is easy to understand
"Java Programming" edited by Chen Weijun and Wang Haojuan Tsinghua University Press

first program

public class HelloWorld {
    
    
    public static void main(String []args) {
    
    
        System.out.println("Hello World"); // 打印 Hello World
    }
}

Insert image description here

(1) Basic grammar

objects and classes

Java是一种面向对象语言

Insert image description here

  • Object: An instance of a class, with state (properties) and behavior (methods)

  • Class: a template used to describe the behavior and status of a class of objects

    • A class can contain the following three types of variables:
      1. Local variables: variables defined in methods, constructors, and statement blocks (variables are declared and initialized in methods, and variables are automatically destroyed after the method ends)
      2. Member variables: variables defined in the class and outside the method body (instantiated when the object is created, and can be accessed by methods, constructors and statement blocks of a specific class in the class)
      3. Class variables: declared in the class and outside the method body, but must be declared as static type
  • Method: that is, behavior. There can be many methods in a class. Logical operations, data modification and other actions are all completed in methods.

  • Constructor : The name of the constructor must be the same as the class. A class can have multiple constructors.

  • Create an object : Create using the keyword new. When creating an object, at least one constructor must be called.

type of data

  • Java's two major data types: built-in data types; reference data types
  • Built-in types (8 types): byte 1 byte (8 bits), short 2 bytes (16 bits), char 2 bytes (16 bits), long 8 bytes (64 bits), int 4 bytes (32 bits) ), boolean 1 bit, float 4 bytes (32 bits), double 8 bytes (64 bits)
  • Reference type : A reference type points to an object, and the variable pointing to the object is a reference variable. These variables are assigned a specific type when declared. Once a variable is declared, its type cannot be changed. Except for the 8 built-in types, the remaining data types are all reference types.

Variable type

  • Variable types supported by Java:
    Class variables (static variables): variables independent of methods, modified with static.
    Instance variables: variables independent of methods, but without static modification.
    Local variables: Variables in methods of a class.
public class Variable{
    
    
    static int allClicks=0;    // 类变量
    String str="hello world";  // 实例变量
    public void method(){
    
    		//
        int i =0;  // 局部变量
    }
}

modifier

  • Access control modifiers (4 types):
name explain user target audience
default (i.e. default, write nothing) Visible within the same package without any modifiers Classes, interfaces, variables, methods
private Visible within the same category variables, methods
public visible to all classes Classes, interfaces, variables, methods
protected Visible to classes and all subclasses in the same package variables, methods

Insert image description here

  • Non-access modifier :
name explain Suitable
static independent of object methods, variables
final Once a variable is assigned a value, it cannot be reassigned; a final class cannot be inherited; it
is usually used with the static modifier to create class constants;
Classes, methods, variables
abstract It cannot be used to instantiate objects. The only purpose of declaring an abstract class is to extend the class. Class, method
synchronized 和 volatile Mainly used for thread programming

operator

  • Operator summary
Operator type Contains symbols Remark
arithmetic operators + - * / % ++ – Insert image description here
Relational operators == != > < >= <= Determine whether the condition is true or false
Bit operators & l ^ ~ << >> >>> Acts on all bits, bitwise operations
Logical Operators && ll ! and, or, not
assignment operator = += -= *= /= (%)= <<= >>= &= ^= l=
Other operators Conditional operation Insert image description here
  • Operator precedence, auto-
    increment, subtraction, multiplication, division, addition , subtraction , shift relationship , equality, bitwise logic, logical operation , conditional assignment

(2) Process control

sequential structure

Select structure

Loop structure

branch structure


(3) Object-oriented

Method definition and calling

  • method definition
/*
修饰符 返回值类型 方法名(形参){
	//方法体
	return 返回值
	//void类型时,不需要返回值
}
*/

举例:
//有返回值
public int max(int a,int b){
    
    
	return a>b ? a : b;		//条件运算符
}
//无返回值
public void  print(){
    
    
}
//抛出异常
public void readRile(String file)throw IOException{
    
    
}
  • When calling a method
    , it differs depending on whether the method is static or not.

    • Static method (static): can be called directly in main
      类名.方法();
    • Non-static methods: need to instantiate this class
      对象类型 对象名 = new 类名();
  • Understanding of instantiation:
    static methods are created together with the class.
    Non-static methods need to be instantiated (new) before they can be called. That is,
    non-static methods are created only when instantiated. This
    can be seen as There is a sequential time sequence and cannot be called before it is created.

  • Construction method:

    1. Same as class name
    2. no return value
    3. Instantiating new class name() essentially calls the constructor
    4. The constructor takes parameters and can initialize the object.
    5. Once you define a parameterized construct, you must write a parameterless constructor

Insert image description here

Creation of classes and objects

  • Class (contains two things)
    1. Static properties (properties)
    2. Dynamic behavior (method)
  • Attribute (member variable):
    For example: static int age (modifier attribute type attribute name = attribute value)
  • Creation and use of objects
    • Objects must be created using the new keyword
      Person xiaoming = new Person();
    • Object properties
      xiaoming.name;
    • object methods
      xiaoming.show();

Insert image description here

encapsulation

  • Encapsulation hides properties and implementation details (For class encapsulation, properties are private)
    Only public access methods are provided to the outside world. The
    properties are set to privateand the methods are set to public
    The properties only provide get and set methods to the outside world, and the methods only provide interfaces to the outside world.
    Insert image description here

inherit

类和类之间的关系

  • A subclass is an extension of the parent class. Keywords extends. Things to be inherited are generally defined as public, or defined as privateusing encapsulation get and set to call the corresponding attributes.
  • Classes in JAVA only have single inheritance, not multiple inheritance (a parent class can have multiple subclasses; a subclass cannot have multiple parent classes)
  • super (similar to this)
    • Used in subclasses to call the constructor of the parent class
    • Can only appear in methods or constructors of subclasses

Insert image description here
Insert image description here

  • Method overriding

Polymorphism


(4) Use of categories

In order to better organize classes, JAVA provides a package mechanism to distinguish the namespace of class names.
Define package: package 包名
Import package: import package 包名.类名
For example: import java.util.Scanner calls the Scanner class under the utli package
. For example: import java.util.* Import all classes under the util package
(.* is called a wildcard)

User InteractionScanner

  • Obtain user input through the Scanner class
//一定先要导入java工具包中的Scanner类
import java.util.Scanner
//或者用import java.util.*
//创建Scanner对象
Scanner s = new Scanner(System.in);
  • Use next() and nextLine() methods to get the input string
  • Use hasNext and hasNextLine to determine whether there is still input data

Exception handling

(pending upgrade…)

Guess you like

Origin blog.csdn.net/Taylor_Kurt/article/details/129589296