Day06-constant variables, operators, package mechanism, JavaDoc

Day06-constant variables, operators, package mechanism, JavaDoc

variable

Variable: The amount that can be changed.

Java is a strongly typed language, and every variable must be declared of its type . A Java variable is the most basic storage unit in a program, and its elements include variable name, variable type and scope.

Variable declaration format : (basic, reference) data type variable name = value (you can use commas to separate multiple variables of the same type)

int a, b, c; // 声明三个int型整数:a、 b、c
int d = 3, e = 4, f = 5; // 声明三个整数并赋予初值
byte z = 22; // 声明并初始化 z
String s = "runoob"; // 声明并初始化字符串 s
double pi = 3.14159; // 声明了双精度浮点型变量 pi
char x = 'x'; // 声明变量 x 的值是字符 'x'。

Variables are divided according to scope: class variables, instance variables, local variables

  1. Class variable (static variable: static variable): Variables independent of methods, modified with static.

    ​ Subordinate to the class, the life cycle is always accompanied by the class , from the loading of the class to the unloading.

  2. Instance variables (member variables: member variable): variables independent of methods , but without static modification.

    Method outside the class defined inside variables. Subordinate to the object, the life cycle is always accompanied by the object.

  3. Local variable (lacal variable): The variable in the method of the class .

    The method or internal variables defined statement block. The life cycle is from the declaration position to " } ".

    [Note] Local variables have no default value, and must be declared and initialized (assigned initial value) before use.

    public class Variable{
          
          
    	static int allClicks=0; // 类变量
    	String str="hello world"; // 实例变量
    
        public void method(){
          
          
    		int i =0; // 局部变量
    	}
    }
    

constant

Constant: Its value will not change after initialization!

The so-called constant can be understood as a special variable. After its value is set, it is not allowed to be changed during the running of the program.

Constant declaration format : final constant name = value.

Example:

final double PI = 3.1415926;
final String NAME = "Crown"; 

Variable naming convention:

  1. Class member variables: first letter lowercase and camel case principle: monthSalary
  2. Local variables: lowercase initials and camel case
  3. Constant: all uppercase letters and underscore: MAX_VALUE
  4. Class name: initial capitalization and camel case principle: Man, GoodMan
  5. Method name: lowercase initials and camel case principle: run(), runRun()

Operator

The Java language supports the following operators:

  • Arithmetic operators: +, -, *, /, %, ++, –
  • Assignment operator: =
  • Relational operators: >, <, >=, <=, ==, !=, instanceof
  • Logical operators: &&, ||,!
  • Bitwise operators: &, |, ^, ~, >>, <<, >>> (Understand!!!)
  • Conditional operator:? :
  • Extended assignment operators: +=, -=, *=, /=

1. Unary operator

One operand.

**Increment (++) and Decrease (–)** operator is a special arithmetic operator, divided into two types: prefix and suffix.

public static void main(String[] args) {
    
    
	int a = 3;
	int b = a++; //执行完后,b=3。先给b赋值,再自增。
	int c = ++a; //执行完后,c=5。先自增,再给b赋值。
}

2. Binary operators

Two operands.

public static void main(String[] args) {
    
    
	int a = 10;
	int b = 20;
	int c = 25;
	int d = 25;
	System.out.println("a + b = " + (a + b) );//a + b = 30
	System.out.println("a - b = " + (a - b) );//a - b = -10
	System.out.println("a * b = " + (a * b) );//a * b = 200
	System.out.println("b / a = " + (b / a) );//b / a = 2
} 
  • In integer operation, there is a long type, and the result is long,

    ​ There is no long type, and the result is int.

  • In floating-point operations, if one of the two operands is a double, the result is a double.

    ​ Only if both operands are float, the result is float.

  • Relational operators, >, <, >=, <=, ==,!=, instanceof, return boolean value (true, false)

  • Modulo operation (take the remainder):

    ​ The operand can be a floating-point number, generally an integer is used. For example: 5.9% 3.9 = 2.000000004

Using BigDecimal can avoid errors in its results.

public static void main(String[] args) {
    
    
	System.out.println(9 % 4); //1
	System.out.println(-9 % -4); //-1 ; 负数%负数=负数
	System.out.println(-10 % 4); //-2 ; 负数%正数=负数
	System.out.println(9 % -4); //1 ; 正数%负数=正数
}
  • Logical Operators

    ​ Logic and &&, the same truth is true.

    ​ Logical or ||, one true is true.

    ​ Logical negation!.

    public static void main(String[] args){
          
          
    	int a = 5;//定义一个变量;
    	boolean b = (a<4)&&(a++<10);
    	System.out.println("使用短路逻辑运算符的结果为"+b);
                          //使用短路逻辑运算符的结果为false
    	System.out.println("a的结果为"+a);
    }                     //a的结果为5
    

    ​ This program uses the short-circuit logic operator (&&), first judge the result of a<4 to be false, then the result of b must be false, so the second operation a++<10 is no longer executed, so the value of a 5.

    ​ Logic and logic or use short circuit . Calculated from left to right, as long as one of the logical AND is false, it will directly return false; if the logical OR is true, it will directly return true; at this time, the second operation will not be judged.

Bitwise operator

Bit operators are used to operate on binary bits

A = 0011 1100
B = 0000 1101
================
A & B = 0000 1100
A | B = 0011 1101
A ^ B = 0011 0001
~ A = 1100 0011
Operator description example
& Bitwise AND, if the corresponding bits are all 1, the result is 1, otherwise it is 0 (A&B)= 12,即0000 1100
| Bitwise OR, if the corresponding bits are all 0, the result is 0, otherwise it is 1 (A|B) = 61, which is 0011 1101
^ Bitwise XOR, the corresponding bit value is the same, the result is 0, otherwise it is 1 (A^B)= 49, which is 0011 0001
~ The bitwise negation operator, that is, 0 becomes 1, and 1 becomes 0. (~A) = -61, which is 1100 0011
<< The bitwise left shift operator, the left operand is bitwise shifted to the left by the number of bits specified by the right operand . A << 2 = 240,即1111 0000
>> Bitwise right shift operator, the left operand is bitwise shifted right by the number of bits specified by the right operand . A >> 2 = 15,即1111
>>> The bitwise right shift zero - fill operator, the left operand is bitwise shifted right by the number of bits specified by the right operand , and the space obtained by the shift is filled with 0. A >>> 2 = 15,即0000 1111

Shifting one bit to the left is equivalent to multiplying by 2, and shifting one bit to the right is equivalent to dividing by 2 to get the quotient.

[Interview Questions Expansion] How does 2*8 have the fastest calculation efficiency?

public static void main(String[] args) {
    
    
	System.out.println(2 << 3);
}

2 * 8 What operational efficiency fastest

Spread operator

Operator Usage example Equivalent expression
+ = a += b a = a + b
- = a -= b a = a - b
* = a *= b a = a * b
/ = a /= b a = a / b
% = a %= b a = a % b

3. Ternary conditional operator (?:)

Ternary conditional operator, syntax format:

x ? y : z;

Where x is a boolean type expression, the value of x is calculated first. If x is true, the result is y, otherwise it is z.

Example:

public static void main(String[] args) {
    
    
	int score = 80;
	String type = score < 60 ? "不及格" : "及格";
	System.out.println("type= " + type);
}

Package

In order to organize classes better, Java provides a package mechanism for distinguishing the namespace of class names.

A package can be defined as a set of interconnected types (classes, interfaces, enumerations, and annotations) to provide access protection and namespace management functions for these types.

The role of the package

1. Organize classes or interfaces with similar or related functions in the same package to facilitate the search and use of classes.

2. Like folders, packages also use a tree-shaped directory storage method. Class names in the same package are different, and the names of classes in different packages can be the same. When calling classes with the same class name in two different packages at the same time, the package name should be added to distinguish them. Therefore, the package can avoid name conflicts.

3. The package also restricts access rights, and only classes with package access rights can access classes in a package. Java uses the package mechanism to prevent naming conflicts, access control, and provide search and location classes, interfaces, enumerations, and annotations.

The syntax format of the package statement is:

package pkg1[.pkg2[.pkg3...]];

Example: A Something.java file

package net.java.util;
	public class Something{
    
    
...
}

Then its path should be saved as net/java/util/Something.java. The function of package is to classify and save different java programs, making it easier to be called by other java programs.

Here are some packages in Java:

java.lang-package basic classes

java.io-functions that include input and output functions

Developers can package a set of classes and interfaces by themselves, and define their own packages. After completing the implementation of the class, grouping related classes can make it easier for other programmers to determine which classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace, it will not conflict with any names in other packages. Using the package mechanism makes it easier to implement access control and makes it easier to locate related classes.

Create package

When creating a package, you need to give the package a suitable name. Later, if another source file contains the classes, interfaces, enumerations, or annotation types provided by this package, the package declaration must be placed at the beginning of the source file.

The package declaration should be on the first line of the source file. Each source file can only have one package declaration, and each type in this file applies to it.

If a package declaration is not used in a source file, then the classes, functions, enumerations, comments, etc. will be placed in an unnamed package.

Generally use company domain name inversion as registration; for example:

www.baidu.com Package name: com.baidu.www

bbs.baidu.com Package name: com.baidu.bbs

blog.baidu.com Package name: com.baidu.blog

import keyword

In order to be able to use a member of a package, we need to explicitly import the package in the Java program. Use the "import" statement to complete this function.

In the java source file, the class file can contain any number of import statements. The import statement should be located after the package statement and before the class statement. The syntax format is:

import package1[.package2...].(classname|*);

If in a package, a class wants to use another class in this package, then the package name (package) can be omitted.

If you want to use classes in other packages, you must import the package!

Use the import keyword to import, use the wildcard "*" to import all the classes under the io package!

import java.io.*;

[It is not recommended to use this way, because it will scan globally and affect the speed!

JavaDoc

JavaDoc is a technology for generating HTML documents from comments. The generated HTML documents are similar to Java APIs, which are easy to read and clear.

Javadoc is a technology provided by Sun. It extracts annotations such as classes, methods, and members from the program source code to form an API help document that matches the source code.

/** 这是一个Javadoc测试程序
 * @author 明天也有晚霞嘛
 * @version 1.0
 * @since 1.5
 * */
public class HelloWorld {
    
    
	public String name;
	/**
	 * @param name 姓名
	 * @return 返回name姓名
	 * @throws Exception 无异常抛出
	 * */
	public String function(String name) throws Exception{
    
    
		return name;
	}
}

Start with /* and end with /.

@author author name

@version version number

@since indicates the jdk version that needs to be used earliest

@param parameter name

@return Return value situation

@throws exception throw situation

Generate JavaDoc from the command line

The javadoc command in the command line is used to generate your own API documentation;

Usage: Use the command line to enter javadoc + file name.java in the directory where the target file is located. E.g:

Open the command line to the specified path of the file, enter javadoc **-encoding UTF-8 -charset UTF-8 **HelloWorld.java

-encoding UTF-8 -charset UTF-8
//解决GBK乱码问题,在中间添加编码设置

At this time, the index.html file generated in the HelloWorld.java storage path is the target file (document comment).

IDEA generates JavaDoc

IDEA generates JavaDoc


```java
在这里插入代码片

Guess you like

Origin blog.csdn.net/weixin_46330563/article/details/114769244