一、String类
- ==和equals的区别
==:连接的引用类型变量:比较的是地址值是否一样
equals:默认比较的是两个对象的地址值是否相同,只要他重写了Object的equals方法,比较的是对象中的内容是否相同
String类本身重写了equals方法
将常量赋值给String变量以及new String(“常量”)区别
前者是在常量池中去寻找是否存在这个常量,有就返回它常量池中的这个常量地址;否则,就在常量池中开辟空间!
后者:是在堆内存中开辟空间,同时字符串常量标记,需要在常量池中寻找这个常量
举例:
public class StringDemo {
public static void main(String[] args) {
String s1 = "hello" ;
String s2 = "hello" ;
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println("---------------------");
String s3 = "hello" ;
String s4 = new String("hello") ;
System.out.println(s3==s4);
System.out.println(s3.equals(s4));
System.out.println("---------------------");
String s5 = new String("hello") ;
String s6 = new String("hello") ;
System.out.println(s5==s6);
System.out.println(s5.equals(s6));
}
}
- 字符串变量相加:先开空间,不会直接先拼接;
而字符串常量相加,直接先相相加,然后看结果是否在常量池中有,如果存在,直接返回当前这个地址;否则开辟的新的空间
可以使用反编译工具查看当前字节码文件----如何进行优化的!
举例:
public class StringDemo2 {
public static void main(String[] args) {
String s1 = "hello" ;
String s2 = "world" ;
String s3 = "helloworld" ;
System.out.println((s1+s2)==s3);
System.out.println((s1+s2).equals(s3));
System.out.println("-----------------------------");
System.out.println(("hello"+"world")==s3);
System.out.println(("helloworld").equals(s3));
}
}
- 字符串的特点:是常量,一旦被创建,其值不能更改
字符串中相关的成员方法:
获取功能:
public char charAt(int index):获取指定索引处的字符内容
public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串
public int indexOf(int ch):获取指定字符在此字符串中第一次出现是索引值
public int lastIndexOf(int ch):获取指定字符在此字符串中最后一个次出现的索引值
public int length():获取字符串长度
public String[] split(String regex):字符串拆分(分割功能)—>获取字符串数组
举例:
/*面试题:
* 数组中有没有length方法,字符串中有没有length方法,集合中有没有length方法?
* 数组没有,数组是length属性
* 字符串有length方法
* 集合中没有length方法,size()方法获取集合的元素数
*/
public class StringDemo {
public static void main(String[] args) {
//创建一个字符串:推荐直接赋值
String str = "helloworldJavaEE" ;
//public char charAt(int index):获取指定索引处的字符内容
System.out.println("charAt():"+str.charAt(4));
System.out.println("charAt():"+str.charAt(8));
System.out.println("-----------------------------");
// public String concat(String str):将指定的字符串和当前字符串进行拼接,获取一个新的字符串(拼接功能)
//最传统的拼接使用空串+
int a = 100 ;
System.out.println(""+a); //"100"
System.out.println("contact():"+str.concat("高圆圆")); //contact功能底层:就将字符串---字符串数组--进行赋值!
System.out.println("------------------------------");
//public int indexOf(int ch):获取指定字符在此字符串中第一次出现是索引值
System.out.println("indexOf():"+str.indexOf('l'));
// public int lastIndexOf(int ch):获取指定字符在此字符串中最后一个次出现的索引值
System.out.println("lastIndexOf():"+str.lastIndexOf("a"));
System.out.println("-------------------------------");
//public int length():获取字符串长度
System.out.println("length():"+str.length());
System.out.println("--------------------------------");
//public String[] split(String regex):字符串拆分(分割功能)--->获取字符串数组
String s = "php-javaee-python-go-r-c-c#-c++" ;
//使用-拆分
String[] strArray = s.split("-");
for (int i = 0; i <strArray.length ; i++) {
System.out.print(strArray[i]+"\t");
}
}
}
举例:
猜数字游戏:利用Math类的random方法 [0,1.0)
*/
public class GrameStart {
private GrameStart(){}//构造私有化,外界不能new 类名();
public static void start(){
//产生随机数
int num = (int)(Math.random()*100+1) ; //1-100之间的随机数
while(true){
//创建键盘录入对象
Scanner scanner = new Scanner(System.in) ;
//提示并录入数据
System.out.println("请您输入一个数据(1-100):");
int geessNumber = scanner.nextInt() ;
//判断
if(geessNumber> num){
System.out.println("您要猜的数据大了");
}else if(geessNumber<num){
System.out.println("你要猜的数据小了");
}else{
System.out.println("恭喜您,猜中了!");
break ;
}
}
}
}
举例:
需求:
* 模拟用户登录操作,用户输入用户名和密码,给3次机会
* 用户名和密码和输入的匹配,提示"登录成功"
* 否则,登录失败, 换一种提示"您还剩xx"次机会
* 当前机会用完了,"对不起,账户被锁住,请联系管理员"
* 已知:
* 已经存在用户名和密码:
* admin和admin
*/
public class StringDemo2 {
public static void main(String[] args) {
//已知存在的用户名和密码
String name = "admin" ;
String pwd = "admin" ;
//用户输入用户名和密码,给3次机会
Scanner sc = new Scanner(System.in) ;
for(int x = 0 ; x < 3 ; x ++){ //x=0,1,2
System.out.println("请您输入用户名:");
String username = sc.nextLine() ;
System.out.println("请您输入密码:");
String password = sc.nextLine() ;
//判断
if(name.equals(username) && pwd.equals(password)){
System.out.println("恭喜您,登录成功!");
break ;
}else{
//登录失败,换一种提示
if((2-x)==0){
System.out.println("对不起,您的账号被锁定,请速联系管理员!");
}else{
System.out.println("登录失败,您还剩"+(2-x)+"次机会...");
}
}
}
}
}
举例:
需求:
* 模拟用户登录操作,用户输入用户名和密码,给3次机会
* 用户名和密码和输入的匹配,提示"登录成功",开始玩猜数字游戏(单独定义一个类:GrameStart)
* 提供一个静态功能:start():
* 否则,登录失败, 换一种提示"您还剩xx"次机会
* 当前机会用完了,"对不起,账户被锁住,请联系管理员"
* 已知:
* 已经存在用户名和密码:
* admin和admin
*/
public class StringDemo3 {
public static void main(String[] args) {
//已知存在的用户名和密码
String name = "admin" ;
String pwd = "admin" ;
//用户输入用户名和密码,给3次机会
Scanner sc = new Scanner(System.in) ;
for(int x = 0 ; x < 3 ; x ++){ //x=0,1,2
System.out.println("请您输入用户名:");
String username = sc.nextLine() ;
System.out.println("请您输入密码:");
String password = sc.nextLine() ;
//判断
if(name.equals(username) && pwd.equals(password)){
System.out.println("恭喜您,登录成功,你可以玩游戏了");
GrameStart.start();
/* System.out.println("您还玩吗?y/n");
String msg = sc.nextLine();
if(msg.equalsIgnoreCase("y")){
}*/
break ;
}else{
//登录失败,换一种提示
if((2-x)==0){
System.out.println("对不起,您的账号被锁定,请速联系管理员!");
}else{
System.out.println("登录失败,您还剩"+(2-x)+"次机会...");
}
}
}
}
}
- 字符串的判断功能
public boolean equals(Object anObject):
判断当前字符串和此传递进来的字符串进行对比:内容是否相同
public boolean equalsIgnoreCase(String anotherString):不区分大小写,对比的字符串内容
public boolean contains(CharSequence s):判断是否包含指定的字符值
public boolean isEmpty():判断字符串 是否为空内容
boolean startsWith(String prefix) :判断以指定的字符串开头
boolean endsWith(String suffix):判断以指定的字符串结尾
举例:
public class StringDemo {
public static void main(String[] args) {
//创建一个字符串
String s = "helloJavaEE" ;
//public boolean equals(Object anObject): 区分大小写的(如果为字符串类型)
System.out.println("equals():"+s.equals("HELLOJavaEE"));
System.out.println("equals():"+s.equals("helloJavaEE"));
System.out.println("------------------------------------");
// public boolean equalsIgnoreCase(String anotherString):不区分大小写,对比的字符串内容
System.out.println("equalsIgnoreCase():"+s.equalsIgnoreCase("HELLOJavaEE"));
System.out.println("------------------------------------");
// public boolean contains(String s):判断是否包含指定的子字符串
System.out.println("contains():"+s.contains("hello"));
System.out.println("contains():"+s.contains("ak47"));
System.out.println("------------------------------------");
// public boolean isEmpty():判断字符串 是否为空内容
//不是空内容就是flase,为空内容,就是true
/* s = "" ;//空字符串: 空字符序列
System.out.println(s.isEmpty());
s = null ; //空对象
// System.out.println(s.isEmpty());
if(s!=null){
System.out.println(s.isEmpty());
}else{
System.out.println("对不起,没有字符串对象存在");
}*/
System.out.println("--------------------------------");
System.out.println(s.startsWith("hel"));
System.out.println(s.endsWith("ee"));
}
}
- String类的转换功能
public char[] toCharArray():将指定的支持转换成新的字符数组
public byte[] getBytes():编码,将指定的字符串以平台默认编码集进行编码(String—byte[])
public String toLowerCase():将当前字符串转换成小写
public String toUpperCase():将当前字符串转换成大写
static String valueOf(int i/boolean/double/float/Object):将部分的基本数据和Object引用类型转换成String
举例:
public class StringDemo2 {
public static void main(String[] args) {
//创建一个字符串
String s = "JavaEE" ;
//public char[] toCharArray():将指定的支持转换成新的字符数组
char[] chs = s.toCharArray();
for(int x = 0 ; x < chs.length ; x ++){
System.out.print(chs[x]+" ");
}
System.out.println();
System.out.println("---------------------------------");
// public byte[] getBytes():编码,将指定的字符串以平台默认编码集进行编码(String---byte[])
byte[] bytes = s.getBytes();
System.out.println(bytes);
System.out.println(Arrays.toString(bytes)); //英文的字符:寻找对应的ASCII码表的值
System.out.println("[--------------------------------") ;
/* public String toLowerCase():将当前字符串转换成小写
public String toUpperCase():将当前字符串转换成大写*/
System.out.println("toLowerCase():"+s.toLowerCase());
System.out.println("toUpperCase():"+s.toUpperCase());
System.out.println("--------------------------------") ;
// static String valueOf(int i/boolean/double/float/Object):将部分的基本数据和Object引用类型转换成String
//如何将int类型的数据转换String
int a = 50 ;
String str = String.valueOf(a);
System.out.println(str);//"50"
}
}
举例:
String的应用
键盘录入字符串,遍历字符串:就是将字符串中每一个字符一一获取!
*/
public class StringDemo3 {
public static void main(String[] args) {
/* Scanner sc = new Scanner(System.in) ;
System.out.println("请你输入一个字符串:");
String line = sc.nextLine() ;*/
String s = "helloworld" ;
//原始的做法:charAt(索引值)
System.out.println(s.charAt(0));
System.out.println(s.charAt(1));
System.out.println(s.charAt(2));
System.out.println(s.charAt(3));
System.out.println(s.charAt(4));
System.out.println(s.charAt(5));
System.out.println(s.charAt(6));
System.out.println(s.charAt(7));
System.out.println(s.charAt(8));
System.out.println(s.charAt(9));
System.out.println("-------------------------");
//charAt(int ch)+length()
//直接使用String类的获取功能
for(int x = 0 ; x < s.length() ; x ++){
char ch = s.charAt(x) ;
System.out.print(ch+"\t");
}
System.out.println();
System.out.println("-------------------------");
//使用转换功能去完成:
//char[] toCharArray()
char[] charArray = s.toCharArray();
for (int i = 0; i <charArray.length ; i++) {
//每一个字符获取到了
char ch = charArray[i] ;
System.out.print(ch+"\t");
}
System.out.println();
}
}
- String类的截取功能
public String substring(int beginIndex) :从指定的位置开始进行截取,默认截取到末尾为止
public String substring(int beginIndex,int endIndex)
获取一个新的字符串,从指定位置开始,到指定位置结束(包前不包后)(endIndex-1)
举例:
public class StringDemo {
public static void main(String[] args) {
//创建一个字符串对象
String s = "helloworld" ;
String s2 = s.substring(5);
System.out.println(s2);
System.out.println("--------------------------");
String s3 = s.substring(4, 8);
System.out.println(s3);
}
}
-
String类的 其他功能
替换功能
public String replaceAll(String regex,
String replacement):替换所有:参数1为:匹配的正则表达式的子字符串
参数2:要替换的内容
邮箱: 数字或者字母@数字或者字母.com
public String replace(char oldChar,
char newChar):将oldChar使用newChar进行替换public String replace(String target, String replacement) :将指定target子串使用指定 replacement子串进行替换
去重两端空格
public String trim():应用场景:
在IO中传输一些字符串数据的时候,防止前部和尾部存在空格字符,导致io异常,将字符串先去除两端空格
“hello”
" hello
按照字典顺序比较 ,public int compareTo(String anotherString) "
举例:
public class StringDemo2 {
public static void main(String[] args) {
//创建一个字符串
String s = "helloworldjavaee" ;
String s2 = s.replace('l', 'k');
System.out.println(s2);
System.out.println("-------------------------------");
String s3 = s.replace("worldjavaee", "高圆圆");
System.out.println(s3);
// String result = "hello1234world" ;
//定义正则表达式: Pattern:编译器---将用户输入字符串和当前正则表达式的内容进行对比
//String regex = "[a-zA-Z_0-9]" ;
// String regex2 = "[0-9]" ;
System.out.println("----------------------------");
String str = " helloworld " ;
System.out.println("---"+str+"-----");
String str2 = str.trim();
System.out.println("---"+str2+"-----");
System.out.println("----------------------------");
//public int compareTo(String anotherString):按照字典顺序比较
String strs1 = "hello" ;
String strs2 = "abc" ;
System.out.println(strs1.compareTo(strs2));// abcdefgh
}
}
面试题
* String s1 = "hello" ;
* String s2 = "hel"
* s1.compareTo(s2)---->值是多少,为什么
*/
public class StringDemo3 {
public static void main(String[] args) {
String s1 = "hello" ;
String s2 = "hel" ;
String s3 = "xyz" ;
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
// System.out.println('x'+1);//'x' "20
}
}
举例:
键盘录入一个字符串,
举例:
输入 "Helloworld"
输出 "hELLOWORLD"
*/
public class StringTest {
public static void main(String[] args) {
//创建键盘录入对象
Scanner sc = new Scanner(System.in) ;
System.out.println("请输入一个字符串:");
String line = sc.nextLine() ;
//将这个字符串的第一个字符截取出来
String s1 = line.substring(0, 1);
//将1以后的这些字符都截取出来
String s2 = line.substring(1);
//将s1的内容转换成小写
String s3 = s1.toLowerCase();
//将s2的内容转换成大写
String s4 = s2.toUpperCase();
//s3 和s4拼接
String result = s3.concat(s4) ;
System.out.println("result:"+result);
System.out.println("-----------------------------");
//链式编程
String result2 = line.substring(0, 1).toLowerCase().
concat(line.substring(1).toUpperCase());
System.out.println("result2:"+result2);
}
}
举例:
class String{
private final char value[]; //目的就是存储每一个字符值
public int compareTo(String anotherString) { //s2
int len1 = value.length; //---s1---字符数组----5
int len2 = anotherString.value.length; //len2 = s2---字符数组---->3
int lim = Math.min(len1, len2);// lim = Math.min(5,3) ; ---- 3
char v1[] = value; //v1[] = this.value= s1.value ; {'h','e','l','l','o'}
char v2[] = anotherString.value; //v2[] = {'h','e','l'} ; {'a','b','c'} 'x','y','z'
int k = 0; //统计变量
while (k < lim) { //0 < 3 //1 < 3 //2<3 //3<3 不成立
char c1 = v1[k]; //char c1 = v1[0]; --'h' ,'e' ,'l' 'h' 'h'
char c2 = v2[k]; //char c2 = v2[0]; --'h' ,'e' ,'l' 'a' 'x'
if (c1 != c2) {
return c1 - c2; return c1 - c2 = 'h'和'a'ASCII码表 104 -97= 7 ;
return 104 -120 = -16
}
k++; //k=0,-->1-->2 ---3
}
return len1 - len2; //return len1- len2 / 5-3 = 2
}
}
- StringBuffer:线程安全的可变字符序列
一个类似于 String 的字符串缓冲区,但不能修改
什么是线程安全? ----- (多线程中讲!)
线程安全---->同步---->执行效率低!
1)银行的网站
2)医院的网站
线程不安全---->不同步---->执行效率高
论坛网站
单线程程序中(就是程序的执行路径只有一条):它只考虑效率问题,不考虑安全性!
StringBuffer是一个可变的字符序列
StringBuilder:jdk5以后提供的单线程程序中去替代StringBuffer使用的,不同步,执行效率高
与StringBuffer有兼容的API(所有的功能都相同)
StringBuffer的构造方法:
public StringBuffer():空参构造,创建一个空参的字符串缓冲区对象,16个初始容量字符 (默认容量足够大)
public StringBuffer(String str):构造一个字符串缓冲对象,并且为其声明一个字符序列 str
public StringBuffer(int capacity):构造一个字符串缓冲区对象,指定初始容量
获取功能:
int length():获取缓冲区中的字符长度
public int capacity():获取字符串缓冲区中的容量
举例:
public class StringBufferDemo {
public static void main(String[] args) {
// public StringBuffer():空参构造,创建一个空参的字符串缓冲区对象,16个初始容量字符
StringBuffer sb = new StringBuffer() ; //其实他的默认初始化容量---通过它父类的有参构造通过字符数组操作的!
System.out.println(sb);
System.out.println(sb.length());
System.out.println(sb.capacity());
System.out.println("-------------------------");
//public StringBuffer(String str)
// StringBuffer sb2 = new StringBuffer("hello") ;
StringBuffer sb2 = new StringBuffer("abc") ;
//底层---父类的构造方法:使用创建字符串数组,并且同时还需要将字符串追加缓冲区中:
// append():同步方法:(线程安全方法)
System.out.println(sb2); //"hello" StringBuffer
System.out.println(sb2.length());
System.out.println(sb2.capacity());
System.out.println("-------------------------");
//public StringBuffer(int capacity):构造一个字符串缓冲区对象,指定初始容量
StringBuffer sb3 = new StringBuffer(50) ;
System.out.println(sb3);
System.out.println(sb3.length());
System.out.println(sb3.capacity());
}
}
- StringBuilder用来替换StringBuffer
String s1 = “world” ;
“hello”+s1 ;---->使用反编译工具:new StringBuilder().append(“hello”).append(s1) ;
StringBuffer的添加功能:
StringBuffer append(任何数据类型):将指定的内容追加到字符串缓冲区中,返回字符串缓冲区本身
public StringBuffer insert(int offset,String str)
可以将任意类型元素插入到指定位置处
删除功能:
public StringBuffer deleteCharAt(int index):删除指定索引出的字符序列
public StringBuffer delete(int start,int end):
删除从指定位置开始到指定位置结束的字符序列,但是不包含end,包含的end-1的位置
举例:
public class StringBufferDemo2 {
public static void main(String[] args) {
//创建一个空字符序列的字符串缓冲区对象
StringBuffer sb = new StringBuffer() ;
System.out.println(sb);
sb.append(100).append('a') .append(13.56).append(true).append("hello").append("javaee");
System.out.println(sb);
System.out.println("------------------------------------") ;
StringBuffer sb2 = new StringBuffer() ;
sb2.append("hello") ;
sb2.append("world") ;
sb2.append("javae") ;
sb2.insert(5,"高圆圆") ;
System.out.println(sb2);
System.out.println("-------------------------------------");
StringBuffer sb3 = new StringBuffer() ;
sb3.append("hello") ;
sb3.append("world") ;
System.out.println(sb3);
//public StringBuffer deleteCharAt(int index):返回字符串缓冲区本身
//需求:删除第一个l字符
//System.out.println(sb3.deleteCharAt(2));
//需求:删除e这个字符
// System.out.println(sb3.deleteCharAt(1));
System.out.println("------------------------------");
// public StringBuffer delete(int start,int end):返回值都是字符串缓冲区本身
System.out.println(sb3.delete(4,9));
}
}
举例:
StringBuffer的反转功能
* public StringBuffer reverse()
*/
public class StringBufferDemo3 {
public static void main(String[] args) {
//创建键盘录入对象
Scanner sc = new Scanner(System.in) ;
System.out.println("请输入 一个字符串:");
String line = sc.nextLine() ;
//反转--->StringBuffer
StringBuffer buffer = new StringBuffer(line) ;
buffer.reverse() ;
//在将StringBuffer--->String
String s = buffer.toString();
System.out.println(s);
}
}
- 在实际开发中,经常需要将A类型转换成B类型,因为我可能需要使用B类中的功能!
但是,有的时候就将B类型—>A类型,结果最终可能需要A类型!
String<---->StringBuffer:如何转换
StringBuffer的截取功能:
返回被截取的内容!
public String substring(int start):从指定位置开始截取到末尾,返回一个新的字符串
public String substring(int start,int end):从指定为值到end-1位置,返回值一个新的字符串
举例:
public class StringBufferDemo4 {
public static void main(String[] args) {
//String--->StringBuffer
String s = "hello" ;
//定义StringBuffer类型变量
// StringBuffer sb = s ; //类型不匹配
//方式1:StringBuffer的构造方法(String str)
StringBuffer sb = new StringBuffer(s) ;
System.out.println(sb);
System.out.println("-----------------------");
//方式2:使用StringBuffer的空参构造,+append(元素)
StringBuffer sb2 = new StringBuffer() ;
sb2.append(s) ;
System.out.println(sb2);
System.out.println("--------------------------------------");
//StringBuffer--->String
//String的构造方法:public String(StringBuffer buffer)
StringBuffer buffer = new StringBuffer("javaee") ;//类型为StringBuffer类型
String str = new String(buffer) ;
System.out.println(str);//String
System.out.println("----------------------");
//方式2:
//public String toString()
String str2 = buffer.toString();
System.out.println(str2);
System.out.println("----------------------");
StringBuffer sb3 = new StringBuffer() ;
sb3.append("hello") ;
sb3.append("android") ;
sb3.append("Javaee") ;
/* String substring = sb3.substring(5);*/
String substring = sb3.substring(5,10) ;
System.out.println(substring);
}
}
1)给定一个int数组 {24,69,11,22,33} ; 将数组最终拼接成String(使用功能)
2)键盘录入一个字符串类型数据,将字符串数据反转(使用功能),返回String
public class StringBufferTest {
public static void main(String[] args) {
//创建一个数组,静态初始化
int[] arr = {24,69,11,22,33} ;
//调用功能:--->String形式输出出来
String result = array2String(arr);
System.out.println(result);
System.out.println("------------------------------");
Scanner sc = new Scanner(System.in) ;
System.out.println("请您输入一个字符串:");
String line = sc.nextLine() ;
//调用功能
String result2 = reverse(line);
System.out.println(result2);
}
//自定义的功能
public static String reverse(String s){
//分步走:
//创建一个空字符序列的缓冲区对象(字符串)
/* StringBuffer sb = new StringBuffer() ;
sb.append(s) ;
sb.reverse() ;
return sb.toString() ;*/
//一步走
return new StringBuffer(s).reverse().toString() ;
}
public static String array2String(int[] arr){
//创建一个字符串缓冲区对象
StringBuilder sb = new StringBuilder() ; //单线程中替代StringBuffer
//先去追加左中括号
sb.append("[") ;
//遍历数组
for(int x =0 ; x < arr.length ; x ++){
if(x == arr.length-1){
sb.append(arr[x]).append("]") ;
}else{
sb.append(arr[x]).append(", ") ;
}
}
return sb.toString() ;
}
}
面试题:
StringBuffer和String 作为方法的形式参数有什么区别?
方法的形式参数:基本类型
形参的改变不影响实际参数
引用类型
形参的改变直接影响实际参数
String也是引用类型(特殊的引用类型),特点:是一个常量,一旦被创建,其值不能被更改 String s ="abc" ;
String类型作为形式参数,效果和基本类型一致!
从概念上讲:
StringBuffer:可变的字符序列 (线程安全的类)
String::是一个常量,一旦被创建,其值不能被更改
public class StringBufferTest {
public static void main(String[] args) {
String s = "hello" ;
System.out.println(s) ;//hello
myChange(s) ;
System.out.println(s) ;//hello
System.out.println("-------------------------------") ;
StringBuffer sb = new StringBuffer("hello") ;
System.out.println(sb);
myChange(sb);
System.out.println(sb); //"hellojavaee"
}
private static void myChange(StringBuffer sb) {
sb.append("javaee") ;
System.out.println(sb);
}
private static void myChange(String s) {
System.out.println(s);
s+="worldjavaee" ;
System.out.println(s);
}
}
需求:
键盘录入字符串,统计字符串中大写字母字符,数字字符,小写字母的出现个数(不考虑其他字符)
举例:
输入"helloworld123JavaEE"
输出: 大写字母字符: 3个
小写字母字符:13个
数字字符:3个
分析:
0)定义三个变量:
小写字母统计
大写字母统计
数字字符统计
1)键盘录入值
2)将字符串--遍历----toCharArry() --->字符数组
3)获取到每一个字符
当前字符 'a' 'z' ---> 小写字母字符
当前字符 'A' 'Z' --->大写字母字符
当前字符 '0' '9' --->数字字符
学习了Character类的判断
改造这个需求
public static boolean isDigit(char ch):判断这个ch字符是否为数字
public static boolean isLowerCase(char ch):判断这个ch字符是否为小写字母字符
public static boolean isUpperCase(char ch):判断这个ch字符是否为答谢字母字符
public class Test {
public static void main(String[] args) {
//定义三个统计变量
int bigCount = 0 ;
int smallCount = 0 ;
int numberCount = 0 ;
Scanner sc = new Scanner(System.in) ;
//提示
System.out.println("请你输入一个字符串(包含大小写以及数字): ");
String line =sc.nextLine() ;
//转换
char[] charArray = line.toCharArray();
for (int i = 0; i <charArray.length ; i++) {
//获取到每一个字符
char ch = charArray[i] ;
//判断
if(ch>= 'a' && ch <='z'){
smallCount ++ ;
}else if(ch >= 'A' && ch <= 'Z'){
bigCount ++;
}else if(ch >= '0' && ch<='9'){
numberCount ++ ;
}else{
System.out.println("对不起,不提供这个字符统计");
}
}
System.out.println("大写字母字符有:"+bigCount+"个");
System.out.println("小写字母字符有:"+smallCount+"个");
System.out.println("数字字符:"+numberCount+"个");
}
}
二、Character类
-
Java中基本数据类型:四类八种,都会对应一个引用类型(JDK5以后新特性:自动拆装箱)
基本类型 对应的引用类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean基本类型 内存中—引用类型:好处就是可以String类型之间进行转换!
Character:包含了一个char的值
构造方法
public Character(char value) :创建Character类对象,参数为char类
提供 了一些判断功能
public static boolean isDigit(char ch):判断这个ch字符是否为数字
public static boolean isLowerCase(char ch):判断这个ch字符是否为小写字母字符
public static boolean isUpperCase(char ch):判断这个ch字符是否为答谢字母字符
举例:
public class CharacterDemo {
public static void main(String[] args) {
//创建Character类对象
// Character character = new Character('a') ;
Character character = new Character((char)97) ;
System.out.println(character);
}
}
举例:
提供 了一些判断功能;静态
* public static boolean isDigit(char ch):判断这个ch字符是否为数字
* public static boolean isLowerCase(char ch):判断这个ch字符是否为小写字母字符
* public static boolean isUpperCase(char ch):判断这个ch字符是否为答谢字母字符
*/
public class CharacterDemo2 {
public static void main(String[] args) {
System.out.println(Character.isDigit('a'));
System.out.println(Character.isDigit('A'));
System.out.println(Character.isDigit('0'));
System.out.println("----------------------------");
System.out.println(Character.isUpperCase('a'));
System.out.println(Character.isUpperCase('A'));
System.out.println(Character.isUpperCase('0'));
System.out.println("----------------------------");
System.out.println(Character.isLowerCase('a'));
System.out.println(Character.isLowerCase('A'));
System.out.println(Character.isLowerCase('0'));
}
}
三、Integer类
举例:
需求:
求出,十进制100,对应二进制,八进制,十六进制
Integer类的静态的功能:
public static String toBinaryString(int i):将十进制转换成二进制(以字符串形式体现)
public static String toOctalString(int i):转换八进制(返回String)
public static String toHexString(int i):转换成十六进制(返回String)
求出 int类型的取值范围
Integer类:
成员变量:
public static final int MIN_VALUE:包装了int类型的最小值
public static final int MAX_VALUE:包装了int类型的最大值
引入Integer类:
Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。
public class IntegerDemo {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(100));
System.out.println(Integer.toOctalString(100));
System.out.println(Integer.toHexString(100));
System.out.println("----------------------------");
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
}
}
构造方法
public Integer(int value):将int类型的数据包装为Integer类型
public Integer(String s) throws NumberFormatException :将字符串值包装为Integer类型
此s参数必须为数字字符串,否则程序出现 NumberFormatException(数字格式化异常)
举例:
public class IntegerDemo2 {
public static void main(String[] args) {
//创建Integer类对象
int number = 100 ; //基本数据类型
Integer integer = new Integer(number) ;//引用类型
System.out.println(integer);
System.out.println("--------------------------------");
// String s = "hello" ;//当s被解析时,如果不是int值的话,就会出现数字格式化异常
String s = "20" ;
Integer integer2 = new Integer(s) ;
System.out.println(integer2) ;
}
}
Jdk5以后新特性:
静态导入,自动拆装箱,增强for循环,可变参数,枚举…
自动拆装箱:
装箱: 基本数据类型 会自动的包装为对应的引用类型
拆箱: 引用类型会自动的转换为基本数据类型
int--->Integer
Integer--->int
举例:
public class IntegerDemo3 {
public static void main(String[] args) {
int num = 200 ;
//创建Integer类对象
Integer i = new Integer(num) ;
i += 100 ;
System.out.println(i);
/*
* 反翻译工具将xx.class文件
*
* package com.qf.integer_01;
import java.io.PrintStream;
public class IntegerDemo3
{
public IntegerDemo3()
{
}
public static void main(String args[])
{
int num = 200; //声明这个变量int
Integer i = new Integer(num); //创建一个Integer类对象:将int---->装箱为Integer了
//public int intValue()
//public static Integer valueOf(int i)
i = Integer.valueOf(i.intValue() + 100); // i = Ineger.valueOf(先将Integer拆箱为int) ---->在装箱为Integer类型
System.out.println(i);
}
}
}
}
举例:
看程序,写结果
Integer类中存在一个:内部缓存区 IntegerCache(Integer的成员内部类): 范围:-128~127
直接赋值:----考虑到值的是否在范围内
Integer xx = 值 ;---->底层执行的valueOf(int )
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high){
return IntegerCache.cache[i + (-IntegerCache.low)]; //127 + 128
}else{
return new Integer(i); //new Integer(128) ;
}
}
如果不在内部缓存区 的范围内(-128~`27):会重新开辟空间new Integer
如果在内部缓存区中:直接从缓冲区(Integer的静态的成员内部类) :直接从缓存区中取值!
public class IntegerTest {
public static void main(String[] args) {
Integer i1 = 127 ;
// Integer i2 = new Integer(127) ;
Integer i2 = 126 ;
System.out.println(i1 == i2);
System.out.println(i1.equals(i2));
System.out.println("-------------------------");
Integer i3 = new Integer(127) ;
Integer i4 = new Integer(127) ;
System.out.println(i3==i4);
System.out.println(i3.equals(i4));
System.out.println("--------------------------");
Integer i5 = 128 ;
Integer i6 = 128 ;
System.out.println(i5 == i6);//false
System.out.println(i5.equals(i6));
System.out.println("--------------------------");
Integer i7 = 129 ;
Integer i8 = new Integer(129) ;
System.out.println(i7==i8);
System.out.println(i7.equals(i8));
//Integer ii = new Integer(200);
// System.out.println(ii);
}
}