银川做网站的有哪些,wordpress 歌,灰色行业做网站,卖主机 服务器的网站一.掌握创建String字符串对象的两种方式
方式一(常用)
在程序中直接写字符串变量,就是一个String对象
String s1 abc;
System.out.println(s1);注意 : 打印字符串类型的变量,是不会看到字符串对象空间地址值的,底层是有优化的,直接看到字符串对象中存储的内容…一.掌握创建String字符串对象的两种方式
方式一(常用)
在程序中直接写字符串变量,就是一个String对象
String s1 abc;
System.out.println(s1);注意 : 打印字符串类型的变量,是不会看到字符串对象空间地址值的,底层是有优化的,直接看到字符串对象中存储的内容,底层打印对象十六进制地址值的代码
方法二
使用new关键字创造String对象,附带调用String的构造器
第一种,String(): 创建String对象, 内容是
String s2 new String();
System.out.println(s2);第二种,String(String str)利用提供的String字符串内容创建String对象
String s3 new String(黑马);
System.out.println(s3);第三种,String(char[] chs)根据字符数组中的字符拼接一个字符串得到字符串对象
char[] chs {传, 播};
String s4 new String(chs);
System.out.println(s4);第四种,String(byte[] bys)根据byte数组中的数字在编码表中的字符拼接成字符串得到字符串对象
byte[] bys {97, 98, 99};
String s5 new String(bys);
System.out.println(s5);二.掌握String提供的常见方法的使用
2.1 获取字符串长度 length()
String str 黑马;
System.out.println(str.length());// 22.2 根据索引获取字符串中的字符字符串索引从0开始 charAt(int index )
char c str.charAt(0);
System.out.println(c);// 黑注 : 若获取一个不存在的索引位置的字符
char c str.charAt(2);
System.out.println(c);//报错StringIndexOutOfBoundsException字符串索引越界异常2.3 将字符串转换成字符数组toCharArray()
char[] chs str.toCharArry();
for (int i 0; i chs.length; i){
sout(chs[i] \t);
}
sout();//黑
//马2.4 比较调用方法的字符串和传入方法的字符串的内容是否相同区分大小写equals(String str)
boolean r1 abc.equals(ABC);
sout(r1);//2.5 比较两个字符串内容是否相同不区分大小写equalsIgnoreCase(String str)
boolean r2 abc.equalsIgnoreCase(ABc);
System.out.println(r2);//true2.6 判断调用方法的字符串是否包含指定的字符串contains(字符串
boolean r3 黑马程序员.contains(黑马);
System.out.println(r3);三. 了解String使用时的注意事项
//1.String字符串对象是不可变的字符串对象String name 黑马;System.out.println(System.identityHashCode(name));name 程序员;System.out.println(System.identityHashCode(name));name 播妞;System.out.println(System.identityHashCode(name));//这里的不可变指的是对象空间中的字符串内容不可变但不代表字符串对象不可变System.out.println(name);String s1 abc;String s2 abc;System.out.println(s1 s2); // truechar[] chs {a, b, c};String s3 new String(chs);String s4 new String(chs);System.out.println(s3 s4); // falseString s5 abc;String s6 ab;String s7 s6 c;System.out.println(s5 s7); // falseString s8 a b c; // Java有编译优化机制如果一个运算中只有字面量没有变量编译后会直接得到结果System.out.println(s5 s8); // trueRandom
import java.util.Random;
public static void main(String[] args) {String code getCode(5);System.out.println(验证码 code);}/*** 1.定义方法* 明确参数int n验证码的位数* 明确返回值String获取的验证码*/public static String getCode(int n) {//2.定义两个字符串变量分别代表验证码和验证码要用到的字符String code ;String data 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;//3.随机功能使用RandomRandom r new Random();//4.循环n次每次生成一个随机字符拼接到code字符串上for (int i 0; i n; i) {//获取一个随机整数代表字符串的索引范围是0到字符串的长度减1int index r.nextInt(data.length());//根据索引从data字符串中获取字符拼接到code上char c data.charAt(index);code c;}//5.返回验证码codereturn code;}