Java常用类的使用

Object类

toString() 方法

toString() 方法用于返回以一个字符串表示的 Number 对象值。
如果方法使用了原生的数据类型作为参数,返回原生数据类型的 String 对象值。
如果方法有两个参数, 返回用第二个参数指定基数表示的第一个参数的字符串表示形式。

语法
以 String 类为例,该方法有以下几种语法格式:

String toString()
static String toString(int i)

参数
i 表示要转换的整数。

返回值

toString(): 返回表示 Integer 值的 String 对象。
toString(int i): 返回表示指定 int 的String 对象。

实例

public class Test{
    public static void main(String args[]){
        Integer x = 5;
        System.out.println(x.toString());  
        System.out.println(Integer.toString(12)); 
    }
}

编译以上程序,输出结果为:

5
12

equals() 方法

equals() 方法用于将字符串与指定的对象比较。

返回值
如果给定对象与字符串相等,则返回 true;否则返回 false。

public class Test {
    public static void main(String args[]) {
        String a = new String("studyequals");
        String b = a;
        String c = new String("equals");
        
        System.out.println("返回值 = " + a.equals( b ) );
        System.out.println("返回值 = " + a.equals( c ) );
    }
}

结果

true
false

hashCode() 方法

hashCode() 方法用于返回字符串的哈希码。

public class Test {
        public static void main(String args[]) {
                String Str = new String("hashCode");
                System.out.println( Str.hashCode());
        }
}

结果

147696667

getClass方法

可以获取一个类的定义信息,然使用反射去访问其全部信息(包括函数和字段)。
还可以查找该类的ClassLoader,以便检查类文件所在位置等。

String类

public class StringDemo {
    public static void main(String[] args) {
		String s = "ababcdebcda";
		System.out.println("字符串s的长度: "+s.length());
		System.out.println("字符串s的第一个字符是: "+s.charAt(0));
		System.out.println("c在字符串s第一次出现的位置是: "+s.indexOf("c"));
		System.out.println("c在字符串s最后一次出现的位置是: "+s.lastIndexOf("c"));
		System.out.println("ba在字符串s第一次出现的位置是: "+s.indexOf("ba"));
		System.out.println("ba在字符串s最后一次出现的位置是: "+s.lastIndexOf("ba"));
		System.out.println("把s中所有的a替换成ha: "+s.replace("a", "ha"));
		System.out.println("判断字符串s是否以ab开头: "+s.startsWith("ab"));
		System.out.println("判断字符串s是否以da结尾: "+s.endsWith("da"));
		System.out.println("判断字符串s是否为空: "+s.isEmpty() );
		System.out.println("截取字符串s的前3个字符: "+s.substring(0,3));
		System.out.println("从字符串s的第3个截取到末尾: "+s.substring(2));
	}
}

输出结果:

字符串s的长度: 11
字符串s的第一个字符是: a
c在字符串s第一次出现的位置是: 4
c在字符串s最后一次出现的位置是: 8
ba在字符串s第一次出现的位置是: 1
ba在字符串s最后一次出现的位置是: 1
把s中所有的a替换成ha: habhabcdebcdha
判断字符串s是否以ab开头: true
判断字符串s是否以da结尾: true
判断字符串s是否为空: false
截取字符串s的第3个截取到末尾: aba
从字符串s的第3个截取到末尾: abcdebcda

猜你喜欢

转载自blog.csdn.net/qq_46150940/article/details/106932248