Common classes in java

Common classes in java

1. Object class

  • Object class features:

    1. The Object class is the root of the class hierarchy, and all classes in Java fundamentally inherit from this class.

    2. The Object class is the only class in Java that has no parent class.

    3. All other classes, including standard container classes such as arrays, inherit methods from the Object class.

Second, the String class

  • Some methods of the String class:
  • Obtain

    1. Get the number (length) of string characters: int length();

    2. Get character by position: char charAt(int index);

    3. Get the position in the string according to the character; int indexOf(int ch);

    4. Get a part of the string in the string, called substring: String substring(int beginIndex,int endIndex);

      • Sample code :
class Demo
{
    public static void main(String[] args)
    {
        String str="你好,世界!";
        //输出字符串的长度
        System.out.println("字符串的长度:"+str.length());
        //获取指定位置的字符
        System.out.println("字符串的第1个字符是:"+str.charAt(0));
        //获取字符在字符串的位置(角标从0开始)
        System.out.println("获取“好”在字符串的角标:"+str.indexOf('好'));
        //获取"你好"子字符串
        System.out.println("获取“你好”子字符串:"+str.substring(0,2));
    }
}

write picture description here

  • convert

    1. Turn a string into an array of strings (cutting of strings): String[] split(String regex);

    2. Turn a string into a character array: char[] toCharArray();

    3. Turn a string into an array of bytes: byte[] getBytes();

    4. Convert the letters in the string to uppercase and lowercase: uppercase, String toUpperCase(); lowercase, String toLowerCase();

    5. Replace the content of the string: String replace(char oldChar,char newCh);

    6. Remove spaces from both ends of a string: String trim();

    7. Concatenate strings: String concat();

class Demo
{
    public static void main(String[] args)
    {
        String str="Hello World";
        //将字符串中的字母全部转为小写
        System.out.println(str.toLowerCase());
        //将字符串中的字母全部转为大写
        System.out.println(str.toUpperCase());
    }
}

write picture description here

  • judge

    1. Whether the contents of two strings are equal: bolean equals(Object obj);

    2. Comparing string contents ignoring case: boolean equalsIgnoreCase(Object obj);

    3. Whether the string contains the specified string: boolean contains(String str);

    4. Whether the string starts with the specified character: boolean startsWith(String str);

    5. Whether the string ends with the specified character: boolean endsWith(String str);

class Demo
{
    public static void main(String[] args)
    {
        String str="boy";
        String str1=new String("boy");
        //判断字符串的类容是否相同
        System.out.println(str.equals(str1));
    }
}

write picture description here

  • Compare

    1. int compareTo(String str): Returns a value of 0 if the argument string is equal to this string; returns a value less than 0 if this string is lexicographically less than the string argument; if this string is lexicographically greater than characters String parameter, returns a value greater than 0.

    2. String intern(): When the intern method is called, if the pool already contains a string equal to this String object (determined by the equals(Object) method), the string in the pool is returned. Otherwise, add this String object to the pool and return a reference to this String object.

Three, StringBuffer and StringBuilder classes

StringBuffer class

  • StringBuffer : It is a string buffer, a container for storing data.

  • Features of StringBuffer:

    1. The length is variable.

    2. Different types of data can be stored.

    3. In the end, it will be converted into a string for use.

  • Some methods of StringBuffer:

    1. Add to

      1. StringBuffer append(data); add data.

      2. StringBuffer insert(index,data); Insert the specified data at the specified position.

    2. delete

      1. StringBuffer delete(int start, int end); includes header, not tail.

      2. StringBuffer deleteCharAt(int index); Delete the element at the specified position.

    3. find

      1. char charAt(int index); Get the data at the specified position.

      2. int indexOf(String str); Search from the head to get the position of the specified element.

      3. int lastIndexOf(String str); Search from the end to get the position of the specified element.

    4. Revise

      1. StringBuffer replace(int start,int end,String str); Include the head, not the tail.

      2. void setCharAt(int index, char ch); Modify the character at the specified position.

    5. Other methods

      1. void setLength(int newLength); set the length of the character sequence

      2. public StringBuffer reverse(); replace the character sequence with its reversed form

StringBuilder class

  • StringBuilder: The function that appears after jdk1.5 is exactly the same as StringBuffer, which is StringBuilder.

  • The difference between StringBuffer and StringBuilder:

    1. StringBuffer is thread synchronized and is usually used for multithreading.
    2. StringBuilder is thread asynchronous, usually used for single thread, its appearance can improve program efficiency.

Fourth, the basic data type packaging class

  • Definition: encapsulate basic data types into objects, define properties and methods in objects
    write picture description here

  • basic type –> string

    1. Basic data value + "".

    2. Use the static method ValueOf (basic type value) in the String class.

  • String –> base type

    1. Use the static method xxx parseXxx("xxx") in the wrapper class ;

    2. If the string is encapsulated by an Integer object, another non-static method, intValue, can be used. Converts an Integer object to a primitive data type value.

      Integer in=new Integer(“123”); //The string is encapsulated by the Integer object
      int i=in.intValue(); //Call the intValue method to convert the Integer type to int type
      System.out.println(i+1 ) ;
      write picture description here

    3. Use Integer's static method valueOf(String s): the return value is of type Integer .
  • Decimal -> other decimal methods

    1. Convert to binary: String toBinaryString(int i);

    2. Convert to octal: String toOctalString(int i);

    3. Convert to hexadecimal: String toHexString(int i);

    4. Convert to other bases according to radix (base): String toString(int i,int radix);

  • Other hexadecimal -> decimal method

    • int parseInt(String s,int radix);

Five, Scanner class

  • Definition: A simple text scanner that can use regular expressions to parse basic types and strings, located in the java.util package, modified by final, this class cannot be inherited

  • Basic usage of Scanner:

    • Scanner(File source) //Constructs a new Scanner whose generated values ​​are scanned from the specified file

    • Scanner(InputStream source) //Constructs a new Scanner that generates values ​​scanned from the specified input stream.

    • Scanner(String source) //Constructs a new Scanner that generates values ​​scanned from the specified string.

  • General methods of the Scanner class

    • hasNextXxx() judges whether there is the next input item, where Xxx can be Int, Double, etc. If you need to judge whether the next string is included, you can omit Xxx.

    • xxx nextXxx() Get the next input item. The meaning of Xxx is the same as Xxx in the previous method. By default, Scanner uses spaces, carriage returns, etc. as separators.

6. Enumeration class

  • Definition :
    A class with a fixed and limited instance is called an enumeration class in Java. Java has added support for enumeration classes (the keyword enum has the same status as the class and interface keywords) since JDK1.5.

  • Features:

    • Non-abstract enumerations are decorated with fianl by default, so enumerations cannot be subclassed.

    • The constructor of the enumeration class can only use private access control, if omitted, the default is private.

    • All its instances must be listed on the first line. The semicolon after the last enumeration item can be omitted, but if the enumeration class has other things, the semicolon cannot be omitted. It is recommended not to omit.

    • can be used in a switch statement

  • Common methods of enumerating classes

    • int ordinal() returns the ordinal of the enumeration constant (its position in the enumeration declaration where the initial constant ordinal is zero).

    • int compareTo(E o) Compares the order of this enumeration with the specified object.

    • String name() returns the name of this enum constant, declared in its enum declaration.

    • String toString() returns the name of the enum constant, which is included in the declaration.

    • T valueOf(Class type, String name) returns the enum constant of the specified enum type with the specified name.

    • values() This method is not found in the JDK documentation, but every enumeration class has this method, it is very convenient to traverse all the enumeration values ​​of the enumeration class

7. Math class

  • Math : Provides methods for operating mathematical operations, all of which are static.

  • Common method:

    • ceil(): Returns the smallest integer greater than the argument.

    • floor(): Returns the largest integer less than the argument.

    • round(): Returns the rounded integer.

    • pow(a,b): a raised to the b power.

  • Example:

    • Code:
import java.util.*;
class MathDemo 
{
    public static void main(String[] args) 
    {
        double d1=Math.ceil(12.56);
        double d2=Math.floor(12.56);
        double d3=Math.round(12.56);
        //输出大于12.56的最小整数
        System.out.println(d1);
        //输出小于12.56的最大整数
        System.out.println(d2);
        //输出12.56四舍五入的整数
        System.out.println(d3);
    }
}
  • Output result:
    write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519034&siteId=291194637