Java常用类API(String、Math)

一、String、StringBuilder、StringBuffer

1 构造方法

1.1 public String( )

无参构造方法创建空字符串的String对象。

String str1=new String();

1.2 public String(String value)

用已知的字符串value创建一个String对象。

String str2 = new String("asdf");  
String str3 = new String(str2);

1.3 public String(char[] value)

用字符数组value创建一个String对象

char[] value = {'a','b','c','d'};
String str4 = new String(value);//相当于String str4 = new String("abcd");

1.4 public String(char chars[], int startIndex, int numChars)

用字符数组chars的startIndex开始的numChars个字符创建一个String对象

char[] value = {'a','b','c','d'};
String str5 = new String(value, 1, 2);//相当于String str5 = new String("bc");

1.5 public String(byte[] values)

用比特数组values创建一个String对象

byte[] strb = new byte[]{65,66};
String str6 = new String(strb);//相当于String str6 = new String("AB");

2 常用方法

2.1 求字符串长度

public int length()  //放回该字符串的长度

String str = new String("asdfzxc");
int strlength = str.length();//strlength = 7

2.2 求字符串某一位置字符

public char charAt(int index)  //返回字符串中指定位置的字符,从0~length()-1

String str = new String("asdfzxc");
char ch = str.charAt(4);//ch = z

2.3 提取字串

用String类的substring方法可以提取字符串中的子串,该方法有两种常用参数:
1)public String substring(int beginIndex)//该方法从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回。
2)public String substring(int beginIndex, int endIndex)//该方法从beginIndex位置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回。

String str1 = new String("asdfzxc");
String str2 = str1.substring(2);//str2 = "dfzxc"
String str3 = str1.substring(2,5);//str3 = "dfz"

2.4 字符串比较

1)public int compareTo(String anotherString)//该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0。
2)public int compareToIgnore(String anotherString)//与compareTo方法相似,但忽略大小写。
3)public boolean equals(Object anotherObject)//比较当前字符串和参数字符串,在两个字符串相等的时候返回true,否则返回false。
4)public boolean equalsIgnoreCase(String anotherString)//与equals方法相似,但忽略大小写

String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b = str1.compareToIgnoreCase(str2);//b=0
boolean c = str1.equals(str2);//c=false
boolean d = str1.equalsIgnoreCase(str2);//d=true

2.5 字符串连接

public String concat(String str)//将参数中的字符串str连接到当前字符串的后面,效果等价于"+"。

String str = "aa".concat("bb").concat("cc");
//相当于String str = "aa"+"bb"+"cc";

2.6 字符串中单个字符查找

1)public int indexOf(int ch/String str)//用于查找当前字符串中字符或子串,返回字符或子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。
2)public int indexOf(int ch/String str, int fromIndex)//改方法与第一种类似,区别在于该方法从fromIndex位置向后查找。
3)public int lastIndexOf(int ch/String str)//该方法与第一种类似,区别在于该方法从字符串的末尾位置向前查找。
4)public int lastIndexOf(int ch/String str, int fromIndex)//该方法与第二种方法类似,区别于该方法从fromIndex位置向前查找。

String str = "I am a good student";
int a = str.indexOf('a');//a = 2
int b = str.indexOf("good");//b = 7
int c = str.indexOf("w",2);//c = -1
int d = str.lastIndexOf("a");//d = 5
int e = str.lastIndexOf("a",3);//e = 2

2.7 字符串中字符大小写转换

1)public String toLowerCase()//返回将当前字符串中所有字符转换成小写后的新串
2)public String toUpperCase()//返回将当前字符串中所有字符转换成大写后的新串

String str = new String("asDF");
String str1 = str.toLowerCase();//str1 = "asdf"
String str2 = str.toUpperCase();//str2 = "ASDF"

2.8 字符串中字符的替换

1)public String replace(char oldChar, char newChar)//用字符newChar替换当前字符串中所有的oldChar字符,并返回一个新的字符串。
2)public String replaceFirst(String regex, String replacement)//该方法用字符replacement的内容替换当前字符串中遇到的第一个和字符串regex相匹配的子串,应将新的字符串返回。
3)public String replaceAll(String regex, String replacement)//该方法用字符replacement的内容替换当前字符串中遇到的所有和字符串regex相匹配的子串,应将新的字符串返回。

String str = "asdzxcasd";
String str1 = str.replace('a','g');//str1 = "gsdzxcgsd"
String str2 = str.replace("asd","fgh");//str2 = "fghzxcfgh"
String str3 = str.replaceFirst("asd","fgh");//str3 = "fghzxcasd"
String str4 = str.replaceAll("asd","fgh");//str4 = "fghzxcfgh"

 2.9 其他类方法

1)String trim()//截去字符串两端的空格,但对于中间的空格不处理。

String str = " a sd ";
String str1 = str.trim();
int a = str.length();//a = 6
int b = str1.length();//b = 4

2)boolean startsWith(String prefix)boolean endWith(String suffix)//用来比较当前字符串的起始字符或子字符串prefix和终止字符或子字符串suffix是否和当前字符串相同,重载方法中同时还可以指定比较的开始位置offset。

String str = "asdfgh";
boolean a = str.startsWith("as");//a = true
boolean b = str.endWith("gh");//b = true

3)regionMatches(boolean b, int firstStart, String other, int otherStart, int length)//从当前字符串的firstStart位置开始比较,取长度为length的一个子字符串,other字符串从otherStart位置开始,指定另外一个长度为length的字符串,两字符串比较,当b为true时字符串不区分大小写。
4)contains(String str)//判断参数s是否被包含在字符串中,并返回一个布尔类型的值。

String str = "student";
str.contains("stu");//true
str.contains("ok");//false

 5)String[] split(String str)//将str作为分隔符进行字符串分解,分解后的字字符串在字符串数组中返回。

String str = "asd!qwe|zxc#";
String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] = "zxc";

补:intern方法 

  • 当常量池中不存在"abc"这个字符串的引用,将这个对象的引用加入常量池,返回这个对象的引用。
  • 当常量池中存在"abc"这个字符串的引用,返回这个对象的引用;
    String a="hello";
    String b=new String("hello");
    Stirng c=b.intern();
    a==c?   //true

3 字符串与基本类型的转换

3.1 字符串转换为基本类型

java.lang包中有Byte、Short、Integer、Float、Double类的调用方法:
1)public static byte parseByte(String s)
2)public static short parseShort(String s)
3)public static short parseInt(String s)
4)public static long parseLong(String s)
5)public static float parseFloat(String s)
6)public static double parseDouble(String s) 

如:

int n = Integer.parseInt("12");
float f = Float.parseFloat("12.34");
double d = Double.parseDouble("1.124");

3.2 基本类型转换为字符串类型

String类中提供了String valueOf()放法,用作基本类型转换为字符串类型。
1)static String valueOf(char data[])
2)static String valueOf(char data[], int offset, int count)
3)static String valueOf(boolean b)
4)static String valueOf(char c)
5)static String valueOf(int i)
6)static String valueOf(long l)
7)static String valueOf(float f)
8)static String valueOf(double d) 

如:

String s1 = String.valueOf(12);
String s1 = String.valueOf(12.34);

3.3 进制转换

使用Long类中的方法得到整数之间的各种进制转换的方法:
Long.toBinaryString(long l)
Long.toOctalString(long l)
Long.toHexString(long l)
Long.toString(long l, int p)//p作为任意进制

4 包装类的用处

  • 实现基本类型之间的转换
  • 便于函数传值
  • 在一些地方要用到Object的时候方便将基本数据类型转换

5 StringBuffer

5.1 概述

        对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。而StringBuffer就可以解决这个问题。

5.2 构造方法

public StringBuffer():				无参构造方法
public StringBuffer(int capacity):	指定容量的字符串缓冲区对象
public StringBuffer(String str):		指定字符串内容的字符串缓冲区对象

5.3 StringBuffer的获取长度及容量方法

  • public int capacity():返回当前容量。 理论值
  • public int length():返回长度(字符数)。 实际值

5.4 StringBuffer的添加功能

  • public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
  • public StringBuffer append(String str) 可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身

5.5 StringBuffer的删除功能

  • public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
  • public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身

5.6 StringBuffer的替换和反转功能

  • public StringBuffer replace(int start,int end,String str): 从start开始到end用str替换
  • public StringBuffer reverse(): 字符串反转

5.7 StringBuffer的截取功能及注意事项

  • public String substring(int start): 从指定位置截取到末尾
  • public String substring(int start,int end): 截取从指定位置开始到结束位置,包括开始位置,不包括结束位置
  • 注意:返回值类型不再是StringBuffer本身

5.8 StringBuffer和String的相互转换

  • String – StringBuffer

    a:通过构造方法
    b:通过append()方法

  • StringBuffer – String
    a: 使用substring方法
    b:通过构造方法
    c:通过toString()方法

6 String、StringBuffer、StringBuilder的区别

共同点:都是final类,不允许被继承,主要是从性能和安全性上考虑的。因为这几个类都是经常被使用着,且考虑到防止其中的参数被参数修改影响到其他的应用。

  • StringBuffer是线程安全,可以不需要额外的同步用于多线程中;
  • StringBuilder是非同步,运行于多线程中就需要使用着单独同步处理,但是速度就比StringBuffer快多了;
  • StringBuffer与StringBuilder两者共同之处:可以通过append、indert进行字符串的操作。

6.1运行速度

        StringBuilder>StringBuffer>String

        String最慢的原因:String为字符串常量,而StringBuffer和StringBuilder均为字符串变量 ,即String对象一旦创建之后该对象是不可更改的,但后两者的对象是变量,是可以更改的。而StringBuilder和StringBuffer的对象是变量,对变量进行操作就是直接对该对象进行更改,而不进行创建和回收的操作,所以速度要比String快很多。

6.2 线程安全

        在线程安全上,StringBuilder是线程不安全的,而StringBuffer是线程安全的。

        如果一个StringBuffer对象在字符串缓冲区被多个线程使用时,StringBuffer中很多方法可以带有synchronized关键字,所以可以保证线程是安全的,但StringBuilder的方法则没有该关键字,所以不能保证线程安全,有可能会出现一些错误的操作。所以如果要进行的操作是多线程的,那么就要使用StringBuffer,但是在单线程的情况下,还是建议使用速度比较快的StringBuilder。

6.3 总结

  • String:适用于少量的字符串操作的情况
  • StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况
  • StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况

6.4 常考题型及详解

探秘Java中的String、StringBuilder以及StringBuffer - Matrix海子 - 博客园 (cnblogs.com)icon-default.png?t=M276https://www.cnblogs.com/dolphin0520/p/3778589.htmljava中String、StringBuffer和StringBuilder的区别(简单介绍) - 韦邦杠 - 博客园 (cnblogs.com)icon-default.png?t=M276https://www.cnblogs.com/weibanggang/p/9455926.html

7 Java各个主要包

1. java.awt:提供了绘图和图像类,主要用于编写GUI程序,包括按钮、标签等常用组件以及相应的事件类。

2. java.lang:java的语言包,是核心包,默认导入到用户程序,包中有object类,数据类型包装类,数学类,字符串类,系统和运行时类,操作类,线程类,错误和异常处理类,过程类。

3. java.io:包含提供多种输出输入功能的类。

4. java.net: 包含执行与网络有关的类,如URL,SCOKET,SEVERSOCKET等。

5. java.applet:包含java小应用程序的类。

6. java.util:包含集合框架、遗留的 collection 类、事件模型、日期和时间设施、国际化和各种实用工具类(字符串标记生成器、随机数生成器和位数组、日期Date类、堆栈Stack类、向量Vector类等)。集合类、时间处理模式、日期时间工具等各类常用工具包。
7. java.sql:提供使用 JavaTM 编程语言访问并处理存储在数据源(通常是一个关系数据库)中的数据的 API。

二、Math 

1 算数计算

  • Math.sqrt() : 计算平方根
  • Math.cbrt() : 计算立方根
  • Math.pow(a, b) : 计算a的b次方
  • Math.max( , ) : 计算最大值
  • Math.min( , ) : 计算最小值
  • Math.abs() : 取绝对值
    System.out.println(Math.sqrt(16)); // 4.0
    System.out.println(Math.cbrt(8)); // 2.0
    System.out.println(Math.pow(3, 2)); // 9.0
    System.out.println(Math.max(2.3, 4.5));// 4.5
    System.out.println(Math.min(2.3, 4.5));// 2.3
    
    /**
     * abs求绝对值
     */
    System.out.println(Math.abs(-10.4)); // 10.4
    System.out.println(Math.abs(10.1)); // 10.1
    
    

2 进位 

  • Math.ceil(): 天花板的意思,就是逢余进一
  • Math.floor() : 地板的意思,就是逢余舍一
  • Math.rint(): 四舍五入,返回double值。注意.5的时候会取偶数
  • Math.round(): 四舍五入,float时返回int值,double时返回long值
    /**
    * ceil天花板的意思,就是逢余进一
     */
    System.out.println(Math.ceil(-10.1)); // -10.0
    System.out.println(Math.ceil(10.7)); // 11.0
    System.out.println(Math.ceil(-0.7)); // -0.0
    System.out.println(Math.ceil(0.0)); // 0.0
    System.out.println(Math.ceil(-0.0)); // -0.0
    System.out.println(Math.ceil(-1.7)); // -1.0
    
    System.out.println("-------------------");
    
    /**
     * floor地板的意思,就是逢余舍一
     */
    System.out.println(Math.floor(-10.1)); // -11.0
    System.out.println(Math.floor(10.7)); // 10.0
    System.out.println(Math.floor(-0.7)); // -1.0
    System.out.println(Math.floor(0.0)); // 0.0
    System.out.println(Math.floor(-0.0)); // -0.0
    
    System.out.println("-------------------");
    
    /**
     * rint 四舍五入,返回double值 注意.5的时候会取偶数 异常的尴尬=。=
     */
    System.out.println(Math.rint(10.1)); // 10.0
    System.out.println(Math.rint(10.7)); // 11.0
    System.out.println(Math.rint(11.5)); // 12.0
    System.out.println(Math.rint(10.5)); // 10.0
    System.out.println(Math.rint(10.51)); // 11.0
    System.out.println(Math.rint(-10.5)); // -10.0
    System.out.println(Math.rint(-11.5)); // -12.0
    System.out.println(Math.rint(-10.51)); // -11.0
    System.out.println(Math.rint(-10.6)); // -11.0
    System.out.println(Math.rint(-10.2)); // -10.0
    
    System.out.println("-------------------");
    /**
     * round 四舍五入,float时返回int值,double时返回long值
     */
    System.out.println(Math.round(10)); // 10
    System.out.println(Math.round(10.1)); // 10
    System.out.println(Math.round(10.7)); // 11
    System.out.println(Math.round(10.5)); // 11
    System.out.println(Math.round(10.51)); // 11
    System.out.println(Math.round(-10.5)); // -10
    System.out.println(Math.round(-10.51)); // -11
    System.out.println(Math.round(-10.6)); // -11
    System.out.println(Math.round(-10.2)); // -10
    
    

    3 随机数

  • Math.random(): 取得一个[0, 1)范围内的随机数
    System.out.println(Math.random()); // [0, 1)的double类型的数
    System.out.println(Math.random() * 2);//[0, 2)的double类型的数
    System.out.println(Math.random() * 2 + 1);// [1, 3)的double类型的数
    
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值