java wrapper class and other classes

wrapper class

Encapsulation classes of eight basic data types:

  1. boolean—>Boolean
  2. char—>Character
  3. byte–>Byte
  4. int–>Integer
  5. long–>Long
  6. float–>Float
  7. double–>Double
  8. short–>Short

Packing and unpacking:

jdk5 used to pack and unpack manually. jdk5 will automatically pack and unpack.

The underlying call of auto boxing is the valueOf method. For example, Integer.valueof() is used similarly to other wrapper classes.

Integer wrapper class:

public class Wrapper01 {
   public static void main(String[] args) {
      Integer integer = new Integer(1);//All objects that come out through new are new objects.
      Integer integer1 = new Integer(1);
      System.out.println(integer==integer1);//false
      Integer i=1;//The valueOf method is called automatically.
      Integer j=1;//The valueOf method is called automatically.
      System.out.println(i==j);//true
      Integer i1=128;
      Integer j2=128;
      System.out.println(i1==j2);//false
   }
}

//valueOf method.
//This method will always cache values in the range -128 to 127,
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

It can be seen from the underlying code that when creating an object through the valueOf method, if the value is between - 128-127, the existing object reference in IntegerCache.cache will be returned; Otherwise, create a new object.

Integer i2=127;
      int j3=127;
      System.out.println(i2==j3);//true.

As long as there are basic data types, it is judged whether the values are equal.

String

  1. String pairs are used to save strings, that is, a set of character sequences.

  2. The String class has many constructors, such as:

    String s=new String(String original);
    String s1=new String(char[] a);
    String s2=new String(char[] a,int starIndex,int count);
    String s3=new String(byte[] b);
    
    
  3. String implements the Serializable interface, which can be transmitted over the network.

  4. String is a final class and cannot be inherited by other classes.

  5. String has the property private final char value [], which is used to store the string content.

  6. value is a final type and cannot be modified, that is, the address cannot be modified, but the content of a single character can be changed.

Differences between the two methods of creating strings:

Method 1: String n1 = "zhang";

Method 2: String n2=new String("zhang");

The first way is to check whether there is a "zhang" data space from the constant pool. If there is a direct point, if not, create it and then point to it. n1 finally points to the address of the constant pool.

The second way is to create a space in the heap first, pointing to the zhang space of the constant pool. If the constant pool does not exist, it will be recreated. If there is a direct point through value, it will eventually point to the space in the heap.

Example:

      String n3="zhang";//Point to constant pool.
      String n4 = new String("zhang");//Points to objects in the heap.
      System.out.println(n3.equals(n4));//true.
      System.out.println(n3==n4);//false. 
      System.out.println(n3==n4.intern());//true

Note: the b4.intern() method finally returns the address of the constant pool.

Interview questions:

String is a final class that represents an immutable character sequence.

String n1="hello";
n1="hi";
//The "hello" object and "hi" object are created successively in the constant pool, and finally n1 points to the "hi" object.
String a="hello";
String b="abc";
//First create a StringBuilder sb = new stringbuilder();
//Execute sb.append("hello"), and execute sb.append("abc").
//String c = sb. ToString (looking at the underlying layer, it is found that the toString method actually creates a new object.)
//Finally, c points to the object in the heap, and the value in the object points to "helloabc" in the constant pool
String c=a+b; 

Note: String c=a+b;

​ String c="hello"+"abc";

The difference between the two: the former is variable addition, looking at the heap, the latter is constant addition, looking at the pool.

public class StringExercise02 {
   public static void main(String[] args) {
      Test ex = new Test();
      ex.change(ex.str,ex.ch);//Calling a method will generate a new stack, which will be destroyed when the method is called.
      System.out.print(ex.str+" and"+"\t");
      System.out.print(ex.ch);
   }
}
class Test{
   String str=new String("hsp");
   final char[] ch={'j','a','v','a'};
   public void change(String str,char[] ch){
      str="java";
      ch[0]='h';
   }
}
//hsp and hava

The memory distribution diagram is as follows:

Common methods of String class:

     String s=new String("zhangz");
     System.out.println(s.equalsIgnoreCase("ZHANG"));//Case. false;
     System.out.println(s.charAt(1));//Gets the character at an index. h
     System.out.println(s.indexOf("z"));//Gets the index position of the first occurrence of a character in a string. 0
     System.out.println(s.lastIndexOf("z"));//Gets the index position of the last occurrence of a character in a string. five
     System.out.println(s.substring(1));//Intercept characters after index: hangz
     System.out.println(s.substring(0,4));//Cut from 0 to 3. zhan
     



    
     String s="zhang";
     System.out.println(s.toUpperCase());//Convert to uppercase. ZHANG
     System.out.println(s.toLowerCase());//Convert to lowercase. zhang
     System.out.println(s.concat("jian").concat("handsome").concat("great"));
//String splicing. zhangjianhandsomegreat
     System.out.println(s.replace("zhang","jian"));//replace. jian
     System.out.println("===================");
     String poem="Weeding day at noon, sweat drops under the soil, whose plate of Chinese food, every grain is hard";
     String[] split = poem.split(",");//Split string. Divide with "," as the standard.
     for (String s1 : split) {
        System.out.println(s1+"\t");
     }
     String n="\\aaa\\bbb\\ccc\\ddd";
     String[] split1 = n.split("\\\\");//When splitting a string, if there are special characters, the escape character "\" needs to be added
     for (String s1 : split1) { 
        System.out.println(s1);
     }\\aaa
       \\bbb
       \\ccc
       \\ddd
     String s1="zhang";
     char[] chars = s1.toCharArray();//Convert to character array.
     for (char aChar : chars) {
        System.out.println(aChar);
     }
     String n1="zhnge";
     String n2="zhang";
     System.out.println(n1.compareTo(n2));//Compare the size of two strings. If the length is the same and each string is the same, zero is returned; If the length is different or the same, when the first different character appears during comparison, the ASCII value is subtracted; If the previous part is the same, n1.length-n2.length is returned
  
String name="Zhang Yu";
    int age=21;
    double score=99.0;
    char gender='male';
    String format = String.format("My name is:%s ,Age is:%d ,The score is:%.2f ,Gender is:%c",           name, age, score, gender);
    //%s. % D,%. 2f,% c, these are called placeholders, replaced by subsequent variables,% s means replaced by strings,% d is replaced by integers,%. 2f means replaced by decimals, two decimal places are retained, and rounded.% d c use char type instead.
    System.out.println(format);

StringBuffer class

The immediate parent class of StringBuffer is AbstractStringBuilder.

StringBuffer implements Serializable, that is, objects can be serialized.

In the parent class, AbstractStringBuilder has the attribute char[] value, which is not final. The string content stored in this value is stored in the stack.

StringBuffer is a final class and cannot be inherited.

Example:

//Every three digits before the decimal point are separated by commas.
public static void main(String[] args) {
        String s = "121343455.44";
        StringBuffer stringBuffer = new StringBuffer(s);
        for (int i1 = stringBuffer.lastIndexOf(".") - 3; i1 > 0; i1 -= 3) {
            stringBuffer.insert(i1, ",");
        }
        System.out.println(stringBuffer);
    }

Comparison between String and StringBuffer:

String saves a string constant. The value in it cannot be modified. Each update of string actually updates the address, which is inefficient.

//private final char[] value points to the constant pool.

StringBuffer saves string variables. The values in StringBuffer can be modified. Each update of StringBuffer is a content update without changing the address, which is more efficient.

//char[] value points to the heap.

String and StringBuffer conversion:

 //String to StringBuffer
      String s="zhang";
      //1. Use the constructor.
      StringBuffer stringBuffer = new StringBuffer(s);
      //2. Use the append method.
      StringBuffer stringBuffer1 = new StringBuffer().append(s);
 //StringBuffer to String.
      StringBuffer stringBuffer2 = new StringBuffer("Zhang Yu is not handsome");
      //1. Use the toString method to create.
      String string = stringBuffer2.toString();
      //2. Use the constructor.
      String s1 = new String(stringBuffer2);

Common methods of StringBuffer:

 StringBuffer stringBuffer = new StringBuffer("Zhang Yu");
      //add to.
      stringBuffer.append(",");
      stringBuffer.append("Super handsome.");
      stringBuffer.append("you 're right.");
      System.out.println(stringBuffer);
      //Delete. Delete characters between [0,2].
     stringBuffer.delete(0,2);
      System.out.println(stringBuffer);
      //Replace. [0,2)
      stringBuffer.replace(0,2,"Edison Chan");
      System.out.println(stringBuffer);
      //Finds the index of the first occurrence of the specified string in the string. If not found, returns - 1;
      System.out.println(stringBuffer.indexOf("Edison"));
      //Insert at specified location
      System.out.println(stringBuffer.insert(0, "Wu Yanzu,"));
      //Returns the length.
      System.out.println(stringBuffer.length());

   }

StringBuilder class

  1. StringBulider inherits the AbstractStringBuilder class.
  2. Serializable is implemented, which shows that the StringBulider object can be serialized.
  3. StringBuilder is a final class and cannot be inherited.
  4. The character sequence of the StringBulider object is still stored in the char[] value of the parent class.
  5. StringBulider is used in the case of single thread because it does not have the synchronized keyword.

Comparison of StringBuffer,StringBuilder and String:

  • Both StringBuffer and StringBuilder are variable character sequences, and the method is the same.
  • String: immutable character sequence, low efficiency, but high reuse rate.
  • StringBuffer: variable character sequence, high efficiency and thread safety.
  • StringBuilder: variable character sequence, high efficiency, thread unsafe.

Math common methods:

 int abs = Math.abs(-34);//Find the absolute value.
      System.out.println(abs);
      double pow = Math.pow(2,4);//power
      System.out.println(pow);
      double ceil = Math.ceil(-1.89);//Round up.
      System.out.println(ceil);
      double floor = Math.floor(-4.49);//Round down.
      System.out.println(floor);
      long round = Math.round(1.2);//rounding.
      System.out.println(round);
      double sqrt = Math.sqrt(4);//Find the square.
      System.out.println(sqrt);
      for (int i = 0; i < 10; i++) {
         System.out.println((int)(2+Math.random()*6));//Find a random number and return the number on [2,8].
      }
      System.out.println(Math.max(2,3));
      System.out.println(Math.min(2,3));

Key points: random number ()

Arrays class:

Integer[] array={1,22323,4,524,50};
System.out.println(Arrays.toString(array));//Displays the array.
Arrays.sort(array);//Sort array.
System.out.println(Arrays.toString(array));//Output again.
//Binary search the index of a number in the array. The array must be ordered. If the number does not exist, the return is / / return -(low+1).  
 Integer[] integer={1,3,4,5,};
int i = Arrays.binarySearch(integer, 1);
      System.out.println("index="+i);
      Integer[] array={1,2,34,324,34};
      Integer[] integers =Arrays.copyOf(array,array.length);//Array copy.
      System.out.println(Arrays.toString(integers));

      Integer[] array={1,2,34,324,34};     
      Arrays.fill(array,10);//The padding of the array.
      System.out.println(Arrays.toString(array));
      boolean equals=Arrays.equals(array,integers);//Compare whether the elements of the two arrays are the same. Yes, return true. No, return false.
      System.out.println(equals);  


Example:

 public static void main(String[] args) {
      Book[] books = new Book[4];
      books[0]=new Book("The Dream of Red Mansion",100);
      books[1]=new Book("New Golden Lotus",90);
      books[2]=new Book("New Youth Digest",5);
      books[3]=new Book("java From getting started to giving up",300);
      Arrays.sort(books, new Comparator<Book>() {
         @Override
          //Override the compare method. If you want to change the sorting method, you can directly modify the value of return.
         public int compare(Book o1, Book o2) {
            int priceVal= o2.getPrice()-o1.getPrice();
            if(priceVal>0){
               return 1;
            }else if(priceVal<0){
               return -1;
            }else {
               return 0;
            }
         }
      });
      System.out.println(Arrays.toString(books));
     
      System.out.println("=====================");

      Arrays.sort(books, new Comparator<Book>() {
         @Override
         public int compare(Book o1, Book o2) {
            return o1.getName().length()-o2.getName().length();
         }
      });
      for (int i = 0; i <books.length ; i++) {
         System.out.println(books[i].toString());
      }

   }
}
class Book{
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public int getPrice() {
      return price;
   }

   public void setPrice(int price) {
      this.price = price;
   }

   private String name;
   private int price;

   @Override
   public String toString() {
      return "The title of the book is:"+ name + '\'' +
              ", The price is:" + price ;
   }

   public Book(String name, int price) {
      this.name = name;
      this.price = price;
   }
}

System class:

      long l = System.currentTimeMillis();//current time 
      Integer[] integers={1,2,4,5};
      Integer[] integers1 = new Integer[3];
      //Copy 3 elements from the first element of the original array and the first element of the new array
      System.arraycopy(integers,0,integers1,0,3);
      System.out.println(Arrays.toString(integers1));

BigInteger class

When the data is large, BigInteger is used for calculation.

      
      BigInteger bigInteger = new BigInteger("200000000000"); 
      BigInteger bigInteger1 = new BigInteger("100000000000");
      //Add
      BigInteger add = bigInteger.add(bigInteger1);
      System.out.println(add);
      //subtract 
      BigInteger subtract = bigInteger.subtract(bigInteger1);
      System.out.println(subtract);
      //be divided by
      BigInteger divide = bigInteger.divide(bigInteger1);
      System.out.println(divide);
      //Multiply.
      BigInteger multiply = bigInteger.multiply(bigInteger1);
      System.out.println(multiply);

BigDecimal class

When the decimal data is large, use the BigDecimal class,

 BigDecimal bigDecimal = new         BigDecimal("1.2222222222222222222222222");
      BigDecimal bigDecimal1 = new BigDecimal("7");
      //Add
      System.out.println(bigDecimal.add(bigDecimal1));
      //subtract 
      System.out.println(bigDecimal.subtract(bigDecimal1));
      //Multiply
      System.out.println(bigDecimal.multiply(bigDecimal1));
      //Divide. If the loop is infinite, write bigdeciaml.round in the method_ Ceiling is the number of digits reserved for divisor.
System.out.println(bigDecimal.divide(bigDecimal1,BigDecimal.ROUND_CEILING));

Date class (first generation date class)

 Date date = new Date();
      System.out.println(date);
      //To create a simpleDateFormat object, you can specify the corresponding format and can't Scribble.
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year MM month dd day E HH:mm:ss");
      String format = simpleDateFormat.format(date);
      System.out.println(format);//Friday, October 29, 2021 16:18:03
      System.out.println("=================");
      //Converts a string to a date.
      //The date obtained is still in foreign form and needs to be converted and output.
      //If the format of simpleDateFormat is different from that of String, you need to throw a conversion exception.
      String s="2024 Friday, 29 October 2016:14:54";
      Date parse = simpleDateFormat.parse(s);
      System.out.println(simpleDateFormat.format(parse));
      System.out.println("================");
      //Gets the time by the specified number of milliseconds
      Date date1 = new Date(123456);
     System.out.println(simpleDateFormat.format(date1));//Thursday, January 1, 1970 08:02:03
   }

Calendar Class (second generation date class)

The Calendar class is an abstract class, and the constructor is private, so you need to call the getInstance method to get the instance.

The Calendar class does not provide the corresponding format, so the programmer needs to write the format himself.

  Calendar instance = Calendar.getInstance();
//Get year
      System.out.println(instance.get(Calendar.YEAR));
//Get month + 1
      System.out.println(instance.get(Calendar.MONTH)+1);
//Get the day.
      System.out.println(instance.get(Calendar.DAY_OF_MONTH));
//Gets the number of hours.
      System.out.println(instance.get(Calendar.HOUR));
//Gets the number of minutes.
       System.out.println(instance.get(Calendar.MINUTE));
//Write your own date format:
System.out.println(instance.get(Calendar.YEAR)+"-"+(instance.get(Calendar.MONTH)+1)+"-"+instance.get(Calendar.DAY_OF_MONTH)+"\t"+instance.get(Calendar.HOUR_OF_DAY)+":"+instance.get(Calendar.MINUTE)+":"+instance.get(Calendar.SECOND));//2021-10-30	13:1:18

(common) LocalDateTime class (third generation date class)

LocalDateTime now = LocalDateTime.now();
      System.out.println(now);//Gets the current date.
      DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy year MM month dd day E HH:mm:ss");//Format date.
      String format = dateTimeFormatter.format(now);
      System.out.println(format);
      //A year later.
       LocalDateTime localDateTime = now.plusYears(1);
     //A year ago.
      LocalDateTime localDateTime1 = now.minusYears(1);
      System.out.println("A year ago:"+dateTimeFormatter.format(localDateTime1));
      System.out.println("One year later:"+dateTimeFormatter.format(localDateTime));

Exercise:

Inverts the specified part of the string.

 public static void main(String[] args) {
        String s = "abcdef";
        System.out.println(reverse(s, 1, 4));//aedcbf 

    }

    public static String reverse(String s, int start, int end) {
        if(!(s!=null&&start>=0start<end&&end>start&&end<s.length())){
            throw new ArrayIndexOutOfBoundsException("The parameter is incorrect.");
        }
        char[] chars = s.toCharArray();
        char temp;
        for (int i = start, j = end; i < j; i++, j--) {
            temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
        }
        return new String(chars);
    }

Keywords: Java

Added by clairian on Sun, 31 Oct 2021 15:19:40 +0200