26.API文档中的常用工具类

Object类

Object类中的常用方法:
equals():
用来比较两个对象是否相等 --比较的是对象的内存地址。
toString():
如果子类没有重写父类Object类的toString方法,这个时候直接输出对象,结果是对象的内存地址
如果子类重写父类Object类中的toString方法,这个时候直接输出对象,结果是执行子类重写后的toStirng方法,输出对象的字符串表现形式
hashCode(): 获取对象的哈希码值-- 我们把哈希码值看作对象的内存地址
getClass(): 显示对象是由哪个类创建的
5.finalize(): 垃圾回收器

package com.woniuxy.api.object;

public class Test {
	public static void main(String[] args) {
		User user1 = new User();
		User user2 = new User();
		// equals方法,用来比较两个对象是否相等  --比较的是对象的内存地址
		System.out.println(user1.equals(user2));
		int hash1 = user1.hashCode();
		int hash2 = user2.hashCode();
		/**
		 * hashCode方法,获取对象的哈希码值-- 我们把哈希码值看作对象的内存地址
		 */
		System.out.println(hash1);
		System.out.println(hash2);
		/**
		 * getClass方法,显示对象是由哪个类创建的
		 */
		System.out.println(user1.getClass());
	}
}

equals和“==”的区别

  • 在java开发中,所有的引用数据类型的值,都是使用equals方法来比较两个是否相等,结果是个布尔类型 --比较的是对象的内存地址。
  • equals方法,用来比较两个对象是否相等,结果是布尔类型 --比较的是对象的内存地址
  • == 作用于引用数据类型的比较,比较的是对象的内存地址是否相等
  • == 作用于基本数据类型的比较,比较的是两个变量的值是否相等。

数组工具类Arrays

java.util.Arrays是一个与数组相关的工具类,里面提供了大量的静态方法,用来实现数组的一些操作。下面只介绍几个常见操作。

import java.util.Arrays;

public class Test {
	public static void main(String[] args) {
		// 创建数组
		int[] arr1 = {3,1,6,5,7};
		// 1.数组扩容
		int[] arr2 = Arrays.copyOf(arr1, 10);
		for(int i=0;i<arr2.length;i++) {
			System.out.println(arr2[i]);//[3,1,6,5,7,0,0,0,0,0]
		}
		// 2.数组升序排列
		// 如果数组是数值类型,那么默认按照从小到大升序
		// 如果数组是字符串类型,那么默认按照字母升序
		Arrays.sort(arr1);
		for(int e:arr1) {
			System.out.println(e);//[1,3,5,6,7]
		}
		// 3.数组查找--使用二分法去数组中查找元素,前提是数组必须是升序的,结果是元素在数组中的下标
		int result = Arrays.binarySearch(arr1, 7);
		System.out.println(result);//4
		// 4.数组转字符串,再输出。该方法能将任何数据类型的数组,变成字符串输出。
		System.out.println(Arrays.toString(arr1));//[1, 3, 5, 6, 7]
	}
}

数学工具类Math

java.lang.Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算相关的操作,直接使用,无需导包。
Math类常用方法:

  1. public static double abs(double num):获取绝对值,有多种重载。
  2. public static double ceil(double num):向上取整
  3. public static double floor(double num):向下取整
  4. public static long round(double num):四舍五入
  5. Math.PI代表近似的圆周率常量(double)。
public class Test {
	public static void main(String[] args) {
		// 1.圆周率PI
		System.out.println(Math.PI);
		// 2.取绝对值--负数的绝对值是正数,正数的绝对值是它本身
		System.out.println(Math.abs(5));//5
		System.out.println(Math.abs(-5));//5
		// 3.向上取整
		System.out.println(Math.ceil(3.3));//4.0
		// 4.向下取整
		System.out.println(Math.floor(3.3));//3.0
		// 5.四舍五入。小数点后大于等于5,向上取整,小于5则向下取整,结果是一个整数
		System.out.println(Math.round(3.5));
		System.out.println(Math.round(3.2));
		// 6.随机数 0<=Math.random< 1
		double ran1 = Math.random();
		System.out.println(ran1);
		// 自动生成一个1到100之间的整数
		int ran2 = (int)(Math.random()*100)+1;
		System.out.println(ran2);		
	}

UUID类

随机生成一个32位的随机字符串。

import java.util.UUID;
public class Test {
	public static void main(String[] args) {

		String uuid =UUID.randomUUID().toString();
		System.out.println(uuid);	
	}
}

日历类(Calendar)

Calendar 类是一个抽象类。Calendar 的 getInstance 方法返回一个Calendar 对象,其日历字段已由当前日期和时间初始化
Calendar now = Calendar.getInstance();
Calendar类可以让我们像看日历一样得到这个时间的所有属性。

package com.woniuxy.api4;

import java.util.Calendar;
public class Test1 {
	public static void main(String[] args) {
		//1.获取到Calendar的对象
		Calendar calendar = Calendar.getInstance();
		//2.获取日历
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		System.out.println(year);
		System.out.println(month);//月份从0开始
		System.out.println(day);
		System.out.println(hour);
		System.out.println(minute);
		System.out.println(second);
	}
}

日期类(Date)

常用方法:

方法说明
getTime()返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
		/**
		 * 	时间原点:以格林威治时区的 1970年1月1日0时0分0秒0毫秒作为时间原点
		 * 	中国的时区比格林威治时区多8个小时
		 *	 日期类 Date
		 */
		//1.创建Date对象
		Date date1 = new Date();
		//2.输出日期对象
		System.out.println(date1);
		//3.获取date对象表示的毫秒数
		long time = date1.getTime();
		System.out.println(time);
		//4把一个指定的毫秒数转成Date
		Date date2 = new Date();
		System.out.println(date2);

格式化日期

  • 日期格式转换工具类
  • SimpleDateFormat sdf=new SimpleDateFormat(“要输出的日期格式”);
  • 格式
  • yyyy:年
  • MM:月
  • dd:日
  • HH:时
  • mm:分
  • ss:秒

作用: 可以把Date转换成对应的字符串,把字符串转换成Date对象。

常用方法

方法说明
String format(Date d)将日期转为字符串
Date parse(String str)将字符串转为日期格式

public class Test3 {
	public static void main(String[] args) throws ParseException{
		//1.创建日期格式转换工具类的对象 2021年08月27日 17:45:50
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//2.创建Date对象
		Date date = new Date();
		//3.把date对象转字符串
		String dateToStr = sdf.format(date);
		System.out.println(dateToStr);
		
		//4.把字符串转Date对象
		String str = "2021-01-01 00:00:01";
		Date strToDate = sdf.parse(str);
		System.out.println(strToDate);
	}
}

Random类

Random类:生成随机数。
需要注意的是Random类中的方法没有static修饰,不是静态方法,因此不能全局调用。要想使用Random中的方法需要先创建Random类的对象:Random random = new Random();

import java.util.Random;
public class Test {
	public static void main(String[] args) {
		Random random = new Random();
		//生成0-10之间的随机数
		int nextInt = random.nextInt(10);
		System.out.println(nextInt);	
	}
}

包装类

java语言是一个面向对象的语言,但是java中的基本数据类型却不是面向对象的,但是我们在实际使用中经常将基本数据类型转换成对象,便于操作,这时,我们就需要将基本类型数据转化成对象!
包装类的继承关系:

基本数据类型包装类型
byteByte
shortShort
charCharacter
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean

这些包装类型的方法都是类似的,下面我们以Integer为例,介绍一下包装类的相关方法。

  1. 将字符串转换为int类型
//将字符串转换为int类型--字符串的字面值必须看着就像一个数字
		String str = "123";
		int n = Integer.parseInt(str);
		System.out.println(n);
  1. Integer跟int值的区别:
    Integer属于引用数据类型,有属性和方法
    int属于基本数据类型,没有属性也没有方法
    Integer的值比int多了一个null

在java中代表空,表示没有值,不占用内存空间
所有的引用数据类型都可以赋null

  1. 自动装箱和自动拆箱

自动装箱

自动把int类型的数字转换成Integer,该过程自动调用valueOf(int i)

int a = 100;
Integer b = a; 等价于 Integer b = Integer.valueOf(100) 

自动拆箱

自动把Integer类型的数字转换成int,该过程自动调用 intValue()

    Integer a = 100;等价于Integer a = new Integetr(100)
	int b = a;

java的128陷阱

Integer 有一个缓冲区,java会提前创建范围在-128到127的Integer对象存储到缓冲区。当我们给Integer类型的变量赋值的时候,如果值在-128到127之间,会从缓冲区把相应的Integer对象赋值给变量。

  • 对于引用类型,==比较的是两个对象的内存地址值
  • 对于基本数据类型,==比较的是两个变量的值
package com.woniuxy.api.baozhuanglei;

public class Test2 {
	public static void main(String[] args) {	
		Integer i = 10;// 把缓冲区中值为10的Integer对象赋值给变量i
	    Integer j = 10;// 把缓冲区中值为10的Integer对象赋值给变量j
	    // 比较对象的内存地址,i和j共用一个对象的地址值,结果为true
	    System.out.println(i == j);
	    Integer a = 128;// 给变量a赋值128时,值得范围超过了缓冲区的范围,此时会创建新的Integer对象
	    Integer b = 128;// 创建新的Integer对象
	    // 这时,a和b不是同一个对象,内存地址值不一样,结果为false
	    System.out.println(a == b);
	    int k = 10;
	    // k为基本数据类型,i为包装类型,两者运算时,包装类型会自动拆箱,把Integer类型的数字转为int类型的数字,再比较两者的值
	    System.out.println(k == i);// true
	    int kk = 128;
	    System.out.println(kk == a);// a自动拆箱成int类型,再和kk作比较true
	    Integer m = new Integer(10);
	    Integer n = new Integer(10);
	    // m和n是创建的两个不同的对象,因此内存地址值不一样,结果为false
	    System.out.println(m == n);
	    String ass = "hello world";
	    String bss = "hello world";
	    System.out.println("===================");
	    System.out.println(ass ==bss);
	}
}

总结:

  • 分析源码我们可以知道在 i >= -128 并且 i <= 127 的时候,之直接从缓存中把值取出来赋值给变量。那么第一个打印结果因为 i
    = 10 在缓存表示范围内,所以为 true。
  • 从上面的分析我们知道,128是不在-128到127之间的,所以第一次创建新的Integer对象,第二次也创建了一个新的Integer对象。故打印结果为false。
  • 基本数据类型跟包装类型比较,直接比较值
  • 基本数据类型跟包装类型比较,直接比较值
  • new出来的都是新对象

注意:Integer类重写了equals方法,重写后的作用是用来比较2个Integer类型变量的值
比较引用数据类型变量的值,使用equals

String类

String类是被final修饰的类,是最终类,因此不可以被继承。
String 类代表字符串。java程序中的所有字符串字面值(如"abc")都作为此类的实例实现,即字符串。对象所有通过new关键字创建的字符串,也是字符串对象。
所有的String类对象都是常量。

1.字符串的比较相关方法

public class TestString {
	public static void main(String[] args) {
		// 在java中把字面值"Java 基础版"作为String类的对象
		String str1 = "Java 基础版";
		// 使用new关键字创建String类对象
		String str2 = new String();
		// 这一行代码创建了2个对象:  "Java 高级版"是一个对象,同时也new了一个新字符串对象str3
		String str3 = new String("Java 高级版");	
		/**
		 * 1.比较字符串的值是否相等
		 */
		String s1 = "hello";//创建了一个字符串对象hello
		//首先去内存中找hello这个字符串对象是否存在,如果不存在则重新创建对象,如果存在,则把对象赋值给相应的变量
		String s2 = "hello";
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s1 == s2);//s1,s2是同一个字符串对象
		
		System.out.println("-------------------------");
		String s3 = new String("hello");//s3是new出来的,是一个新的对象,而hello是已经创建的对象
		System.out.println(s3);
		System.out.println(s1 == s3);

		String ss1 = "hello world";
		String ss2 = new String("hello world");
		//==比较对象的内存地址
		System.out.println(ss1 == ss2);//false		
		//String类对Object类的equals方法进行了重写,重写后用来比较2个字符串的值是否相等
		System.out.println(ss1.equals(ss2));//true		
	}
}

2.字符串的判断相关方法

public class TestString {
	public static void main(String[] args) {	
		String s2 = "www.woniuxy.com";
		// 1.判断此字符串是否以指定的前缀开始
		boolean isStart = s2.startsWith("www");
		System.out.println(isStart);//true
		// 2.判断字符串是否以指定的后缀结束
		boolean isEnd = s2.endsWith("com");
		System.out.println(isEnd);//true
		// 3.判断字符串是否为空字符串
		String s3 = "";
		System.out.println("");
		String result = s3.length()==0?"空":"不空";
		// 4.判断字符串中是否包含包含指定内容,按顺序
		boolean isContains = s2.contains("woniu");
		System.out.println(isContains);//true
		boolean isContains2 = s2.contains("wonu");
		System.out.println(isContains2);//false
		// 5.判断两个字符串的值是否相等,忽略大小写
		String s4 = "WWW.WONIUXY.COM";
		boolean isE = s2.equalsIgnoreCase(s4);
		System.out.println(isE);//true
	}

3.字符串的获取相关方法

public class TestString {
	public static void main(String[] args) {
		String s1= "hello";
		// 1.获取字符串的长度
		int len = s1.length();
		System.out.println(len);//5
		/**
		 * 2. 通过下标获取字符串中某个字符,字符串中每个字符都有下标,下标从0开始
		 */
		char c= s1.charAt(4);
		System.out.println(c);//o
		// 3.获取指定字符首次出现的位置,结果是该字符下标
		int index = s1.indexOf("l");
		System.out.println(index);//
		
		
		
		String s2 = "www.woniuxy.com";
		// 1.判断此字符串是否以指定的前缀开始
		boolean isStart = s2.startsWith("www");
		System.out.println(isStart);//true
		// 2.判断字符串是否以指定的后缀结束
		boolean isEnd = s2.endsWith("com");
		System.out.println(isEnd);//true
		// 3.判断字符串是否为空字符串
		String s3 = "";
		System.out.println("");
		String result = s3.length()==0?"空":"不空";
		// 4.判断字符串中是否包含包含指定内容,按顺序
		boolean isContains = s2.contains("woniu");
		System.out.println(isContains);//true
		boolean isContains2 = s2.contains("wonu");
		System.out.println(isContains2);//false
		// 5.判断两个字符串的值是否相等,忽略大小写
		String s4 = "WWW.WONIUXY.COM";
		boolean isE = s2.equalsIgnoreCase(s4);
		System.out.println(isE);//true
	}

4.字符串的转换相关方法

// 字符串<===>数组
public class TestString3 {
	public static void main(String[] args) {
	String s1 = "woniuxy";
	// 把字符串转字符数组
	char[] charArr1 = s1.toCharArray();
	for(int i = 0;i<charArr1.length;i++) {
		System.out.println(charArr1[i]);
	}
	// 把字符数组转字符串
	char[] charArr2 = {'a','b','c',	'd'};
	String str = new String(charArr2);
	System.out.println(str);
	}
}

5.字符串的其他方法

// 替换、切割、截取、去除空格
import java.util.Arrays;
public class TestString4 {
	public static void main(String[] args) {
		String s1 = "hello";
		// 1.替换--替换后得到新的字符串
		String newStr1= s1.replace("ell", "www");
		System.out.println(newStr1);
		// 2.切割--不能以.进行切割
		String s2 = "abc@ddd@eee";
		String [] strArr = s2.split("@");
		System.out.println(Arrays.toString(strArr));
		// 3.截取
		String s3 = "我在学java";
		// 	从指定的下标开始截取,一直截取到字符串的末尾
		String newSub1 = s3.substring(1);
		System.out.println(newSub1);
		//  指定范围截取字符串,不包含结束下标,左闭右开
		String newSub2 = s3.substring(1,4);
		System.out.println(newSub2);
		// 4.去除字符串首尾空格
		String s4 = " aaa bbb ccc ";
		String newTrim = s4.trim();
		System.out.println(newTrim);
		// 5.去掉字符串的所有空格
		String s5 = " aaa bbb ccc ";
		String newRep = s5.replace(" ","");
		System.out.println(newRep);
		// 6.获取指定字符在字符串中最后一次出现处的索引值。如果不存在这个字符,则返回-1
		String s6 ="abcd.efg.hi";
		int lastIndexOf =s6.lastIndexOf(".");
		System.out.println(lastIndexOf);
	}
}

6.字符串的循环遍历

public class TestString5 {
	public static void main(String[] args) {
		String s1 = "hello";
		//使用for循环遍历字符串
		for(int i=0;i<s1.length();i++) {
			//通过下标取出字符串中的每一个字符
			char c = s1.charAt(i);
			// 输出
			System.out.println(c);
		}
	}
}

7.字符串的哈希值

因为Object类是所有类的父类,那么String类肯定就继承了Object类。在Object类中hashCode方法的作用是获取对象的hash码值,我们把对象的hash码值看作对象的内存地址。但是String类重写了Object类的hashCode方法,重写后的hash值将不再与字符串的内存地址有关,而是跟字符串的值相关。 值一样,hash值一定一样,值不一样,hash值肯一样。

package com.woniuxy.api.string;
public class TestString6 {
	public static void main(String []args) {
		String s1= "hello";
		String s2 = "hello";
		System.out.println(s1.hashCode());
		System.out.println(s2.hashCode());
		System.out.println("-------------------");
		String s3 = new String("hello");
		System.out.println(s3.hashCode());
		System.out.println("-------------------");
		String s4= "Aa";
		String s5 = "BB";
		System.out.println(s4.hashCode());
		System.out.println(s5.hashCode());
		System.out.println("-------------------");
		String s6= "xxx";
		String s7 = "yyy";
		System.out.println(s6.hashCode());
		System.out.println(s7.hashCode());
		System.out.println("-------------------");	
	}
}

在这里插入图片描述

8.字符串练习

练习1:

现在有一个字符串:“hello world,hello china”,将字符串反转成"anihc olleh,dlrow olleh"

String str = "hello world,hello china";
		//方式一
		//1.把字符串转字符数组
		char[] charArr = str.toCharArray();
		//2.数组反转
		for (int i = 0; i < charArr.length/2; i++) {
			char temp = charArr[i];
			charArr[i] = charArr[charArr.length-1-i];
			charArr[charArr.length-1-i] = temp;
		}
		//3.数组转字符串
		String newStr = new String(charArr);
		//4.输出新的字符串
		System.out.println(newStr);
		
		//方式二
		//字符串倒序遍历
		for(int i = str.length()-1;i>=0;i--) {
			char c = str.charAt(i);
			System.out.print(c);
		}

练习2:

现在有一个字符串:“hello world,hello china”,将字符串反转成"china hello,world hello"

String str = "hello world,hello china";
		//1.切割
		String[] arr = str.split(",");
		String[] arrOne = arr[0].split(" ");
		String[] arrTwo = arr[1].split(" ");
		//2.字符串拼接
		String newStr = arrTwo[1]+ " " +arrTwo[0]+ "," +arrOne[1]+ " " +arrOne[0];
		System.out.println(newStr);

练习3:

3、现在有一个字符串:“abcd12absdfabsdfabsadfba”,统计该字符串中"ab"出现的次数。

		String str = "abcd12absdfabsdfabsadfba";
		String[] strArr = str.split("ab");
		System.out.println(Arrays.toString(strArr));
		int count = strArr.length - 1;
		System.out.println("ab出现的次数为"+count);

练习4:

在控制台输入一个字符串,将其中的大写字母变成小写,将小写字母变成大写,得到一个新的字符串,然后输出. 比如:“abDH”—>“ABdh” ;

package com.woniuxy.api.day16_test;

import java.util.Arrays;
import java.util.Scanner;
public class Test4 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个字符串");
		String str = sc.next();
		// 把字符串转字符数组
		char[] arr = str.toCharArray();
		// 循环遍历字符数组,修改数组中的元素
		for (int i = 0; i < arr.length; i++) {
			// 如果是大写字母,则转为小写字母
			if (arr[i] >= 'A' && arr[i] <= 'Z') {
				arr[i] = (char) (arr[i] + 32);
				// 如果是小写字母,则转为大写字母
			} else if (arr[i] >= 'a' && arr[i] <= 'z') {
				arr[i] = (char) (arr[i] - 32);
			}
		}
		// 把字符串转字符数组
		String str2 = new String(arr);
		System.out.println(str2);
	}
}

练习5:

给定一个前面有空格和后面有空格的字符串,写代码去掉前导空白和后导空白,不允许直接使用replace()和trim()方法。

import java.util.Scanner;
public class Test5 {
	public static void main(String[] args) {
		String str = "  qwerty uiop  ";
		// 把字符串转字符数组 
		char[] array = str.toCharArray();
		int startIndex = 0;//第一个非空格的字符下标
		int endIndex = 0;//最后一个非空格字符的下标
		// 1.找到第一个非空格字符的下标
		for (int i = 0; i < str.length(); i++) {
			// 取字符串中的每个字符
			char c= str.charAt(i);
			if(c !=' ') {
				startIndex = i;//把找到的下标存储在变量startIndex
				break;
			}
		}
		// 2.找到最后一个非空格字符的下标
		for (int i = str.length()-1; i >=0; i--) {
			char c=str.charAt(i);
			if(c !=' ') {
				endIndex = i;
				break;
			}
		}
		// 3.截取
		String newStr = str.substring(startIndex,endIndex+1);
		// 4.输出
		System.out.println(newStr);
	}
}

进阶1:

从控制台接受一个字符,判断是大写字母还是小写字母还是数字字符, 如果都不是就输出不是字母和数字,如果是大写字母就将其转为小写并输出,如果是小写字母就将其转为大写字母输出。

import java.util.Scanner;
public class Test6 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个字符");
		char c = sc.next().charAt(0);
		if (c >= 'A' && c <= 'Z') {
			char num = (char) (c + 32);
			System.out.println(num);
		} else if (c >= 'a' && c <= 'z') {
			char num = (char) (c - 32);
			System.out.println(num);
		} else if (c >= '0' && c <= '9') {
			System.out.println("是数字");
		} else {
			System.out.println("您输入的不是字母和数字");
		}
	}
}

进阶2:极具代表性的一题

验证用户输入的是否是合法的标识符,规定一种合法的标识符为:以字母或_、$开头,后面可以由字母,数字下划线、 $组成,如果不合法提示对应的错误信息。
方法一:

import java.util.Scanner;
public class Test7 {
	public static void main(String[] args) {
		// 2.验证用户输入的是否是合法的标识符,规定一种合法的标识符为:以字母或_、$开头,
//		后面可以由字母,数字下划线、$组成,如果不合法提示对应的错误信息
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个标识符");
		String str = sc.next();
		// 1.判断标识符的第一位是否合法
		char startChar = str.charAt(0);
		if ((startChar >= 'A' && startChar <= 'Z') || (startChar >= 'a' && startChar <= 'z') || startChar == '_'
				|| startChar == '$') {
			// 2.判断其他位是否合法--对字符串进行遍历
			for (int i = 1; i < str.length(); i++) {
				char otherChar = str.charAt(i);
				if ((otherChar >= 'A' && otherChar <= 'Z') || (otherChar >= 'a' && otherChar <= 'z') || otherChar == '_'
						|| otherChar == '$' || (otherChar >= '0' && otherChar <= '9')) {
					continue;
				} else {
					System.out.println("不合法");
					System.exit(0);
				}
			}
			System.out.println("合法");
		} else {
			System.out.println("不合法");
		}
	}
}

方法二:

import java.util.Scanner;
public class Test7 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个标识符");
		String str = sc.next();
		// 定义变量存储标识符的状态
		boolean flag = false;//false代表不合法,true代表合法
		// 1.判断标识符的第一位是否合法
		char startChar = str.charAt(0);
		if ((startChar >= 'A' && startChar <= 'Z') || (startChar >= 'a' && startChar <= 'z') || startChar == '_'
				|| startChar == '$') {
			// 2.判断其他位是否合法--对字符串进行遍历
			for (int i = 1; i < str.length(); i++) {
				char otherChar = str.charAt(i);
				if ((otherChar >= 'A' && otherChar <= 'Z') || (otherChar >= 'a' && otherChar <= 'z') || otherChar == '_' || otherChar == '$' || (otherChar >= '0' && otherChar <= '9')) {
					flag=true;
				} else {
					flag = false;
					break;//如果不合法直接结束for循环
				}
			}
		} else {
			flag = false;
		}
		// 判断并输出最终的结果
		if(flag) {
			System.out.println("合法");
		}else {
			System.out.println("不合法");
		}
	}
}

StringBuff类

前面我们了解到,所有的字符串字面值都是String类的对象,同时也是常量。不管是字符串的创建还是字符串的拼接,都一定会创建新的字符串的对象。当一个程序中需要使用很多字符串或者字符串的拼接操作时,就会随之产生很多个对象,而对象的创建是一个非常消耗内存资源且非常耗时的操作。
由此,为了解决字符串拼接会创建新对象的问题,在jdk的不断更新中,java引入了新的类StringBffer类和StringBuilder类。这样可以很好的节约内存空间,提高程序的运行速度。

package com.woniuxy.api.StringBuffer;
public class StringBufferTest {
	public static void main(String[] args) {
		String s1 = "hello";
		String s2 = "world";
		String s3 = "xxx";
		String s4 = s1 + s2 + s3;
		// 上面的操作中一个创建了四次字符串对象
		// 创建StringBuffer对象 --可变长度字符串
		StringBuffer sb = new StringBuffer();
		sb.append(s1);
		sb.append(s2);
		sb.append(s3);
		System.out.println(sb);
		// 3.字符串的反转
		StringBuffer sb2 = sb.reverse();
		System.out.println(sb2);
		// 4.StringBuffer转String
		String str = sb.toString();
		System.out.println(str);

	}

}

StringBuilder类

StringBuilder的用法跟StringBuffer类一样,但是StringBuilder在运行效率上要快于StringBuffer。

package com.woniuxy.api.StringBuilder;
public class StringBuilderTest {

	public static void main(String[] args) {
		String str = "hello world,hello china";
		//1.创建StringBuilder对象
		StringBuilder sb = new StringBuilder();
		// 2.向StringBuilder对象中拼接字符串
		sb.append(str);
		System.out.println(str);
		// 3.字符串的反转
		StringBuilder sb2 = sb.reverse();
		System.out.println(sb2);
		// 4.向字符串中插入点
		stringBuilder.insert(4, ".");
		stringBuilder.insert(9, ".");
		// 5.StringBuilder转String
		String newStr = sb2.toString();
		System.out.println(newStr);
	}
}

总结: 如果程序中需要大量的字符串拼接操作,才考虑使用StringBuffer类和StringBuilder类,优先使用StringBuilder类

  • String是不可变长度字符串
  • StringBuffer线程安全的可变长度字符串,StringBuffer用来存储可变的字符串,相当于一个容器。
  • StringBuilder是可变长度字符串。JDK 5.0 版本以后提供了StringBuilder 类,它和StringBuffer
    类等价,不支持线程同步。

查看源码

怎么查看源码?首先要将jdk中的src压缩包解压到当前目录下。
在这里插入图片描述
接着进入eclipse将鼠标放在要查看的类名上,按住ctrl,点击external location,选择src文件。
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值