Java Basics

await 2021-09-15 07:22:39
java basics

{collapse-item label=" To write equals and hashCode"}

Use... Correctly HashMap, As key The class of must override equals() and hashCode() Method ; If a class overrides equals(), You have to rewrite hashCode(), And the override rule is : If equals() return true, be hashCode() The return values must be equal ; If equals() return false, be hashCode() Return values should not be equal . Realization hashCode() Methods can be Objects.hashCode() Auxiliary method implementation .


{collapse-item label="instanceof "}

instanceof Strictly speaking Java A binocular operator in , Used to test whether an object is an instance of a class , Usage for : boolean result = objinstanceof Class


{collapse-item label=" Inheritance relationships "}

When we judge whether an instance is a type , Under normal circumstances , Use instanceof The operator

Object n = Integer.valueOf(123);
boolean isDouble = n instanceof Double; // false
boolean isInteger = n instanceof Integer; // true
boolean isNumber = n instanceof Number; // true
boolean isSerializable = n instanceof; // true

If it's two Class example , To judge whether an upward transformation is established , You can call isAssignableFrom()

// Integer i = ?
Integer.class.isAssignableFrom(Integer.class); // true, because Integer I can assign a value to Integer
// Number n = ?
Number.class.isAssignableFrom(Integer.class); // true, because Integer I can assign a value to Number
// Object o = ?
Object.class.isAssignableFrom(Integer.class); // true, because Integer I can assign a value to Object
// Integer i = ?
Integer.class.isAssignableFrom(Number.class); // false, because Number Cannot assign a value to Integer


{collapse-item label=" Access field "}

Access field Class Class provides the following methods to get fields : Field getField(name): Get a... Based on the field name public Of field( Including the parent class ) Field getDeclaredField(name): Get a... Of the current class according to the field name field( Do not include parent classes ) Field[] getFields(): Get all public Of field( Including the parent class ) Field[] getDeclaredFields(): Get all... Of the current class field( Do not include parent classes )

Class stuClass=Student726.class;
// obtain public Field "score":
// Get inherited public Field "name":
// obtain private Field "age":
Field f=String.class.getDeclaredField("value");

Field object This object contains all the information of a field One Field Object contains all the information of a field : getName(): Return field name , for example ,"name"; getType(): Return field type , Also a Class example , for example ,String.class; getModifiers(): Returns the modifier for the field , It's a int, Different bit It means something different .

class Student726 extends Person{
public int score;
private int age;
class Person{
public String name;
final class String{
private final byte[] value;


{collapse-item label="printStackTrace()"}

Exceptions can call printStackTrace() Method print exception stack , This is a simple and useful way to quickly print exceptions .

{/collapse-item} {collapse-item label="BigDecimal"}

// It can represent a floating-point number of any size with full accuracy
BigDecimal bd1=new BigDecimal("123456.123456789");
//scale For decimal places
// You can put a BigDecimal Format as an equal ,
// But the end is left out 0 Of BigDecimal
BigDecimal db2=new BigDecimal("123.12300");
BigDecimal db4=new BigDecimal("12300");
BigDecimal db3=db2.stripTrailingZeros();
BigDecimal db5=db4.stripTrailingZeros();
System.out.println(db2+" "+db3);//123.12300 123.123
// If one BigDecimal Of scale() Return a negative number , for example -2,
// Indicates that the number is an integer , And there are two at the end 0
System.out.println(db5.scale());//-2 digit 00
// Round or truncate directly setScale Format decimal point
BigDecimal db6=new BigDecimal("456.789");
BigDecimal db7=db6.setScale(2,RoundingMode.HALF_UP);
BigDecimal db8=db6.setScale(2,RoundingMode.DOWN);
System.out.println(db7);// rounding 456.79
System.out.println(db8);// Direct truncation 456.78
//divide Represents the divisor Retain 1 Place decimals and round off
//roundingMode Indicates the value taking method of the result
BigDecimal db9=db2.divide(db4,1,RoundingMode.HALF_UP);
//divideAndRemainder() The returned array contains two BigDecimal
// They are quotient and remainder , Where quotient is always an integer , The remainder will not be greater than the divisor
// You can use this method to judge two BigDecimal Whether it is an integer multiple
BigDecimal m1=new BigDecimal("10.5");
BigDecimal m2=new BigDecimal("0.15");
BigDecimal[] m3=m1.divideAndRemainder(m2);
if (m3[1].signum()==0) {
System.out.println("m1 yes m2 Integer multiple ");
// Comparing two BigDecimal When the values of are equal , Pay special attention to ,
// Use equals() The method requires not only two BigDecimal The values are equal ,
// They are also required to scale() equal :
BigDecimal d1 = new BigDecimal("123.456");
BigDecimal d2 = new BigDecimal("123.45600");
System.out.println(d1.equals(d2)); // false, because scale Different
System.out.println(d1.equals(d2.stripTrailingZeros())); // true, because d2 Remove the tail 0 after scale Turn into 2
// You have to use compareTo() Method to compare ,
// It returns a negative number based on the size of the two values 、 Positive sum 0,
// They are less than 、 Greater than and equal to .
System.out.println(d1.compareTo(d2)); // 0

{/collapse-item} {collapse-item label="BigInteger"}

// Yes BigInteger When you do arithmetic , Only instance methods can be used , for example , Addition operation :
BigInteger b1=new BigInteger("1234567890");
BigInteger b2=new BigInteger("98765432101");
BigInteger sum=b1.add(b2);
// Maybe BigInteger convert to long type
// Use longValueExact() When the method is used ,
// If it goes beyond long The range of the type , Will throw out ArithmeticException.

BigInteger and Integer、Long equally , It is also an immutable class , And also inherited from Number class . because Number Several methods for converting to basic types are defined :

Convert to byte:byteValue() Convert to short:shortValue() Convert to int:intValue() Convert to long:longValue() Convert to float:floatValue() Convert to double:doubleValue()

therefore , By the above methods , You can put BigInteger Convert to basic type . If BigInteger The scope of the representation exceeds the scope of the basic type , High bit information will be lost during conversion , That is, the results are not necessarily accurate . If you need to convert to the base type exactly , have access to intValueExact()、longValueExact() Other methods , If it is out of range during conversion , Will be thrown directly ArithmeticException abnormal .

If BigInteger The value of even exceeds float The maximum range of (3.4x1038), So back float yes Infinity

{/collapse-item} {collapse-item label="enum Enumeration class "}

Enables the compiler to automatically check that a value is in an enumerated collection , also , Enumerations for different purposes require different types to mark , Can't mix

demo721_1.demo721_1_1 d=demo721_1.demo721_1_1.mon;
if(d==demo721_1.demo721_1_1.sat || d==demo721_1.demo721_1_1.sun){
System.out.println(" welcome ");
}else {
System.out.println(" Go away ");
package bindle;
public class demo721_1 {
// enumeration
public enum demo721_1_1{
}// Compile followed by class No difference
// public final class demo721_1_1 extends Enum{// Inherit Enum Mark final class
// // Each strength is unique in the overall situation
// public static final demo721_1_1 sun=new demo721_1_1;
// public static final demo721_1_1 mon=new demo721_1_1;
// public static final demo721_1_1 tue=new demo721_1_1;
// public static final demo721_1_1 wed=new demo721_1_1;
// public static final demo721_1_1 thu=new demo721_1_1;
// public static final demo721_1_1 frt=new demo721_1_1;
// public static final demo721_1_1 sat=new demo721_1_1;
// //private Construction method , Make sure that the external cannot call new The operator ;
// private demo721_1_1(){}
// }

Comparison of citation types , To use equals() Method , If you use == Compare , It compares whether two variables of reference type are the same object . therefore , Comparison of citation types , Always use equals() Method , but enum Types can be exceptional .

enum The defined type is class, But it has the following characteristics : Defined enum Types always inherit from java.lang.Enum, And cannot be inherited ; You can only define enum Example , And not through new Operator creation enum Example ; Each instance defined is the only instance of the reference type ; Can be enum Type is used for switch sentence .

enum Constants themselves have type information , namely demo721_1.demo721_1_1.mon The type is demo721_1_1, The compiler will automatically check for type errors .


{collapse-item label="String"}

{tabs-pane label=" Size conversion "}

 String str=" Hello ,HelLo";
// Turn lowercase
System.out.println(str.toLowerCase());// result : Hello ,hello
// Turn capitalization
System.out.println(str.toUpperCase());// result : Hello ,HELLO
String str1="HelLo";
str1.indexOf("l");// result 2 First appearance
str1.lastIndexOf("o");// result 4 For the last time
str1.startsWith("ll");// result false Whether to start with the specified money
str1.endsWith("o");// result true Whether to end with the specified suffix
str1.contains("o");// result true Whether to include case sensitive 

{/tabs-pane} {tabs-pane label=" Ignore size comparison "}

 String str1="HelLo";
String str2="hello";
// Ignore case comparison , Use equalsIgnoreCase() Method .
System.out.println(str1);// result HelLo


{/collapse-item} {collapse-item label=" Inner class "}

stay Java In the program , Usually , We organize different classes under different packages , For classes under a package , They are on the same level , No father son relationship : java.lang ├── Math ├── Runnable ├── String └── ... There is another kind , It is defined inside another class , So it's called an inner class (Nested Class).Java The internal classes of are divided into several , Usually it's not used much , But you also need to understand how they are used .

{tabs-pane label=" Inner class "}

// Inner class 3-1
demo4_2_2 ou=new demo4_2_2("lq");// Instantiate a ou
demo4_2_2.demo4_2_2_1 demo4_2_2_1();// Instantiate a ouset
// Inner class 3-1
class demo4_2_2{
// Inner class 3-1
private String name;
demo4_2_2(String name){;
this.Name=name;// This is a static inner class
// Inner class 3-1
class demo4_2_2_1{
void getName(){
System.out.println(" This is the inner class Hello ,";

{/tabs-pane} {tabs-pane label=" Anonymous inner class "}

// Inner class 3-1
demo4_2_2 ou=new demo4_2_2("lq");// Instantiate a ou
// Anonymous inner class 3-2
// Inner class 3-1
class demo4_2_2{
// Inner class 3-1
private String name;
demo4_2_2(String name){;
// An anonymous class 3-2
void demo4_2_2_2(){
//Runnable It's an interface , Interface cannot be instantiated , So here
// It defines an implementation Runnable Anonymous class of interface , adopt new Instantiate the anonymous class
// Then transform to Runnable, When you define an anonymous class, you must instantiate it , It is written as follows
Runnable r=new Runnable(){
public void run(){
System.out.println(" This is an anonymous inner class Hello ,";}
new Thread(r).start();

{/tabs-pane} {tabs-pane label=" Static inner class "}

 // Static inner class 3-3
//static modification
demo4_2_2.demo4_2_2_3 sn=new demo4_2_2.demo4_2_2_3();// Instantiation
// Inner class 3-1
class demo4_2_2{
private static String Name;
// Static inner class 3-3
static class demo4_2_2_3{
void hello(){
System.out.println(" This is a static inner class Hello ,"+demo4_2_2.Name);



{collapse-item label=" abstract class abstract"}

Abstract classes themselves are designed to be inherited only , therefore , Abstract classes can force subclasses to implement the abstract methods they define , Otherwise the compilation will report an error . therefore , Abstract methods are actually equivalent to defining “ standard ”.

 chou s=new chou2();
chou w=new chou3();;;
abstract class chou{
public abstract void run();
class chou2 extends chou{
public void run(){
System.out.println(" Subclass auto Parkour 1");
class chou3 extends chou{
public void run(){
System.out.println(" Subclass auto Parkour 2");


{collapse-item label=" Polymorphism and construction "} Polymorphism has a very powerful function , That is to allow adding more types of subclasses to realize function extension , You don't need to modify the code based on the parent class .

// polymorphic structure
// overwrite
Student2 s=new Student2("123");"123213");
// Overrides in inheritance
class Student{
protected String name=" polymorphic ";
public void run(){
public String ceshi(){
return " I am a father super"+name+" ";
//extends Keywords of inherited methods
class Student2 extends Student{
public String ceshi(){
return super.ceshi()+" Subclass call parent ";
// Same method name , The method parameters are the same , But the return value of the method is different ,
// It's also a different way . stay Java In the program , This happens , The compiler will report an error .
public void run(String name){
// Construction method
public Student2(){
System.out.println(" I'm empty ");
public Student2(String name){


{collapse-item label=" Construction method "} Each class has a constructor . If you do not explicitly define a constructor for a class ,Java The compiler will provide a default constructor for this class . When creating an object , Call at least one constructor . The name of the constructor must have the same name as the class , A class can have multiple construction methods .

this: It seems to be used to distinguish between local variables and member variables with the same name this: Represents this kind of object ,this Represents the function where it is located ( Method ) The reference of the object to which it belongs Calls between constructors can only be made through this Statement to complete When calling between constructors this Statements can only appear on the first line , The construction method must first execute , If there is initialization in initialization , Then perform more detailed initialization

package demo1;
public class Puppy{// This is a class
int puppyAge;
// object 1
public Puppy(String name){// Create an object These are some objects in the class object
// This constructor has only one parameter :name
System.out.println(" The dog's name is : " + name );
// object 2 Method
public Puppy(String name,int age)
System.out.println(" The dog's name is :"+name+" The age of the puppy is : " + age );
public void setAge( int age ){// Are all methods.
puppyAge = age;
public int getAge( ){
System.out.println(" The age of the puppy is : " + puppyAge );
return puppyAge;
public static void main(String[] args){
/* Create objects */
Puppy myPuppy = new Puppy( "tommy",123 );
/* Set by method age */
myPuppy.setAge( 2 );
/* Call another method to get age */
/* You can also access member variables as follows */
System.out.println(" A variable's value : " + myPuppy.puppyAge );

{/collapse-item} {collapse-item label=" Create objects "} Objects are created from classes . stay Java in , Use keywords new To create a new object . Three steps are required to create an object : Statement : Declare an object , Include object name and object type . Instantiation : Use keywords new To create an object . initialization : Use new When you create an object , Call constructor to initialize object .

public class Puppy{
public Puppy(String name){
// This constructor has only one parameter :name
System.out.println(" The dog's name is : " + name );
public static void main(String[] args){
// The following statement will create a Puppy object
Puppy myPuppy = new Puppy( "tommy" );


{collapse-item label=" Access control modifiers "} Java in , You can use access controls to protect pairs of classes 、 Variable 、 Access to methods and constructors .Java Support 4 Different access rights . default ( Default , Write nothing ): Visible in the same package , Don't use any modifiers . Use object : class 、 Interface 、 Variable 、 Method . private : Visible in the same category . Use object : Variable 、 Method . Be careful : Can't modify class ( External class ) public : Visible to all classes . Use object : class 、 Interface 、 Variable 、 Method protected : Visible to classes and all subclasses in the same package . Use object : Variable 、 Method . Be careful : Can't modify class ( External class ). {/collapse-item} {collapse-item label=" Non access modifier "} In order to realize some other functions ,Java There are also many non access modifiers . static Modifier , Used to modify class methods and class variables . final Modifier , To decorate a class 、 Methods and variables ,final The decorated class cannot be inherited , Decorated methods cannot be redefined by inherited classes , Modifies a variable as a constant , It's not modifiable . abstract Modifier , Used to create abstract classes and abstract methods synchronized and volatile Modifier , Mainly used for thread programming . {/collapse-item}

{collapse-item label="StringBuilde class String modification "} In the use of StringBuffer Class time , Every time I was right about StringBuffer The object itself operates , Instead of generating new objects , Therefore, if you need to modify the string, it is recommended to use StringBuffer. StringBuilder Class in Java 5 It was proposed that , It and StringBuffer The biggest difference between them is StringBuilder Is not thread safe ( Can't sync access )

//StringBuilder class String modification
StringBuilder sb = new StringBuilder(10);
sb.insert(9, "Java");
sb.delete(5,6);// Delete >=5 Less than 6 Subscript character of

{/collapse-item} {collapse-item label=" other "} import java.util.*; All the bags Type in :Scanner Scanner import java.util.Scanner; Import scanner package for example :Scanner i=new Scanner( data type :Boolean String int double char

//SecureRandom // There are pseudo-random numbers , There are real random numbers . // In fact, the real true random number can only be obtained by the principles of quantum mechanics , // What we want is an unpredictable and secure random number , //SecureRandom Is used to create safe random numbers SecureRandom sr1=new SecureRandom(); System.out.println(sr1.nextInt(10));

Operator precedence : Logical operators can only be used on Boolean Type of data Compare strings with equals Contrast Out-of-service ==

Switch: Switch( Parameters 1){ Case value 1: Output statement break; Case value 2: Output statement break; Default: Output statement }

random number random Random XX=new Random(); int number=ii.nextInt(10);//0~9 int number2=(int)(Math.random()*10)// ditto

loop for for( Initial parameter 1; Variable parameters 2; Parameters 3){} Initial parameter 1 Represents the initial value of the loop , You can define multiple parameters , Variable parameters 2 Represents the number of cycles , It can also be multiple parameters , Parameters 3 Represents the value increased or decreased after each cycle notes :For There can also be break sentence

Java As an object-oriented language . The following basic concepts are supported : polymorphic 、 Inherit 、 encapsulation 、 abstract 、 class 、 object 、 example 、 Method 、 heavy load • object : Object is an instance of a class ( It's not about finding a girlfriend ), Presence and behavior . for example , A dog is an object , Its state is : Color 、 name 、 Varieties ; Behavior has : Wag the tail 、 It's called 、 Eat, etc. . • class : Class is a template , It describes the behavior and state of a class of objects .


{collapse-item label=" Array "}

//java Array
// The definition and writing of array
int[] aa;
int aaa[];
// Set the size of the array
int[] aa1=new int[5];
int aa2[]=new int[5];
// Fixed value
int[] aa3={1,2,4,5,6,3,2};
//foreach Writing
for(int e:aa3){System.out.print(e);}
System.out.println(" Please enter the number of cycles :");// Set the size of the array and the number of cycles
int count=i.nextInt();
double[] alist=new double[count];// Define the size of the array
double sum=0,age=0;
for(int q=0;q

{/collapse-item} {collapse-item label=" Multidimensional arrays "}

System.out.println(" Please enter the number of rows of multidimensional array :");
int d1=i.nextInt();
System.out.println(" Please enter the number of multidimensional array columns :");
int d2=i.nextInt();
String str[][]=new String[d1][d2];//2 Number of bit lines ,3 Number of bits Must all be integers
// Allocate space from the highest dimension
for(int q=0;q


{collapse-item label=" Time SimpleDateFormat Format date "} SimpleDateFormat Is a class that formats and analyzes dates in a locale sensitive way .SimpleDateFormat Allows you to select any user-defined date and time format to run

 Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
System.out.println(" The current time is : " + ft.format(dNow));

{/collapse-item} {collapse-item label=" Ternary operator "} from ?: The symbol means , The specific meaning is actually the same as if-else The meaning of structure is similar , This operator treats a condition in two ways , If the conditions are met, the first result is executed , If not, execute another result

 //java Ternary operator
int a,b,c;
c=a>b ? 100:300; // If a Greater than b will 100 Assign a value to c Otherwise it will be 300 Assign to c


This article altogether 3402 Number of words , Average reading time ≈ 9 minute

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .


  1. Design pattern -- agent pattern
  2. Huawei Java Senior Engineer interview question, Byte Jumping thousand Selected Interview Question is still not Brushed!
  3. 双非本科字节跳动Java面试题分享,一篇文章教你搞定计算机网络面试,
  4. 又到一年金三银四,2021最新Java笔试题及答案,
  5. Huawei Finance and Economics 2021 Spring Recruitment interview, what is distributed Lock?Pourquoi utiliser des serrures distribuées?
  6. Un an plus tard, Golden, Silver, Silver, and Silver, 2021, the latest Java written Examination Questions and Answers,
  7. Partage de questions d'entrevue Java à double saut d'octets non - premier cycle, un article vous apprend à gérer l'entrevue réseau informatique,
  8. Computer graduation project java online voting system based on SSM
  9. K8s gestion des ressources (opérations de base)
  10. 又到一年金三銀四,2021最新Java筆試題及答案,
  11. Collection de code de base JavaScript (1)
  12. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  13. Vérification des permissions d'interface pour le démarrage du printemps à l'aide d'annotations personnalisées AOP +.
  14. Cloud Security Daily 210914: Red Hat Jboss Middleware Platform found important Security Vulnerability and needs to be upgraded as soon as possible
  15. 吐血整理,腾讯团队实力打造spring入门教程,
  16. 史上最全的微服务专业术语面试50问,字节跳动Java岗经典面试真题,
  17. Absolument!C'est l'analyse la plus détaillée du code source de hashtap que j'ai jamais vu!
  18. Computer graduation project Java logistics order management system of logistics company based on SSM
  19. Talk about Kafka: source code analysis of producer
  20. [springboot2 starts from 0] development tips - Lombok, devtools, spring initailizr
  21. 国内一线互联网公司面试题汇总,2021年大厂Java岗面试必问,
  22. 啃完吃透保你涨薪5K,熬夜整理小米Java面试题,
  23. 和字节跳动大佬的技术面谈,Redis成神之路电子版教程已问世,
  24. Le terme professionnel le plus complet de l'histoire des micro - services interview 50 questions, Byte Jumping Java post Classic interview vrai problème,
  25. After using mybatisplus, I haven't written SQL for a long time
  26. [springboot2 starts from 0] how to write a springboot application?
  27. Huawei cloud guassdb (for redis) released a new version, and the two core features were officially unveiled
  28. 和字節跳動大佬的技術面談,Redis成神之路電子版教程已問世,
  29. 啃完吃透保你漲薪5K,熬夜整理小米Java面試題,
  30. Avec l'interview technique du gigolo, le tutoriel électronique redis est sorti.
  31. Après avoir mangé, assurez - vous d'augmenter votre salaire de 5K et de rester debout tard pour trier les questions d'entrevue Java de millet.
  32. Résumé des questions d'entrevue pour les entreprises Internet nationales de première ligne, qui doivent être posées lors de l'entrevue d'emploi Java de la grande usine en 2021,
  33. Le tri des crachats de sang, la force de l'équipe Tencent pour créer le tutoriel d'introduction au printemps,
  34. Java and scala concurrency Fundamentals
  35. Analysis of java thread source code based on Hotspot
  36. 國內一線互聯網公司面試題匯總,2021年大廠Java崗面試必問,
  37. Introduction au module de contrôle de Connexion MySQL
  38. 大厂高级测试面试题,Java面试基础技能罗列,
  39. Comprendre l'architecture sous - jacente d'InnoDB en exécutant une instruction
  40. Chargeur de classe 1 Tomcat
  41. 小白也能看懂的dubbo3应用级服务发现详解
  42. SpringBoot异步使用@Async原理及线程池配置
  43. Questions d'entrevue de test avancé de Dachang, liste des compétences de base de l'entrevue Java,
  44. SpringBoot异步使用@Async原理及線程池配置
  45. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  46. Détails de la découverte du Service d'application Dubbo 3 que Xiaobai peut également comprendre
  47. Springboot utilise asynchrone le principe @ async et la configuration du pool de threads
  48. 如何强大且优雅的搞定Linux文件系统,算法题 JVM,
  49. 太牛了,阿里P7架构师带你看透maven的来龙去脉,
  50. Oracle central et Oracle décentralisé
  51. java JavaBean
  52. Java wrapper type
  53. Java super keyword
  54. Java static keyword
  55. Java this keyword
  56. Java interface
  57. 太牛了,阿裏P7架構師帶你看透maven的來龍去脈,
  58. C'est génial, l'architecte Ali p7 vous montre à travers Maven.
  59. Comment traiter le système de fichiers Linux avec puissance et élégance, algorithme JVM,
  60. Usage of Java scanner