Summary of Java Basics

I always think of beginners in my spare time java The basics of learning,
However, it seems that yesterday's basic knowledge sometimes can't remember its principle and knowledge points.
So review the summary notes again. Encourage each other!!!
At the same time, find the feeling of learning!!!

1, Introduction to Java

  Java is between a compiled language and an interpreted language. Compiled languages, such as C and C + +, are directly compiled into machine code for execution, but the instruction sets of CPUs on different platforms (x86, ARM, etc.) are different. Therefore, it is necessary to compile the corresponding machine code of each platform. Interpretative languages such as Python and Ruby do not have this problem. The interpreter can directly load the source code and run it at the cost of low efficiency. Java compiles the code into a "bytecode", which is similar to abstract CPU instructions. Then, write virtual machines for different platforms, which are responsible for loading and executing bytecode. In this way, the effect of "writing once and running everywhere" is realized. Of course, this is for Java developers. For virtual machines, they need to be developed separately for each platform. In order to ensure that virtual machines developed by different platforms and companies can correctly execute Java bytecode, SUN has formulated a series of Java virtual machine specifications. From a practical point of view, the compatibility of the JVM is very good, and the low version of Java bytecode can run normally on the high version of the JVM.

Java classification:

  • Java se: is the foundation of the other two.
  • JavaME: a small version of the Java language, which is used for the development of embedded consumer electronic devices or mobile devices.
  • Java EE: Web site development for web methods. (mainly engaged in the development of background server)

What is the relationship between the three:

  • JDK: used to write code. It contains development tools and JRE.
  • JRE: used to run code. It contains some things and JVM s that need to be used during runtime.
  • JVM: in fact, it is a translation and the place where the code really runs.

Inclusion relationship: JDK > JRE > JVM

   you can query other relevant information about the download of JDK and the configuration of environment variables, but there are still many.

   the following nonsense is not much, so we can directly summarize the basis.

2, Java program foundation

Basic grammar

Guys, remember the first code you wrote?

The author's first code“ Hello World"
/**
 * Comments that can be used to automatically create documents
 */
public class Demo001 {
    public static void main(String[] args) {
        // Output text to screen:
        System.out.println("Hello  world!");
        /* Multiline comment start
        Note Content 
        End of comment */
    }
} // End of class definition

Storage unit

  first of all, we should know that data is stored in binary form.

  the smallest storage unit is byte.

bit: a 0 or a 1 in binary. (bits)

   but there is too little content represented by a bit. So we will divide the 8 bits into a group. This group is called byte. (bytes)

This byte is the smallest storage unit in the computer.

Conversion relationship between KB, MB, GB and TB

  • 8 bits = 1 byte
  • 1024 bytes = 1KB
  • 1024KB = 1MB
  • 1024MB = 1GB
  • 1024GB = 1TB

This paper briefly introduces the concepts of class, object, method and instance variable

  • Object: an object is an instance of a class with state and behavior. For example, a dog is an object, and its status includes: color, name and variety; Behaviors include wagging tail, barking, eating, etc.
  • Class: a class is a template that describes the behavior and state of a class of objects.
  • Method: method is behavior. A class can have many methods. Logical operation, data modification and all actions are completed in the method.
  • Instance variables: each object has unique instance variables, and the state of the object is determined by the values of these instance variables.

Basic data types in Java (four types and eight types)

  • Integer type: byte short int long
  • Floating point type: float double
  • Character type: char
  • boolean type: boolean

Bytes occupied, default value and value range:

data typeNumber of bytes occupiedDefault valueValue range
byte10-128 ~ 127
short20-32768 ~ 32767
int40-2147483648 ~ 2147483647
long80-2^63 ~ 2^63-1
float40.0fIndex bit: 2 ^ (- 127) ~ 2 ^ 128
double80.0dIndex bit: 2 ^ (- 1023) ~ 2 ^ 1024
char2"\u0000 "0~65535
boolean1falsefalse and true

   note: Although boolean shows the "bit" characteristic of non-0 or 1, the basic unit of measurement of storage space is byte, not bit, so boolean accounts for at least 1 byte. In the JVM specification, boolean variables are treated as int, that is, 4 bytes; The boolean array is treated as a byte array, that is, each element in the boolean array occupies one byte.

There are three reference types: Class, Interface and Array.

   reference types are generally new, such as Integer max = new Integer(); It is stored in the memory heap, which can dynamically allocate the memory size at runtime, and the lifetime does not need to tell the compiler in advance. When the reference type variable is not used, the garbage collector GC in Java will automatically recycle it. What is stored in the reference variable is not the content of the variable, but the address where the content of the variable is stored.

Mandatory provisions for identifiers

  • All identifiers should be in letters (a-z or a-z), dollar sign ($), or underscore () start
  • The first character can be followed by letters (a-z or a-z), dollar sign ($), underscore () Or any character combination of numbers
  • Keywords cannot be used as identifiers
  • Identifiers are case sensitive
  • Examples of legal identifiers: age, $salary_ value,__ 1_value
  • Examples of illegal identifiers: 123abc, - salary

Implicit conversion

   assign the value with small range to the value with large range.

  1. Look to the right of the equal sign, if the right of the equal sign is an integer constant. Then the constant optimization mechanism of integer is triggered.
  2. If there are decimals or variables on the right of the equal sign, it depends on the data type to decide how to promote. (implicit conversion)

   if it is smaller than int, convert it to int first, and then calculate.
   if it is larger than int, it will turn to the one with the largest value range.

Force conversion

   assign a value with a large value range to a value with a small value range. (hard plug) Note: it may cause the loss of accuracy. (the number may be different from the original number)

Java keyword

categorykeywordexplain
access control privatePrivate
protectedProtected
publicPublic
defaultdefault
Class, method, and variable modifiersabstractDeclarative abstraction
classclass
extendsExtension, inheritance
finalFinal value, immutable
implementsImplementation (Interface)
interfaceInterface
nativeNative, native method (non java implementation)
newNew, create
staticstatic state
strictfpStrict and accurate
synchronizedThread, synchronization
transienttransient
volatileVolatile
Program control statementbreakJump out of loop
caseDefine a value for switch to choose from
continuecontinue
defaultdefault
dofunction
elseotherwise
forloop
ifIf
instanceofexample
returnreturn
switchSelect execution based on value
whileloop
error handlingassertWhether the assertion expression is true
catchCatch exception
finallyExecute all exceptions
throwThrow an exception object
throwsDeclaring an exception may be thrown
tryCatch exception
Package relatedimportintroduce
packagepackage
Basic typebooleanBoolean type
byteByte type
charcharacter
doubleDouble precision floating point
floatSingle precision floating point
intinteger
longLong integer
shortShort
Variable referencesuperSuperclass
thisThis category
voidNo return value
Reserved keywordsgotoIs a keyword, but cannot be used
constIs a keyword, but cannot be used
nullempty

Special escape characters

SymbolCharacter meaning
\nLine feed (0x0a)
\rEnter (0x0d)
\fPage feed (0x0c)
\bBackspace (0x08)
\0Null character (0x0)
\sSpace (0x20)
\tTab
"Double quotation mark
'Single quotation mark
\Backslash
\dddOctal character (ddd)
\uxxxxHexadecimal Unicode character (xxxx)

placeholder

placeholder explain
%dFormat output integer
%xFormat output hexadecimal integer
%fFormat output floating point number
%eFormat and output the floating-point number represented by scientific counting method
%sformat string

Note that since% represents a placeholder, two consecutive%% represent a% character itself.

Arithmetic operator

+ - * / %

Operation rules:

The primary school is as like as two peas.

Division is different from before.

  • In Java, if you divide integers, you can only get integers.
  • In Java, if you divide decimals, the result may be inaccurate.
// Division operator 
// 1. How to type the division operator in the code 
// 2. Details of division in the code 
int a1 = 10; 
int b1 = 2; 
int result1 = a1 / b1; 
System.out.println(result1); //5

//In Java, if you divide integers, you can only get integers. 
int a2 = 10; 
int b2 = 3; 
int result2 = a2 / b2; 
System.out.println(result2);//3 

//In Java, the result of dividing decimals may be inaccurate. 
//If we want to calculate accurately, we will learn again in the employment class. 
double a3 = 10.0; 
double b3 = 3.0; 
double result3 = a3 / b3; 
System.out.println(result3);//3.3333333333333335


// %Take remainder and mold 
int a = 10; 
int b = 2; 
int result = a % b; 
System.out.println(result);//0 
//Because 10 divided by 2 is divisible, quotient 5 is more than 0 
//%The remainder is obtained, so the result is 0

// %Take remainder and mold 
int a = 10; 
int b = 3; 
int result = a % b; 
System.out.println(result);//1 
//Because 10 divided by 3 is not divisible, so quotient 3 is 1 
//%The remainder is obtained, so the result is 1

Get the last digit, ten digit and hundred digit formula of a number:

  • If you want to get bits of a number: number% 10
  • If you want to get the ten digits of a number: number / 10% 10
  • If you want to get the hundredth of a number: number / 100% 10
  • If you want to get the thousands of a number: number / 1000% 10
  • If you want to get 10000 bits of a number: number / 10000% 10

Assignment Operators

Operatordescribeexample
=A simple assignment operator that assigns the value of the right operand to the left operandAssign the value of C = a + to B
+ =The addition assignment operator, which adds the left and right operands and assigns them to the left operandC + = A is equivalent to C = C + A
- =Subtraction and assignment operator, which subtracts the left operand from the right operand and assigns it to the left operandC - = A is equivalent to C = C - A
* =Multiplication and assignment operator, which multiplies the left and right operands and assigns values to the left operandC * = A is equivalent to C = C * A
/ =The division and assignment operator, which divides the left and right operands and assigns them to the left operandC / = A, C is equivalent to C = C / A when it is of the same type as A
(%)=Modulo and assignment operator, which assigns the left and right operands to the left operand after moduloC% = A is equivalent to C = C% A
<< =Left shift assignment operatorC < < = 2 is equivalent to C = C < < 2
>> =Right shift assignment operatorC > > = 2 is equivalent to C = C > > 2
&=Bitwise and assignment operatorsC & 2 is equivalent to C = C & 2
^ =Bitwise exclusive or assignment operatorC ^ = 2 is equivalent to C = C ^ 2
A=Bitwise or assignment operatorC = 2 is equivalent to C = C

=: assign the right to the left.
+=: add the left and right, and then assign the final result to the left. The underlying layer contains a cast type.

byte a = 1; 
byte b = 2; 
a+=b; 
//a+=b, equivalent to a = (byte)(a + b); 
//+=The underlying layer implies a cast
public class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 0;
        c = a + b;
        System.out.println("c = a + b = " + c );
        c += a ;
        System.out.println("c += a  = " + c );
        c -= a ;
        System.out.println("c -= a = " + c );
        c *= a ;
        System.out.println("c *= a = " + c );
        a = 10;
        c = 15;
        c /= a ;
        System.out.println("c /= a = " + c );
        a = 10;
        c = 15;
        c %= a ;
        System.out.println("c %= a  = " + c );
        c <<= 2 ;
        System.out.println("c <<= 2 = " + c );
        c >>= 2 ;
        System.out.println("c >>= 2 = " + c );
        c >>= 2 ;
        System.out.println("c >>= 2 = " + c );
        c &= a ;
        System.out.println("c &= a  = " + c );
        c ^= a ;
        System.out.println("c ^= a   = " + c );
        c |= a ;
        System.out.println("c |= a   = " + c );
    }
}

Self increasing and self decreasing operator

++: add the value in the variable + 1
–: set the value in the variable to - 1

a++; Post + +: add later, use first, participate in the operation first, and then increase automatically.
++a; First + +: add first and then use. First increase by itself, and then participate in the operation of the result after the increase by itself.

int x = 10; 
//First take out the original value to participate in the operation, and then increase it by itself 
//First take out the original value 10 and assign it to y, and then increase it by itself, so after the execution of the second line of code: x = 11, y = 10 
int y = x++; 

//At the beginning of the third line of code, the value of x is 11 
//Self increment is performed first, and then the results of self increment are involved in the operation 
//First, the value of X is self incremented to 12, and then the self incremented result is assigned to Z. So after the third line of code is executed: x = 12, z = 12 
int z = ++x; 

//Because it has increased twice, the value of x is 12 
System.out.println(x);//12 
System.out.println(y);//10 
System.out.println(z);//12

Relational operator

operatordescribe
==Checks whether the values of the two operands are equal. If they are equal, the condition is true
!=Check if the values of the two operands are equal, and if the values are not equal, the condition is true
>Check whether the value of the left operand is greater than the value of the right operand. If so, the condition is true
<Check whether the value of the left operand is less than the value of the right operand. If so, the condition is true
>=Check whether the value of the left operand is greater than or equal to the value of the right operand. If so, the condition is true
<=Check whether the value of the left operand is less than or equal to the value of the right operand. If so, the condition is true

Never write = = as =:

  • ==It's judgment
  • =Is assignment
public class Test {
 
  public static void main(String[] args) {
     int a = 10;
     int b = 20;
     System.out.println("a == b = " + (a == b) );
     System.out.println("a != b = " + (a != b) );
     System.out.println("a > b = " + (a > b) );
     System.out.println("a < b = " + (a < b) );
     System.out.println("b >= a = " + (b >= a) );
     System.out.println("b <= a = " + (b <= a) );
  }
}

Bitwise Operators

Operatordescribeexample
If the corresponding bits are all 1, the result is 1, otherwise it is 0(A & B), get 12, i.e. 0000 1100
AIf the corresponding bits are all 0, the result is 0, otherwise it is 1(A
^If the corresponding bit values are the same, the result is 0, otherwise it is 1(A ^ B) get 49, i.e. 0011 0001
~The bitwise negation operator flips each bit of the operand, that is, 0 becomes 1 and 1 becomes 0(? A) get - 61, i.e. 1100 0011
<<Bitwise shift left operator. Left operand shifts left by bits the number of bits specified by the right operandA < < 2 gets 240, i.e. 1111 0000
>>Bitwise shift right operator. Left operand shifts right bit by bit the number of bits specified by the right operandA > > 2 gets 15, i.e. 1111
>>>Bitwise shift right zeroing operator. The value of the left operand is shifted to the right by the number of bits specified by the right operand, and the empty bits obtained by moving are filled with zerosA> > > 2 gets 15, i.e. 0000 1111
public class Test {
  public static void main(String[] args) {
     int a = 60; /* 60 = 0011 1100 */ 
     int b = 13; /* 13 = 0000 1101 */
     int c = 0;
     c = a & b;       /* 12 = 0000 1100 */
     System.out.println("a & b = " + c );
 
     c = a | b;       /* 61 = 0011 1101 */
     System.out.println("a | b = " + c );
 
     c = a ^ b;       /* 49 = 0011 0001 */
     System.out.println("a ^ b = " + c );
 
     c = ~a;          /*-61 = 1100 0011 */
     System.out.println("~a = " + c );
 
     c = a << 2;     /* 240 = 1111 0000 */
     System.out.println("a << 2 = " + c );
 
     c = a >> 2;     /* 15 = 1111 */
     System.out.println("a >> 2  = " + c );
  
     c = a >>> 2;     /* 15 = 0000 1111 */
     System.out.println("a >>> 2 = " + c );
  }
} 

Logical operator

& | ! ^ && ||

The user name is correct && The password is correct 
//If the user name has been entered incorrectly, there is no need to execute the password// If the user name is entered correctly, the password is necessary. 

The user name is correct & The password is correct 
//Whether your user name is entered correctly or incorrectly, the password on the right will be compared.

Short circuit &, once the left side can determine the final result, the right side will not execute.

Short circuit. Once the final result can be determined on the left, there is no need to execute on the right.

Ternary expression

Format: relational expression? Expression 1: expression 2;

  • First, evaluate the value of the relationship expression. This value must be a boolean result.
  • If true, the result of expression 1 is the result of the entire ternary expression.
  • If false, the result of expression 2 is the result of the entire ternary expression.
//Define three variables to record the height of three monks 
int height1 = 150; 
int height2 = 210; 
int height3 = 165; 
//First compare the height of the first and the second. Get a larger value. 
int temp = height1 > height2 ? height1 : height2; 
//Take the larger value and compare it with the third one. Get the maximum value. 
int max = temp > height3 ? temp : height3; 
//Maximum output 
System.out.println(max);

3, Modifier

It is mainly divided into two categories:

  • Access modifier
  • Non access modifier

Access control modifier:

  access control characters to protect access to classes, variables, methods and construction methods

  • default: visible in the same package without any modifiers. Use objects: classes, interfaces, variables, methods.
  • private: visible in the same category. Use object: variable, method. Note: cannot decorate class (external class)
  • public: visible to all classes. Objects used: classes, interfaces, variables, methods
  • protected: visible to classes and all subclasses in the same package. Use object: variable, method. Note: you cannot decorate classes (external classes).
Modifier Current classIn the same bagDescendants (same package)Descendants (different packages)Other packages
publicYYYYY
protectedYYYY/NN
defaultYYYNN
privateYNNNN

Access control and inheritance

  • Methods declared public in the parent class must also be public in the child class.
  • Methods declared as protected in the parent class are either declared as protected or public in the child class, and cannot be declared as private.
  • Methods declared as private in the parent class cannot be inherited.

Non access modifier

  • static modifier, used to modify class methods and class variables.

  • final modifier, used to modify classes, methods and variables
    Modified classes cannot be inherited, modified methods cannot be redefined by inherited classes, and modified variables are constants and cannot be modified.

  • Abstract modifier to create abstract classes and methods.

  • synchronized and volatile modifiers are mainly used for thread programming.

static modifier

  • Static variables:

   static keyword is used to declare static variables independent of objects. No matter how many objects a class instantiates, there is only one copy of its static variables. Static variables are also called class variables. Local variables cannot be declared as static variables.

  • Static method:

  static keyword is used to declare static methods independent of objects. Static methods cannot use non static variables of a class. The static method obtains the data from the parameter list, and then calculates the data.

public class InstanceCounter {
   private static int numInstances = 0;
   protected static int getCount() {
      return numInstances;
   }
 
   private static void addInstance() {
      numInstances++;
   }
 
   InstanceCounter() {
      InstanceCounter.addInstance();
   }
 
   public static void main(String[] arguments) {
      System.out.println("Starting with " +
      InstanceCounter.getCount() + " instances");
      for (int i = 0; i < 500; ++i){
         new InstanceCounter();
          }
      System.out.println("Created " +
      InstanceCounter.getCount() + " instances");
   }
}

final modifier

  • final variable:

   final means "last and final". Once a variable is assigned, it cannot be re assigned. The instance variable modified by final must explicitly specify the initial value.

The   final modifier is usually used with the static modifier to create class constants.

public class Test{
  final int value = 10;
  // The following is an example of declaring constants
  public static final int BOXWIDTH = 6;
  static final String TITLE = "Manager";
 
  public void changeValue(){
     value = 12; //An error will be output
  }
}
  • final method

   the final method in the parent class can be inherited by the subclass, but cannot be overridden by the subclass.

  the main purpose of declaring the final method is to prevent the content of the method from being modified.

   as shown below, use the final modifier to declare the method.

public class Test{
    public final void changeName(){
       // Method body
    }
}
  • final class

   final class cannot be inherited. No class can inherit any features of final class.

public final class Test {
   // Class body
}

abstract modifier

  • Abstract class:

  abstract classes cannot be used to instantiate objects. The only purpose of declaring abstract classes is to expand them in the future.

  a class cannot be modified by abstract and final at the same time. If a class contains abstract methods, the class must be declared as an abstract class, otherwise a compilation error will occur.

  abstract classes can contain abstract and non abstract methods.

abstract class Caravan{
   private double price;
   private String model;
   private String year;
   public abstract void goFast(); //Abstract method
   public abstract void changeColor();
}
  • Abstract method

   abstract method is a method without any implementation. The specific implementation of the method is provided by subclasses.

  abstract methods cannot be declared as final and static.

  any subclass that inherits from an abstract class must implement all abstract methods of the parent class unless the subclass is also an abstract class.

  if a class contains several abstract methods, the class must be declared as an abstract class. Abstract classes can contain no abstract methods.

   the declaration of an abstract method ends with a semicolon, for example: public abstract sample();.

public abstract class SuperClass{
    abstract void m(); //Abstract method
}
 
class SubClass extends SuperClass{
     //Implement abstract methods
      void m(){
          .........
      }
}

synchronized modifier

The method declared by the   synchronized keyword can only be accessed by one thread at a time. The synchronized modifier can be applied to four access modifiers.

public synchronized void showDetails(){
.......
}

transient modifier

   when the serialized object contains an instance variable modified by transient, the java virtual machine (JVM) skips the specific variable.

The modifier used to define the data type of the variable is included in the statement.

public transient int limit = 55;   // Not persistent
public int b; // Persistence

volatile modifier

Each time a member variable modified by volatile is accessed by a thread, the value of the member variable is forced to be re read from the shared memory. Moreover, when the member variable changes, the thread will be forced to write the change value back to the shared memory. In this way, at any time, two different threads always see the same value of a member variable.

  a volatile object reference may be null.

public class MyRunnable implements Runnable
{
    private volatile boolean active;
    public void run()
    {
        active = true;
        while (active) // first line
        {
            // code
        }
    }
    public void stop()
    {
        active = false; // Second line
    }
}

   usually, the run() method is called in one thread (the thread opened in Runnable) and the stop() method is called in another thread. If the active value of the buffer in the first line is used, the loop will not stop when the active value in the second line is false.

   but the above code uses volatile to modify active, so the loop will stop.

4, Input and output

  • output

  in the previous code, always use system out. Println () to output some content.

   println is the abbreviation of print line, which means output and line feed. Therefore, if you don't want to wrap lines after output, you can use print():

public class Main {
    public static void main(String[] args) {
        System.out.print("A,");
        System.out.print("B,");
        System.out.print("C.");
        System.out.println();
        System.out.println("END");
    }
}
  • input

Guide Package: tell the virtual machine where the Scanner class is.
Create object: say hello, I'm ready to start using this class now.
Receiving data: code that really works

//1. Package Guide - tell the virtual machine where the Scanner class is? 
import java.util.Scanner; 

public class ScannerDemo{ 
	public static void main(String [] args){
		 //2. Create an object - say hello and start using this class. 
		 Scanner sc = new Scanner(System.in); 
		 //3. Receiving data is the function of using this class 
		 System.out.println("Please enter a number"); 
		 int number = sc.nextInt(); 
		 //Output the variable just entered on the keyboard 
		 System.out.println("The data just entered is:"+number); 
	} 
}

Note:

  • sc.nextInt(); You can only accept integers, not decimals or strings.
  • If you enter a decimal or string, the program will report an error.

Avoid entering the pit

1, The methods involved in keyboard entry are as follows:

​ next(),nextLine(),nextInt(),nextDouble()

The bottom layer is very troublesome. It is suggested to look directly at the final conclusion.

Of which:

1)next(),nextLine():

   any data can be accepted, but a string will be returned.

    for example, if abc is entered on the keyboard, abc will be returned as a string.

   enter 123 on the keyboard, and 123 will be returned as a string.

Code example:

Scanner sc = new Scanner(System.in);
String s = sc.next();//All data entered will be regarded as strings
System.out.println(s);

Code example:

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();//All data entered will be regarded as strings
System.out.println(s);

2)nextInt():

Only integers can be accepted.

For example, if you enter 123 on the keyboard, 123 will be returned as an integer of type int.

If you enter decimals or other letters on the keyboard, an error will be reported.

Code example:

Scanner sc = new Scanner(System.in);
int s = sc.nextInt();//Only integers can be entered
System.out.println(s);

3)nextDouble():

Can receive integers and decimals, but will be returned as decimals.

An error will be reported when entering letters.

Code example:

Scanner sc = new Scanner(System.in);
double d = sc.nextDouble();//The entered integer and decimal will be regarded as decimal.
						//Errors will be reported when entering letters
System.out.println(d);

2, Method bottom level details:

First detail:

   next(), nextInt(), nextDouble() will encounter spaces when receiving data. Enter and one of the tabs will stop receiving data.

Code example:

Scanner sc = new Scanner(System.in);
double d = sc.nextDouble();
System.out.println(d);
//Keyboard entry: 1.1 2.2 / / pay attention to adding a space between 1.1 and 2.2 when entering.
//At this time, the console prints 1.1
//Indicates that the nextDouble method stops when it encounters a space when receiving data, and the subsequent methods will not be received this time.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println(i);
//Keyboard entry: 1 2 / / pay attention to adding a space between 1 and 2 when entering.
//The console prints 1
//It means that the nextInt method stops when it encounters a space when receiving data, and the following will not be received this time.
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(s);
//Keyboard entry: a b / / note that a space is added between a and b during entry.
//The console prints a
//Indicates that when the next method receives data, it stops when it encounters a space, and the following will not be received this time.

Second detail:

   next(), nextInt(), nextDouble() will encounter spaces when receiving data. Enter and one of the tabs will stop receiving data. However, the data behind these symbols + is still in memory and is not received. If there are other keyboard entry methods, these data will be received automatically.

Code example:

Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String s2 = sc.next();
System.out.println(s1);
System.out.println(s2);
//At this time, enter a and b with the keyboard (note that a and b are separated by spaces)
//Then the first next(); A will be received. If a is followed by a space, it will stop, so printing s1 is a
//But the space + b is still in memory.
//The second next will remove the preceding space and only receive b
//So the second s2 print out is b

Third detail:

The   nextLine() method is to receive the whole line.

Code example:

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s);
//Enter a and b on the keyboard (note that a and b are separated by spaces)
//Then nextLine will not filter the front and back spaces, and will receive the whole line of data.

3, Conclusion (how to use)

Keyboard entry is divided into two sets:

  • next(), nextInt(), and nextDouble().

If you use one of these three, don't use nextLine ().

  • nextLine() is used alone.

   if you want an integer, receive it first and then use integer ParseInt for type conversion.

Code example:

Scanner sc = new Scanner(System.in);
String s = sc.next();//Keyboard entry 123
System.out.println("This is a string" + s);//At this point, 123 is a string
int i = sc.nextInt();//Keyboard entry 123
System.out.println("This is an integer:" + i);
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();//Keyboard entry 123
System.out.println("This is a string" + s);//At this point, 123 is a string
int i = Integer.parseInt(s);//Want to convert to an integer
System.out.println("This is an integer:" + i);

4, Consequences caused by mixing

   the two sets of keyboard input mentioned above cannot be mixed. If mixed, there will be serious consequences.

Code example:

Scanner sc = new Scanner(System.in);//①
int i = sc.nextInt();//②
String s = sc.nextLine();//③
System.out.println(i);//④
System.out.println(s);//⑤

   when the code runs to the second line, we will enter it with the keyboard, and then enter 123.

  but actually we recorded 123 + return.

    nextInt stops when you encounter spaces, enter, and tabs.

   therefore, nextInt can only accept 123, and carriage return is not received in memory.

  it is received by nextLine at this time.

  therefore, if mixed, nextLine will not receive data.

Keywords: Java Back-end

Added by zesoft.net on Sun, 20 Feb 2022 02:11:48 +0200