B:Scanner的构造方法原理
Scanner(InputStream source)System类下有一个静态的字段: public static final InputStream in; 标准的输入流,对应着键盘录入。C:一般方法
hasNextXxx() 判断是否还有下一个输入项,其中Xxx可以是Int,Double等。如果需要判断是否包含下一个字符串,则可以省略XxxnextXxx() 获取下一个输入项。Xxx的含义和上个方法中的Xxx相同,默认情况下,Scanner使用空格,回车等作为分隔符package com.heima.scanner;import java.util.Scanner;public class Demo1_Scanner { /** * @param args */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); //键盘录入 //int i = sc.nextInt(); //键盘录入整数存储在i中 //System.out.PRintln(i); if(sc.hasNextInt()) { //判断键盘录入的是否是int类型的数据 int i = sc.nextInt(); //键盘录入的数据存储在i中 System.out.println(i); }else { System.out.println("输入的类型错误"); } }}A:String类的概述
通过JDK提供的API,查看String类的说明
可以看到这样的两句话。
a:字符串字面值”abc”也可以看成是一个字符串对象。b:字符串是常量,一旦被赋值,就不能被改变。package com.heima.string;public class Demo1_String { /** * a:字符串字面值"abc"也可以看成是一个字符串对象。 * b:字符串是常量,一旦被赋值,就不能被改变。 */ public static void main(String[] args) { //Person p = new Person(); String str = "abc"; //"abc"可以看成一个字符串对象 str = "def"; //当把"def"赋值给str,原来的"abc"就变成了垃圾 System.out.println(str); //String类重写了toString方法返回的是该对象本身 }}abc cde abcde bcd heima
2.下面这句话在内存中创建了几个对象? String s1 = new String(“abc”);
3.判断定义为String类型的s1和s2是否相等 String s1 = new String(“abc”); String s2 = “abc”;System.out.println(s1 == s2); System.out.println(s1.equals(s2));4.判断定义为String类型的s1和s2是否相等 String s1 = “a” + “b” + “c”;String s2 = “abc”;System.out.println(s1 == s2); System.out.println(s1.equals(s2));5.判断定义为String类型的s1和s2是否相等 String s1 = “ab”;String s2 = “abc”;String s3 = s1 + “c”;System.out.println(s3 == s2);System.out.println(s3.equals(s2));
package com.heima.string;public class Demo3_String { public static void main(String[] args) { //demo1(); //demo2(); //demo3(); //demo4(); String s1 = "ab"; String s2 = "abc"; String s3 = s1 + "c"; System.out.println(s3 == s2); System.out.println(s3.equals(s2)); //true } private static void demo4() { //byte b = 3 + 4; //在编译时就变成7,把7赋值给b,常量优化机制 String s1 = "a" + "b" + "c"; String s2 = "abc"; System.out.println(s1 == s2); //true,java中有常量优化机制 System.out.println(s1.equals(s2)); //true } private static void demo3() { String s1 = new String("abc"); //记录的是堆内存对象的地址值 String s2 = "abc"; //记录的是常量池中的地址值 System.out.println(s1 == s2); //false System.out.println(s1.equals(s2)); //true } private static void demo2() { //创建几个对象 //创建两个对象,一个在常量池中,一个在堆内存中 String s1 = new String("abc"); System.out.println(s1); } private static void demo1() { //常量池中没有这个字符串对象,就创建一个,如果有直接用即可 String s1 = "abc"; String s2 = "abc"; System.out.println(s1 == s2); //true System.out.println(s1.equals(s2)); //true }}A:String的转换功能:
byte[] getBytes():把字符串转换为字节数组。char[] toCharArray():把字符串转换为字符数组。static String valueOf(char[] chs):把字符数组转成字符串。static String valueOf(int i):把int类型的数据转成字符串。
注意:String类的valueOf方法可以把任意类型的数据转成字符串。String toLowerCase():把字符串转成小写。(了解)
String toUpperCase():把字符串转成大写。String concat(String str):把字符串拼接。-3 40657 39532 1125 32 0

新闻热点
疑难解答