/*Scanner:用于获取键盘录入的数据(基本数据类型,字符串数据) public String nextLine();获取键盘录入的字符串数据 */ 代码块
public class ScannerDemo{ public static void main(String[] args){ //创建键盘录入对象 Scanner sc = new Scanner(System.in); //接收数据 System.out.println("请输入一个字符串数据:"); String s = sc.nextLine(); //输出结果 System.out.println("s:"+s) } }/* String:字符串类 由多个字符组成的遗传数据 字符串其本质是一个字符数组 构造方法:
String(String original):把字符串数组封装成字符串对象 String(char[] value):把字符数组的数据封装成字符串对象 String(char[] value ,int index , int count):把字符数组中的一部分数组封装成字符串对象注意:字符串是一种比较特殊的引用数据类型,直接输出字符串对象输出的是该对象的数据 */ 代码块
public class StringDemo{ public static void main(String[] args ){ //方式一 //String(String original):把字符串数组封装成字符串对象 String s1 = new String("Hello"); System.out.println("s1"+s1); System.out.println("-------") //方式二 //String(char[] value):把字符数组的数据封装成字符串对象 char[] chs = {'h','e','l','l','o'}; String s2 = new String(chs); System.out.println("s2"+s2); System.out.println("-------"); //方式三 //tring(char[] value ,int index , int count):把字符数组中的一部分数组封装成字符串对象 //String s3 = new String(chs,0,chs.length); String s3 = new String(chs,1,3); System.out.println("s3"+s3); System.out.println("-------"); //方式四 String s4 = "hello"; System.out.println("s4"+s4); } }输出结果:
s1:hello ------ s2:hello ------- s3:ell ------- s4:hello/* 通过构造方法创建字符串对象和直接赋值方法创建的字符串对象的区别 直接构造方法创建字符串对象是在堆内存 直接赋值方式创建对象实在方法区的常量池
==: 基本数据类型:比较的是基本数据类型的值是否相同 引用数据类型:比较的是引用数据类型的地址值是否相同 */ 代码块
public class StringDemp{ public static void main(String[] args){ String s1 = new String("hello"); Srint s2 = "hello"; System.out.prinln("s1:"+s1); System.out.prinln("s2:"+s2); System.out.prinln("s1==s2:"+(s1==s2));//false String s3 = "hello"; System.out.prinln("s1==s3:"+(s1==s3));//false System.out.prinln("s2==s3:"+(s2==s3));//true } }注意:字符串的内容是存储在方法区的常量池里,为了方便字符串的重复使用
