目录
六、String类、StringBuffer类和StringBuilder类的区别?
JavaAPI
Java API(Java Application Programming Interface):即Java应用程序编程接口,它是运行库的集合,预先定义了一些接口和类,程序员可以直接使用已经打包的接口和类做具体的应用。除了“应用程序编程接口”的意思外,API也称为帮助文档。Java语言的强大之处在于它提供了多种多样的类库,从而大大提高了程序编程的效率和质量。
一、枚举类型
枚举:指由一组固定的常量组成的类型
语法:
[Modifier] enum enumName{
enumContantName1
[,enumConstantName2...[;]]
//[field,method]
}
实例:
//定义一个枚举类
public enum Week {
MON,TUE,WED,THU,FRI,SAT,SUN
}
实现类:
public class WeekDemo {
public void doWhat(Week day){
switch (day){
case MON:
case TUE:
case WED:
case THU:
case FRI:
System.out.println("工作日,努力写代码");
break;
case SAT:
System.out.println("星期六,休息!看电影");
break;
case SUN:
System.out.println("星期日,休息!打篮球");
break;
default:
System.out.println("地球上一个星期就7天");
}
}
public static void main(String[] args) {
WeekDemo weekDemo = new WeekDemo();
weekDemo.doWhat(Week.SAT);
}
}
枚举类型优点:
1、枚举可以使代码易于维护,保证类型安全。
2、枚举易于输入,使用枚举赋值,只需要输入枚举名,然后输入点操作符就能将所有的值显示出来。
3、枚举使代码更清晰,允许使用描述性的名称表示数据,使用时直观方便。
二、包装类
Java语言是面向对象的,但是Java中的基本数据类型却不是面向对象的,这在实际开发中存在很多的不便。为了解决这个不足,在设计类时为每个基本数据类型设计了一个对应的类,称为包装类。每个基本类型在java.lang包中都有一个相应的包装类。
1、包装类有何作用
1、提供了一系列实用的属性和方法,方便对象的操作。
2、集合不允许存放基本数据类型数据,存放数字时,要用包装类型。
2、包装类和基本数据类型的对应关系
基本数据类型 |
包装类 |
byte |
Byte |
boolean |
Boolean |
short |
Short |
char |
Character |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
3、包装类的构造方法
所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例。
包装类的构造方法有两种形式
方式1:public Type(type value)
Type表示包装类,参数type为基本数据类型。
例如:
Integer i=new Integer(520);
方式2:public Type(String value)
除Character类外其他包装类可将一个字符串作为参数构造它们的实例
Type表示包装类,参数type为基本数据类型。
例如:
Integer i=new Integer(“520”);
Boolean类构造方法参数为String类型时,若该字符串内容为true(不考虑大小写),则该Boolean对象表示true,否则表示false
例如:
Boolean boo = new Boolean(null);
System.out.println(boo);-------结果为false
Boolean boo = new Boolean(true);
System.out.println(boo);--------结果为true
Boolean boo = new Boolean("asd");
System.out.println(boo);--------结果为false
当包装类构造方法参数为String 类型时,字符串不能为null,且该字符串必须可解析为相应的基本数据类型的数据,否则编译通过,运行时NumberFormatException异常
例如:下面两种情况都会报错
Integer integer = new Integer(null);
System.out.println(integer);
Integer integer1 = new Integer("asd");
System.out.println(integer1);
4、包装类的常用方法
1、语法:public static Type valueOf(type value)
Integer i=Integer.valueOf(520);
除Character类外,其他包装类都有如下方法
2、语法:public static Type valueOf(String value)
Integer i=Integer.valueOf(“520”);
3、XXXValue()方法:包装类转换成基本类型
Integer num=new Integer(20);
int age=num.intValue();
4、所有包装类都有如下方法(Character类除外)public static 基本数据类型 parseXXX(String value)
byte b=Byte.parseByte("125");
short s=Short.parseShort("3256");
int num=Integer.parseInt("36");
long l=Long.parseLong("123456789");
float f=Float.parseFloat("3.14");
final double PI=Double.parseDouble("3.14159");
boolean bool=Boolean.parseBoolean("false");
parseXXX()方法的作用:把字符串转换为相应的基本数据类型数据
5、toString()方法:以字符串形式返回包装对象表示的基本类型数据
byte bt=12;
String b=Byte.toString(bt);
short sh=25;
String s=Short.toString(sh);
String num=Integer.toString(520);
String l=Long.toString(123456789l);
String f=Float.toString(3.14f);
String PI=Double.toString(3.1415926d);
String bool=Boolean.toString(false);
三、装箱和拆箱
装箱:基本类型转换为包装类的对象
拆箱:包装类对象转换为基本类型
Integer intObj=5; //装箱
int intValue=intObj; //拆箱
包装类的特点
1、所有包装类都是final类型,不能创建它们的子类
2、Java 5.0版本以后,程序员不需要编码实现基本数据类型和包装类之间的转换,编译器会自动完成。
3、JDK1.5后,允许基本数据类型和包装类型进行混合数学运算。
4、包装类并不是用来取代基本数据类型的
5、在基本数据类型需要用对象表示时使用
Math类
Math类提供了常用的数学运算方法和两个静态常量E(自然对数的底数)和PI
方法名 | 备注 |
abs(int a) |
返回 int 值的绝对值 |
ceil(double a) |
返回最小的(最接近负无穷大)double 值,该值大于等于参数,并等于某个整数。 |
floor(double a) |
返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数。 |
max(int a, int b) |
返回两个 int 值中较大的一个。 |
random() |
返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。 |
round(double a) |
返回最接近参数的 long。 |
min(int a, int b) |
返回两个 int 值中较小的一个。 |
sqrt(double a) |
返回正确舍入的 double 值的正平方根。 |
例如:
System.out.println(Math.abs(-8));
System.out.println(Math.ceil(-23));
System.out.println(Math.floor(23));
//比较大小
System.out.println(Math.max(23,34));
System.out.println(Math.min(23,34));
//得到一个大于0.0,小于1.的数
System.out.println(Math.random());
System.out.println(Math.round(8));
//取平方根
System.out.println(Math.sqrt(4));
//相加
System.out.println(Math.addExact(12,23));
Random类
Random类:用于生成伪随机数流
构造方法 | 备注 |
Random( ) |
创建一个新的随机数生成器。 |
Random(long seed) |
使用单个 long 种子创建一个新的随机数生成器。 |
方法名 | 备注 |
next(int bits) |
生成下一个伪随机数。 |
nextInt( ) |
返回下一个伪随机数,它是此随机数生成器的序列中均匀分布的 int 值。 |
nextInt(int n) |
返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括)和指定值(不包括)之间均匀分布的 int 值 |
实例:
定义方法public static int getRandom(){ //方法体},在方法体中产生[155,658]之间的随机数,并返回该随机数
public static int getRandom(){
Random random = new Random();
int num = random.nextInt(504) + 155;
return num;
}
//打印10个随机数
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.print(NUmberTools.getRandom() + "\t");
}
}
四、String类
在Java中使用String类的对象存储字符串
常用方法:
方法名 | 作用 |
char charAt(int index) |
返回指定索引处的 char 值。 |
String concat(String str) |
将指定字符串连接到此字符串的结尾。 |
boolean contains(CharSequence s) |
当此字符串包含指定的 char 值序列时,返回 true。 |
boolean equals(Object anObject) |
将此字符串与指定的对象比较。 |
boolean equalsIgnoreCase(StringanotherString) |
将此 String 与另一个 String 比较,不考虑大小写。 |
byte[] getBytes() |
使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 |
int indexOf(String str) |
返回指定子字符串在此字符串中第一次出现处的索引。 |
int lastIndexOf(String str) |
返回指定子字符串在此字符串中最右边出现处的索引 |
int length( ) |
返回此字符串的长度。 |
boolean matches(String regex) |
告知此字符串是否匹配给定的正则表达式。 |
char charAt(int index)
String str = "HelasdadloWorld";
System.out.println("index=8时,索引位置的字符是:" + str.charAt(8));
String concat(String str)
System.out.println("在末尾拼接Hello:" + str.concat("Hello"));
boolean contains(CharSequence s)
String str = "helloWorld";
boolean boo = str.contains("e");
System.out.println(boo);
boolean equals(Object anObject)
String str = "HelasdadloWorld";
String upStr = "HELLOWORLD";
System.out.println(str.equals(upStr));
boolean equalsIgnoreCase(StringanotherString)
System.out.println(str.equalsIgnoreCase(upStr));
byte[] getBytes()
byte[] bytes = str.getBytes();
int indexOf(String str)
String str = "HelasdadloWorld";
int index = str.indexOf("l");
System.out.println("l第一次出现的位置是:" + index);
int lastIndexOf(String str)
String str = "HelasdadloWorld";
int lastIndex = str.lastIndexOf("l");
System.out.println("l最后一次出现的位置是:" + lastIndex);
int length( )
String str = "HelasdadloWorld";
System.out.println("字符串的长度是:" + str.length());
boolean matches(String regex)
String numAge = "15A";
boolean isNumber = numAge.matches("[0-9]+");
System.out.println(isNumber);
常用方法:
方法名 | 作用 |
String replace(CharSequence target, CharSequence replacement) |
使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。 |
String[] split(String regex) |
根据给定正则表达式的匹配拆分此字符串。 |
String substring(int beginIndex) |
返回一个新的字符串,它是此字符串的一个子字符串 |
String substring(int beginIndex, int endIndex) |
返回一个新的字符串,它是此字符串的一个子字符串。最后一个字符不包含 |
char[] toCharArray() |
将此字符串转换为一个新的字符数组。 |
String toLowerCase() |
将此 String 中的所有字符都转换为小写。 |
String toUpperCase() |
将此 String 中的所有字符都转换为大写。 |
String trim() |
返回字符串的副本,忽略前导空白和尾部空白 |
static String valueOf(Object obj) |
返回 Object 参数的字符串表示形式。 |
String replace(CharSequence target, CharSequence replacement)
String info = "大家好,我叫{name},今年{age}岁了,性别{sex}";
System.out.println("替换前:" + info);
info = info.replace("{name}","张三");
info = info.replace("{age}","19");
info = info.replace("{sex}","男");
System.out.println("替换后:" + info);
String[] split(String regex)
String word = "戏一折,水袖起落,唱悲欢唱离合,无关我,扇开合,锣鼓响又默";
String[] words = word.split("默");
System.out.println(words.length-1);
for (String s : words) {
System.out.println(s);
}
String substring(int beginIndex)
String str = "helloWorld";
String st = str.substring(3);
System.out.println(st);
String substring(int beginIndex, int endIndex)
String subStrTest = "HelasdadloWorld";
System.out.println("截取5-8的字符串:" + subStrTest.substring(5,8));
System.out.println(subStrTest.substring(5,15));
char[] toCharArray()
char[] charArray = str.toCharArray();
for (char c : charArray) {
System.out.print(c + "\t");
}
String toLowerCase()
System.out.println("将str变量全部转大写:" + str.toLowerCase());
String toUpperCase()
System.out.println("将str变量全部转大写:" + str.toUpperCase());
String trim()
String trimStr = " asdasd asd ash ";
System.out.println("trimStr的长度是:" + trimStr.length());
System.out.println(trimStr.trim());
static String valueOf(Object obj)
int num = 15;
String numStr = String.valueOf(num);
System.out.println(numStr instanceof String);
int length( ):返回字符串中的字符数。
String trim() :返回字符串的副本,忽略前导空白和尾部空白。
boolean equals(Object anObject) :比较存储在两个字符串对象的内容是否一致 。
“==”和equals()有什么区别呢?
==:判断两个字符串在内存中的地址,即判断是否是同一个字符串对象
equals():检查组成字符串内容的字符是否完全一致
字符串的搜索和提取方法
方法名 |
说明 |
public int indexOf(int ch) |
搜索第一个出现的字符ch(或字符串value),如果没有找到,返回-1 |
public int indexOf(String value) | |
public int lastIndexOf(int ch) |
搜索最后一个出现的字符ch(或字符串value),如果没有找到,返回-1 |
public int lastIndexOf(String value) |
|
public String substring(int index) |
提取从位置索引开始的字符串部分 |
public String substring(int beginindex, int endindex) |
提取beginindex和endindex之间的字符串部分 |
public int indexOf(int ch)
public static void main(String[] args) {
String word = "我爱你中国,我爱你故乡爱爱";
int index;
int count = 0;
do {
index = word.indexOf("爱");
if(index >=0 ){
count++;
}
word = word.substring(index + 1);
}while (index >= 0);
System.out.println("爱一共出现" + count + "次");
}
五、StringBuffer类:
StringBuffer类位于java.util包中,是String类的增强类。
对字符串频繁修改时,使用StringBuffer类可以大大提高程序执行效率
StringBuffer类的常用构造方法
StringBuffer strb = new StringBuffer();
StringBuffer strb = new StringBuffer("abc");
StringBuffer类的常用方法
strb.toString(); //将StringBuffer类型的字符串转化为String类型的对象返回
strb.append(Object obj); //将参数连接到字符串后并返回
strb.insert (int offset, Object obj); //将参数插入到字符串指定位置后并返回
实例:
public static void main(String[] args) {
String money = "100245321226";
//1,002,453,213
int lenth = money.length();
StringBuffer sbf = new StringBuffer(money);
for(int i = lenth-3;i > 0;i-=3){
sbf.insert(i,",");
}
sbf.append("¥");
System.out.println(sbf.toString());
}
六、String类、StringBuffer类和StringBuilder类的区别?
1、String是不可变对象,在每次对String类型进行改变时其实都等同于生成了一个新的String对象,然后再指向新的String对象。
2、经常改变内容的字符串最好不要使用String,因为每次生成对象都会对系统性能产生影响。
3、StringBuffer是可变的字符串,在每次对StringBuffer对象进行改变时,会对StringBuffer对象本身进行操作,而不是生成新的对象。
4、字符串经常改变的情况可使用StringBuffer,执行效率要比String类高。
5、StringBuilder等价StringBuffer ,StringBuffer类是线程安全的, StringBuilder类是单线程,不提供同步,理论上效率更高
七、获取时间:Date类、Calendar类
//创建日期对象
Date date = new Date();
//定制日期格式
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy年MM月dd日 HH:mm:ss");
//调用方法将日期格式化为文本
String now = sdf.format(date);
System.out.println(now);
Calendar类
Calendar类是抽象类:用于设置和获取日期/时间数据的特定部分
Calendar类提供一些方法和静态字段来操作日历
常用属性
属性 | 说明 |
static int MONTH |
指示月 |
static int DAY_OF_MONTH |
指示一个月中的某天 |
static int DAY_OF_WEEK |
指示一个星期中的某天 |
常用方法
方法 | 说明 |
static Calendar getInstance() |
使用默认时区和语言环境获得一个Calendar对象 |
int get(int field) |
返回给定日历字段的值 |
实例:
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.get(Calendar.MONTH)+1);
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/93375.html