Java Basics
First acquaintance with Java
-
Java is a high-level programming language. It is an object-oriented and static programming language
-
Java contains JDK, JRE and JVM. Where JVM is a Java virtual machine. JRE is the running environment. JDK is a development kit
-
Java program structure. Three steps in total. Write source code, compile and run
public class Demo{ public static void main(String args[]){ System.out.println("Helloworld"); } }
Variables and data types
type | name | Occupied bytes |
---|---|---|
byte | Byte integer | 1 |
short | Short | 2 |
int | integer | 4 |
long | Long integer | 8 |
float | Single-precision floating-point | 4 |
double | Double precision floating point number | 8 |
boolean | Boolean | 1 |
char | character | 2 |
Different bytes represent different space occupied, so the data length can be represented is different. Generally speaking, int is used for integers and double is used for decimals. You need to add f when you use float. Because the default is double. To use long, you need to add l. Because the default is int
public class Demo{ public static void main(String args[]){ byte a = 100; short c = 20; int b = 10; long d = 10000; float e = 10.0f; double r = 20.0; } }
Console inputs and outputs
-
What is it?
- It is used to receive the data entered by the user through the keyboard and store it in the variable.
-
Why
- In order to receive data from users, generally speaking, such as the registration form (your account password needs to be entered). (of course, the registration form is a web page).
-
When
- ditto
-
How to use it?
- Import package import Java util. Scanner;
- Create Scanner object Scanner scan = new Scanner();
- Call his method to receive data through scan.
import java.util.Scanner; public class Demo1 { public static void main(String[] args) { // For example, my system needs users to register // Let the user register, you need the user to fill in his information. // For example, there is an account, password and confirm password. // Generally, the account and password are in English plus numbers, which is also a string type Scanner scan = new Scanner(System.in); System.out.println("Please enter your favorite account name"); String username = scan.next(); System.out.println("Please enter your password"); String password = scan.next(); System.out.println("Please confirm your password"); String rePass = scan.next(); if(password.equals(rePass)){ System.out.println("Registration succeeded. Your account is:"+username+"Your password is"+password); }else { System.out.println("Your two passwords are different. Please re-enter them"); } } }
Operation of data
- Operator, as the name suggests, is the symbol used for calculation.
- Operators in the Java language
- It is divided into assignment operator, arithmetic operator, relational operator and logical operator according to function
- Classification by the number of operands: monocular operator, binocular operator and ternary operator
unary operator
-
Assignment operator=
int num = 10 ; He is single purpose.
binary operator
-
Arithmetic operator
operator function Example + Addition operation Expression 1 + 2 evaluates to 3 - Subtraction operation Expression 2-1 evaluates to 1 * Multiplication Expression 2 * 2 evaluates to 4 / Division operation Expression 4 / 2 evaluates to 2 % Modular operation Expression 5%2 evaluates to 1
int num = 10+2; int num2 = 10*2 ;
In the arithmetic operator, a symbol (± * /) needs two numeric parameters, which is called binocular
-
Compound operation
public class Demo2 { public static void main(String[] args) { int a = 10 ; // ++Later, use before operation // ++In the front, calculate first and then use System.out.println(a++); //10 System.out.println(a); // 11 System.out.println(a++); // 11 System.out.println(a); //12 System.out.println(++a);//13 } }
-
Relational operator
- Relational operators are used to compare the size relationship of the values of two variables or expressions
- In Java, the result value of relational operation is boolean type, including "true" or "false"
operator | function | Example |
---|---|---|
> | Comparison greater than relationship | Expression 2 > 1 evaluates to "True" |
< | Comparison less than relation | Expression 2 < 1 evaluates to "False" |
>= | Compare greater than or equal relationships | Expression 2 > = 1 evaluates to "True" |
<= | Compare less than or equal relationships | Expression 2 < = 1 evaluates to "False" |
== | Comparative equivalence | Expression 2 = = 1 evaluates to "False" |
!= | Compare unequal relationships | Expression 2= 1 calculation result is "True" |
int a =10 ; int b = 10 ; boolean check = a>b; // false int c =20 ; int d = 30; boolean check1 = a<d; //true boolean check2 = a==b ;// true
-
Logical operator
The size relationship between two values in a program can be compared by using relational operators, but it is often necessary to obtain comprehensive judgment results from multiple comparison relationships in a program.
operator | function | Example |
---|---|---|
&& | And operation, i.e. simultaneous establishment, are indispensable | a> B & & C > D: the whole result is true only when the values of the left and right expressions are true. As long as one expression is false, the whole expression is false |
|| | Or operation, that is, one of the two is true | a> B|c > D: if one of the left and right expressions is true, it is false only if both expressions are false |
! | Negative operation | ! (a > b): if the expression a > b is false, it will be true after inverse operation; If the expression a > b is true, it will be false after inverse operation |
ternary operator
Syntax: Boolean expression? Expression 1: expression 2
public class Demo5 { public static void main(String[] args) { int age = 16; System.out.println(age>18?"adult":"under age"); } }
Operator precedence
If there are arithmetic operations, arithmetic operations shall be carried out first. The second is logical operation.
For example: 5 + 10 > 10 + 5// I always have to work out my numbers first before I can start comparing them.
priority | operator | Associativity |
---|---|---|
1 | () | From left to right |
2 | !,++,– | Right to left |
3 | * ,/, % | From left to right |
4 | + ,- | From left to right |
5 | > ,<, >=, <= | From left to right |
6 | ==, != | From left to right |
7 | && | From left to right |
8 | || | From left to right |
9 | = ,+=, -=, *=, /=, %= | Right to left |
Conditional structure in Java
The code we wrote before is a sequential structure and executed in sequence.
- Selection structure is also called branch structure.
- When the program executes the branch judgment statement, first judge the condition, and then select the corresponding statement to execute according to the result of the condition expression.
- Branch structure includes single branch, double branch and multi branch.
- if(boolean) {code block}
-
Single branch
import java.util.Scanner; public class Demo6 { public static void main(String[] args) { // We need to judge the age entered by the user and whether he is an adult Scanner scan = new Scanner(System.in); System.out.println("Please enter your age"); int age = scan.nextInt(); if(age>18){ System.out.println("Congratulations on your adulthood. "); } } }
- Double branch
import java.util.Scanner; public class Demo6 { public static void main(String[] args) { // We need to judge the age entered by the user and whether he is an adult Scanner scan = new Scanner(System.in); System.out.println("Please enter your age"); int age = scan.nextInt(); boolean b = age>18; if(b){ System.out.println("Congratulations on your adulthood. "); }else{ System.out.println("Sorry, you're not an adult"); } } }
-
Multi branch
import java.util.Scanner; public class Demo7 { public static void main(String[] args) { // Multi branch // We need to judge his age according to his age // Stand at thirty, do not doubt at forty, know the destiny at fifty, listen at sixty, and do whatever you want at seventy // Yama receives people, either 73 or 84 // Yuan Shikai wanted to overthrow the monarchy. Cixi, the biggest person in power of the monarchy. 72. Scanner scanner = new Scanner(System.in); System.out.println("Please enter your current age"); int age = scanner.nextInt(); if(age<30){ System.out.println("Read well"); }else if(age>=30&&age<40){ // This age is thirty years old System.out.println("And stand"); }else if(age>=40&&age<50){ System.out.println("I'm not confused"); }else if(age>=50&&age<60){ System.out.println("Know destiny"); }else if(age>=60&&age<70){ System.out.println("Ear Shun"); }else{ System.out.println("Do whatever you want"); } } }
-
Nested if
import java.util.Scanner; public class Demo7 { public static void main(String[] args) { // Multi branch // We need to judge his age according to his age // Stand at thirty, do not doubt at forty, know the destiny at fifty, listen at sixty, and do whatever you want at seventy // Yama receives people, either 73 or 84 // Yuan Shikai wanted to overthrow the monarchy. Cixi, the biggest person in power of the monarchy. seventy-two Scanner scanner = new Scanner(System.in); System.out.println("Please enter your current age"); int age = scanner.nextInt(); if(age>0){ if(age<30){ System.out.println("Read well"); }else if(age>=30&&age<40){ // This age is thirty years old System.out.println("And stand"); }else if(age>=40&&age<50){ System.out.println("I'm not confused"); }else if(age>=50&&age<60){ System.out.println("Know destiny"); }else if(age>=60&&age<70){ System.out.println("Ear Shun"); }else{ System.out.println("Do whatever you want"); } }else{ System.out.println("What the hell is less than 0"); } } }
switch-case
public class Demo8 { public static void main(String[] args) { // switch casse // For example, you have to call customer service now // Press 1 for phone bill questions, 2 for package questions and 0 for manual services Scanner scanner = new Scanner(System.in); System.out.println("Please enter the service number you want to consult"); int num = scanner.nextInt(); switch (num){ case 1 : System.out.println("Phone bill problem"); break; case 2: System.out.println("Package problem"); break; case 0: System.out.println("Artificial services"); break; default: System.out.println("The number you entered is incorrect"); } } }
Loop structure in Java
For example, we need to print 10000 sheets of paper. Does our code have to be written 10000 times, so we need to use loops
System.out.println("Print"); System.out.println("Print"); System.out.println("Print"); System.out.println("Print"); . . .
while
while(boolean){ Code block }
public class Demo9 { public static void main(String[] args) { System.out.println("Print 10000 sheets of paper"); // Declare an int i = 0 outside; int i = 1; // while (i<=10000){ // If i is less than 10000, you need to continue printing. System.out.println("The first"+i+"Piece of paper"); i++; } } }
There are some errors when writing a loop.
Error 1: the loop is not executed once
Error 2: the number of loop executions is wrong
Error 3: dead cycle
do while
do while is executed at least once compared with while
public class Demo10 { public static void main(String[] args) { // For example, the lottery in the game is free for the first time. Back charge int i = 5; // The condition is written dead. He didn't charge money and can only smoke once do { System.out.println("Took the second"+i+"second"); i--; }while (i>1); } }
for
for(Initial variable; Boolean condition;Amount of variable change;){ Code block }
break and continue
break is to jump out of the loop
// break ; For example, when I get to the 50th, I have to stop the cycle for (int i = 1 ;i<=10000;i++){ System.out.println(i); if(i==50){ break; } }
Continue is to skip the loop
// continue, for example, I only take even numbers // In other words, when I encounter an even number, I don't output this number for (int i = 0; i < 100; i++) { if(i%2!=0){ continue; } System.out.println(i); } }
Java Procedure
-
Overview of methods
-
Four types of methods
1. No parameter no return value method
public static void main(String[] args) { sayHello(); sayHello(); sayHello(); sayHello(); } // No parameter no return value public static void sayHello(){ System.out.println("Hello"); }
2. Method with parameter and no return value
public static void main(String[] args) { // The method is to combine some repeated functions so that they can be called repeatedly // For example, I need a program that can add two numbers sum(10,2,10,10); sum(50,2,10,10); sum(100,100,10,10); } // The exposed static method name with no return value defines that type int a is a parameter and type int b is a parameter public static void sum (int a , int b , int c , int d ){ int sum = a+b+c+d; System.out.println(sum); }
3. Method with return value without parameter
public static void main(String[] args) { String hello = hello(); String hello1 = hello(); String hello2 = hello(); System.out.println(hello); System.out.println(hello1); System.out.println(hello2); } // Without parameters but with return value public static String hello(){ return "hello"; }
4. Method with parameter and return value
public static void main(String[] args) { int sum = cheng(5,10); System.out.println(sum); } // The exposed static method with return value and type with int name defines that type int a is a parameter and type int b is a parameter public static int cheng (int a , int b ){ int sum = a*b; return sum; }
Overview of methods
When the program contains complex logic and functions, these functions can be decomposed into several sub functions to be realized respectively, and these sub functions are combined to form a complete program.
Methods are defined in classes. They are called through objects, and finally form the whole program. Generally speaking, a program is the call of each object to a method.
array
- If I can only store one data in one variable, what should I do if I have a set of data.
- For example, how can I save the scores of 4000 students in the class.
int xxz = 40; int lkd = 50; int lbh = 60;
- At this time, we need a data type to store our pile of data. After using the array, you only need a variable name.
Start using
-
Declaration array
int[] nums ;
-
Create array
nums = new int[5]; // new int[5], the bracket 5, specifies the length of the array. That is, the number of elements in the array can be stored
-
Initialize array
Is to assign a value to an array
nums[0] =5; nums[1] = 4; nums[2] = 2; nums[3] = 1 ; nums[4] = 5;
-
Access to arrays
public static void main(String[] args) { int[]nums ; nums = new int[5]; nums[0] =5; nums[1] = 4; nums[2] = 2; nums[3] = 1 ; nums[4] = 5; System.out.println(nums); System.out.println(nums[4]); System.out.println(nums[3]); System.out.println(nums[3]); System.out.println(nums[5]);// ArrayIndexOutOfBoundException array subscript out of bounds exception }
-
How to quickly output arrays
-
Through the for loop
-
for (int i = 0; i < nums.length; i++) { int num = nums[i]; System.out.println(num); }
-
// Enhanced for loop for (int i: nums) { System.out.println(i); }
-
-
Via arrays ToString (array variable)
String s = Arrays.toString(nums); System.out.println(s);
-
Summary of array creation methods
- Declare before initialize
- Declare and initialize directly
public static void main(String[] args) { int[] nums = new int[]{1,2,3,4,5}; System.out.println(Arrays.toString(nums)); }
- Direct initialization
int[] nums = {1,2,3,4,5};
-
Java foundation comprehensive project
Realize guessing letters
- The computer will generate five characters
- The user also enters 5 characters
- Compare the characters of the computer with the characters entered by the user one by one
- Finally, output the correct number
import java.util.Arrays; import java.util.Scanner; public class Demo17 { /** * Character guessing game * The computer randomly generates 5 characters. After entering 5 characters, the player will judge the correct number * After writing proficiently, continue to modify * 1. The current judgment logic is, for example, computer-generated mvaxz. If the user inputs zxvma, five are right, but the position is wrong. * Therefore, it is necessary to modify the number that can judge whether it is in the correct position. * 2. Make the computer-generated characters not duplicate. * @param args */ public static void main(String[] args) { // Computer generated method char[] generate = generate(); System.out.println("The number entered by the computer is:"+ Arrays.toString(generate)); // Player input method char[] inputs = input(); // Comparison method int check = check(generate,inputs); System.out.println("Congratulations, you guessed right"+check+"individual"); } // The method used to make a judgment public static int check(char[] generate, char[] inputs) { int a = 0 ; for (int i = 0; i <generate.length ; i++) { for (int j = 0; j <inputs.length ; j++) { if(generate[i]==inputs[j]){ a++; break; } } } return a; } // The method used to receive user input and return the characters entered by the user to the main method public static char[] input() { Scanner scanner = new Scanner(System.in); String next = scanner.next(); next = next.toLowerCase(); char[] chars = next.toCharArray(); return chars; } // A method used to make a computer generate random characters public static char[] generate() { char[] chars = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; char[] generate = new char[5]; for (int i = 0; i < chars.length; i++) { if(i==5){ break; } double random = Math.random(); int a = (int)(random*26); generate[i] = chars[a]; } return generate; } }