编程知识 cdmana.com

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}

{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}

{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 java.io.Serializable; // 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}

{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 )

 //1
 Class stuClass=Student726.class;
  //  obtain public Field "score":
 System.out.println(stuClass.getField("score"));
 //  Get inherited public Field "name":
 System.out.println(stuClass.getField("name"));
 //  obtain private Field "age":
 System.out.println(stuClass.getDeclaredField("age"));
   
       //2
       
       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 .

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

{/collapse-item}

{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");
       System.out.println(bd1.multiply(bd1));//15241414418.977927146750190521
       System.out.println(bd1);//123456.123456789
       //scale For decimal places 
       System.out.println(bd1.scale());//9   
       //stripTrailingZeros
       // 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
       System.out.println(db2.scale());//5
       System.out.println(db3.scale());//3
       // 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(db4);//12300
       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);
       System.out.println(db9);
       
       //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"}

//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);
        System.out.println(sum);//99999999991
        // Maybe BigInteger convert to long type 
        System.out.println(sum.longValue());
        System.out.println(sum.multiply(sum).longValue());
        // 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

    //721_1_1
    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 
    //721_1_1
    public enum demo721_1_1{
        sun,mon,tue,wed,thu,frt,sat;
    }// 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}

{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 .
  str1.equalsIgnoreCase(str2);
  System.out.println(str1);// result HelLo

{/tabs-pane}

{/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 ouset=ou.new demo4_2_2_1();// Instantiate a ouset
       ouset.getName();
// Inner class 3-1
class demo4_2_2{
    // Inner class  3-1
    private String name;
    demo4_2_2(String name){
        this.name=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 ,"+demo4_2_2.this.name);
        }
    }
}

{/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
        ou.demo4_2_2_2();
// Inner class 3-1
class demo4_2_2{
    // Inner class  3-1
    private String name;
    demo4_2_2(String name){
        this.name=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(){
            @Override
            public void run(){
                System.out.println(" This is an anonymous inner class   Hello ,"+demo4_2_2.this.name);}
        };
        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 
        sn.hello();
// 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);
        }
    }
}

{/tabs-pane}

{/collapse-item}

{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();
  w.run();
  s.run();
abstract  class chou{
    public abstract void run();
}
class chou2 extends chou{
    @Override
    public void run(){
        System.out.println(" Subclass auto Parkour 1");
    }
}
class chou3 extends chou{
    @Override
    public void run(){
        System.out.println(" Subclass auto Parkour 2");
    }
}

{/collapse-item}

{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");
s.run("123213");
System.out.println(s.ceshi());
// Overrides in inheritance 
    class Student{
        protected String name=" polymorphic ";
        public void run(){
            System.out.println("Student.run1");
        }
        public String ceshi(){
            return " I am a father super"+name+" ";
        }
    }
    //extends  Keywords of inherited methods 
    class Student2 extends Student{
        @Override
        public String ceshi(){
            //System.out.println("System.run");
            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){
            System.out.println(name);
        }

        // Construction method 
        public Student2(){
            System.out.println(" I'm empty ");
        } 
        public Student2(String name){
            this();
            System.out.println(name);
        }
    }

{/collapse-item}

{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 */
          myPuppy.getAge();
          /* 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}

{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.append("Runoob..");
       System.out.println(sb);  
       sb.append("!");
       System.out.println(sb); 
       sb.insert(9, "Java");
       System.out.println(sb); 
       sb.delete(5,6);// Delete   >=5  Less than 6 Subscript character of   
       System.out.println(sb); 

{/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(System.in) 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}

{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}

{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;
       a=3;
       b=2;
       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
       System.out.println(c);

{/collapse-item}

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 .

版权声明
本文为[await]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/09/20210909125824212t.html

Tags java basics
Scroll to Top