接口,字符串
接口
接口:关键字interface
接口中的所有方法都是抽象方法,不用特意声明,默认都是抽象。
接口的特性:
- 接口不可以被实例化。
- 实现类必须实现接口的所有方法
- 实现类可以实现多个接口
- 接口中的变量都是静态常量
注:
实现类:类使用了接口就是这个接口的实现类。
如何使用接口
用多态方式使用接口
第一步:创建接口.
如:
// USB接口
public interface UsbInterface {
public void server();
}
第二步:创建实现类,实现接口所有方法;
//usb接口的实现类:u盘
public class UDisk implements UsbInterface{
//方法重写
public void server(){
System.out.println("正在传输数据");
}
}
第三步:使用接口;使用实现类实例化接口
//测试类
public class USBTest {
public static void main(String[] args) {
// 创建usb接口对象(通过实现类UDisk创建)
UsbInterface udisk=new UDisk();
udisk.server();
}
}
结果:
字符串
字符串使用:String类的使用
字符串常用提取方法:
//字符串提取方法
public class Dome04 {
public static void main(String[] args) {
String s="我家在麒麟镇麒麟村、白马组";
//查找你要查的字的索引位置(从前往后查)
int str1=s.indexOf("麒");
System.out.println(str1);
//查找你要查的字的索引位置(从后往前查)
int lat=s.lastIndexOf("麟");
System.out.println(lat);
//提取子串1:从提取的位置到结束位置,都输出为一串子串
String sub=s.substring(3);
System.out.println(sub);
//提取子串2:提取选位置,提出的一串子串
String sub2=s.substring(0, 9);
System.out.println(sub2);
//去前后空格
String s2=" 麒麟镇麒麟村 ";
String string=s2.trim();
System.out.println(string);
}
}
结果为:
使用String对象存储字符串
第一种方法:String s = “Hello World”;
第二种方法:
String s = new String();
s = new String(“Hello World”);
String类位于java.lang包中,具有丰富的方法
计算字符串的长度、比较字符串、连接字符串、提取字符串
String类提供了length()方法,确定字符串的长度
数组长度:“数组名.length” 是属性
字符串长度:“变量名.length() ”是方法
“==”和equals()有什么区别呢?
- equals():检查组成字符串内容的字符是否完全一致
- ==:判断两个字符串在内存中的首地址,即判断是否是同一个字符串对象
符串连接:
方法一:使用“+”
方法二:使用String类的concat()方法
例如:下面的 str1.concat(str2)
// “=="字符串比较
public static void main(String[] args) {
//直接指向同样内容时,两者的地址是一样的,指向的都是相同的地址返回true
String str1="hello";
String str2="hello";
System.out.println(str1==str2);
//用new就会在堆中重新开辟一块空间
String str3 = new String();
String str4 =new String();
System.out.println(str3==str4);
//两者比较时比得是地址,而地址不相同所以返回false
//连接字符串
System.out.println(str1.concat(str2));
}
运行结果:
大小写
使用equalslgnoreCase()方法:忽略大小写比较
返回boolean
使用toLowerCase()方法:将所有这都降为小写
返回小写
使用toUpperCase()方法:将所有都升为大写
返回大写
例如:
//大小写转换
public class Dome03 {
public static void main(String[] args) {
//忽略大小写比较
String str1="TOM";
String str2="tom";
System.out.println(str2.equalsIgnoreCase(str2));
//转化为大写
System.out.println(str2.toUpperCase());
//转化为小写
System.out.println(str1.toLowerCase());
}
}
运行结果:
endsWith()判断是某种后缀(返回boolean类型)
public static void main(String[] args) {
//endsWith()判断以某种后缀结束
String s="adc.java";
if (s.endsWith("java")) {
System.out.println("这是个java文件");
}else{
System.out.println("其他文件");
}
}
运行结果为:
String类提供了split()方法
split()方法将一个字符串分割为子字符串,结果作为字符串数组返回
//字符串拆分
public static void main(String[] args) {
String string="床前明月光 疑是地上霜 举头望明月 低头思故乡";
//建一个字符串数组存储分割后的字符串
String[] str=new String[10];
//分割方法是以字符空格为标识,遇到空格字符就分割
str=string.split(" ");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
运行结果: