
Java提供了两个类型系统,基本数据类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型要想对象一样操作,就可以使用基本类型对应的包装类,如下:
byte —> Byte
short —> Short
int —> Int
long —> Long
char —> Char
float —> Float
double —> Double
boolean —> Boolean
装箱与拆箱基本数据类型与对应的包装类对象之间,来回转换的过程称为 “装箱” 与 “拆箱”;
装箱:从基本数据类型转换为对应的包装类对象
**拆箱:**从包装类对象转换为对应的基本数据类型
用Integer与int为例:
基本数值----->包装对象
Integer i1 = new Integer(4); Integer i2 = Integer.valueOf(4);
包装对象----->基本数值
int num = i1.intValue();
自动装箱和自动拆箱
public class WrapperDemo {
public static void main(String[] args) {
//装箱
Integer i1 = new Integer(4);
Integer i2 = Integer.valueOf(56);
//为什么转换成包装类: 可以用面向对象的方式来写。
//拆箱
int num = i2.intValue();
System.out.println("num:"+num);
//JDK1.5之后。自动装箱拆箱
Integer integer = 5; //自动装箱
int result = integer + 1; //自动拆箱
System.out.println("result:"+ result);
}
}
基本类型与字符串之间的转换
基本类型直接与 “ ” 相连接即可;如:34+“”
String转换成对应的基本类型
除了Character类外,其他所有包装类都具有parseXxx静态方法可以将字符串参数转换为对应的基本类型;
public static byte parseByte(String s);将字符串参数转换成对应的byte基本类型。 public static short parseShort(String s);将字符串参数转换成对应的short基本类型。 public static int parseInt(String s);将字符串参数转换成对应的int基本类型。 public static long parseLong(String s);将字符串参数转换成对应的long基本类型。 public static float parseFloat(String s);将字符串参数转换成对应的float基本类型。 public static double parseDouble(String s);将字符串参数转换成对应的double基本类型。 public static boolean parseBoolean(String s);将字符串参数转换成对应的boolean基本类型。
以Integer类的静态方法parseXxx为例。
public class WrapperDemo2 {
public static void main(String[] args) {
int num = Integer.parseInt("100");
}
}
注意:如果字符串参数的内容无法正确转换为对应的基本类型,则会抛出 java.lang.NumberFormatException异常。
2.字符串String类 String构造函数public class StringDemo {
public static void main(String[] args) {
//1.构造函数
String str = "hello,abc";
String helloStr = new String("hello");
char data[] = {'a','b','c','d'};
String charStr = new String(data);
System.out.println("charStr:"+charStr);
byte[] bytes = {97,98,99,100,101,102,103};
String byteStr = new String(bytes);
System.out.println("byteStr:"+byteStr);
String s3 = new String(bytes,0,3);
System.out.println("s3:"+s3);
}
}
String常用方法
| public charAt(int index); | 返回char指定索引处的值 |
|---|---|
| public boolean concat(String str); | 将指定的字符串连接到该字符串的末尾 |
| public char[] toCharArray(); | 将字符串转换成字符数组 |
| public int indexOf(String str); | 查找str首次出现的下标,存在,则返回该下标;不存在,则返回-1。 |
| public int lengh(); | 返回字符串的长度 |
| public String trim(); | 去掉字符串前后的空格 |
| public String toUpperCase(); | 将小写转换成大写 |
| public boolean endsWith(String str); | 判断字符串是否以str结尾 |
| public String replace(char oldChar,char newChar); | 将旧的字符串转换成新的字符串 |
| public String[] split(String str); | 根据str做拆分 |
| public String subString(int beginIndex,int endIndex); | 在字符串中截取一个子字符串 |
示例:
public class StringDemo2 {
public static void main(String[] args) {
String str = "abcd";
char c = str.charAt(2);
System.out.println("返回指定索引的值:"+c);
//String newString = str + "--->";
String newString = str.concat("123");
System.out.println("newString:"+newString);
boolean contains = str.contains("abc");
System.out.println("contains:"+contains);
String txtStr = "hello.txt";
boolean endsWith = txtStr.endsWith(".txt");
System.out.println("endsWith:"+endsWith);
String str1 = "2020qwer";
boolean startWith = str1.startsWith("2021");
System.out.println("startWith:"+startWith);
boolean abc1 = "abc".equals("abc");
System.out.println("abc1:"+abc1);
boolean abc2 = "abc".equalsIgnoreCase("ABC");
System.out.println("abc2:"+abc2);
String str2 = "abc";
char[] chars = str2.toCharArray();
System.out.println(chars);
System.out.println("chars:"+ Arrays.toString(chars));
String str4 = "helloworld!!!";
int index1 = str4.indexOf("ll");
int index2 = str4.indexOf("helloworld!!!");
int index3 = str4.indexOf("A");
System.out.println("index1:"+index1); //2
System.out.println("index2:"+index2); //0
System.out.println("index3:"+index3); //-1
int index4 = str4.indexOf("l",4);
System.out.println("index4:"+index4);
int index5 = str4.lastIndexOf("l");
System.out.println("index5:"+index5);
String string = " ";
System.out.println("判断string是否为空:"+string.isEmpty());
String string1 = "abcdefg";
String www = string1.replace("abc","www");
System.out.println("替换后的String:"+ www);
String string2 = "www==woow==123";
String[] split = string2.split("==");
System.out.println("分割后的数组split:"+Arrays.toString(split));
String string3 = "aaabbb";
String substring1 = string3.substring(3);
System.out.println("substring1:"+substring1);
String substring2 = string3.substring(0,3);
System.out.println("substring2:"+substring2);
String string4 = "ABCdefg";
String string5 = string4.toUpperCase();
System.out.println("转换大写:"+string5);
String string6 = string4.toLowerCase();
System.out.println("转换小写:"+string6);
String s1 = " he llo ";
System.out.println(s1.length());
System.out.println(s1);
String trim = s1.trim();
System.out.println(trim.length());
System.out.println(trim);
int i = 10;
String iStr = i + "";
System.out.println("iStr:"+iStr);
String string7 = String.valueOf(iStr);
System.out.println("iStr:"+iStr);
System.out.println("string7:"+string7);
}
}
String类的内存分析
public class StringDemo3 {
public static void main(String[] args) {
String str1 = "abcd";
String str2 = new String("abcd");
System.out.println("str1==str2:"+(str1==str2)); //false
String str3 = "abc";
String str4 = "abc";
System.out.println("str3==str4:"+(str3==str4)); //true
}
}
3.可变字符串
概念:可在内存中创建可变的缓冲空间,存储频繁改变的字符串。
Java中提供了两种可变字符串类。
**StringBuffer:**可变长字符串,运行效率慢,线程安全。
**StringBuilder:**可变成字符串,运行效率块,线程不安全。
这两个类的方法属性完全一样。
验证StringBuilder效率高于String。
public class StringBuilderTest {
public static void main(String[] args) {
//开始时间
long start = System.currentTimeMillis();
String string = "";
for (int i = 0; i < 99999; i++) {
string += i;
}
System.out.println(string);
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < 99999; i++) {
// sb.append(i);
// }
// System.out.println(sb.toString());
long end = System.currentTimeMillis();
System.out.println("用时:"+ (end -start));
}
}
常用方法:
| 方法名 | 属性 |
|---|---|
| public StringBuilder append(String str) | 追加内容 |
| public StringBuilder insert(int dstOffset,CharSequence s) | 将指定字符串插入此序列中 |
| public StringBuilder delete(int start,int end) | 移除此序列的子字符串中的字符 |
| public StringBuilder replace(int start,int end,String str) | 使用给定字符串替换此序列的子字符串中的字符。start开始位置,end结束位置。 |
| public int length() | 返回长度(字符数) |
示例:
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
//追加
// sb.append(123);
// sb.append(true);
// sb.append("www");
//链式调用
sb.append(123).append(true).append("www.baidu.com");
System.out.println(sb);
// 插入
sb.insert(2,"hello");
System.out.println(sb.toString());
System.out.println("-----------");
sb.delete(3,8); //包含前面的位置不包含后面的位置
System.out.println(sb);
System.out.println("sb的长度:"+sb.length());
}
}
4.日期
Date
Date表示特定的瞬间,精确到毫秒。
Date类中的大部分方法都已经被Calendar类中的方法所取代。
时间单位:
1秒 = 1000毫秒
1毫秒 = 1000微秒
1微秒 = 1000纳秒
CalendarCalendar提供了获取或设置各种日历字段的方法
protected Calendar() 构造方法为protected修饰,无法直接创建该对象
常用方法:
| 方法名 | 说明 |
|---|---|
| static Calendar getInstance() | 使用默认时区和区域获取日历 |
| void set(int year,int month,int date,int hourofday,int minute,int second) | 设置日历的年月日时分秒 |
| int get(int field) | 返回给定日历字段得到值,字段比如年,月,日等 |
| void setTime(Date date) | 用给定的Date设置此日历的时间。Date-Calendar |
| Date getTime() | 返回一个Date表示此日历的时间。Calendar-Date |
| void add(int field, int amount) | 按照日历的规则,给指定字段添加或减少时间量 |
| long getTimeInMillis() | 毫秒为单位返回该日历的时间值 |
simpleDateFormat是以与语言环境有关的方式来格式化和解析日期的类。
格式化:日期–>文本 解析:文本–>日期
public class DateDemo {
public static void main(String[] args) {
Date date = new Date();
long time = date.getTime();
System.out.println("当前时间毫秒值:"+ time);
System.out.println("年:"+date.getYear());
System.out.println("--------------------------");
Calendar now = Calendar.getInstance();
//获取年月日时分秒
// System.out.println("年:"+now.get(Calendar.YEAR));
// System.out.println("月:"+now.get(Calendar.MONTH)); //月份返回0-11
// System.out.println("日:"+now.get(Calendar.DAY_OF_MONTH));
// System.out.println("时:"+now.get(Calendar.HOUR_OF_DAY));
// System.out.println("分:"+now.get(Calendar.MINUTE));
// System.out.println("秒:"+now.get(Calendar.SECOND));
//设置一下时间
now.set(2000,10,10,10,10,0);
// System.out.println("年:"+now.get(Calendar.YEAR));
// System.out.println("月:"+now.get(Calendar.MONTH)); //月份返回0-11
// System.out.println("日:"+now.get(Calendar.DAY_OF_MONTH));
// System.out.println("时:"+now.get(Calendar.HOUR_OF_DAY));
// System.out.println("分:"+now.get(Calendar.MINUTE));
// System.out.println("秒:"+now.get(Calendar.SECOND));
//Date --> Calendar
now.setTime(new Date());
System.out.println("年:"+now.get(Calendar.YEAR));
System.out.println("月:"+now.get(Calendar.MONTH)); //月份返回0-11
System.out.println("日:"+now.get(Calendar.DAY_OF_MONTH));
System.out.println("时:"+now.get(Calendar.HOUR_OF_DAY));
System.out.println("分:"+now.get(Calendar.MINUTE));
System.out.println("秒:"+now.get(Calendar.SECOND));
System.out.println("------------------------------");
now.add(Calendar.MONTH,2); //月 + 2
System.out.println("年:"+now.get(Calendar.YEAR));
System.out.println("月:"+now.get(Calendar.MONTH)); //月份返回0-11
System.out.println("日:"+now.get(Calendar.DAY_OF_MONTH));
System.out.println("时:"+now.get(Calendar.HOUR_OF_DAY));
System.out.println("分:"+now.get(Calendar.MINUTE));
System.out.println("秒:"+now.get(Calendar.SECOND));
// Calendar --> Date
Date time1 = now.getTime();
System.out.println("转换之后的time1:"+ time1);
System.out.println("==============================================================");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
//String ----> Date
String str = "2021-12-12 00:00:00";
try {
Date parse = sdf.parse(str);
System.out.println("解析之后的日期:"+parse);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date currentDate = new Date();
String format = sdf2.format(currentDate);
System.out.println("sdf"+format);
}
}
5.BigDecimal
为什么使用BigDecimal?
很多实际应用中需要精确运算,而double是近似值存储,不在符合要求,需要借助BigDecimal.
double d1 = 1.0;
double d2 = 0.9;
System.out.println(d1-d2);
结果:
0.09999999999999998
BigDecimal的基本用法
位置:java.math包中
作用:精确计算浮点数。
创建方式:BigDecimal bd = new BigDecimal(“1.0”);
常用方法:
| 方法名 | 描述 |
|---|---|
| BigDecimal add(BigDecimal bd) | 加 |
| BigDecimal subtract(BigDecimal bd) | 减 |
| BigDecimal multiply(BigDecimal bd) | 乘 |
| BigDecimal divide(BigDecimal bd) | 除 |
除法:divide(BigDecimal bd,int scal,RoundingMode mode)。
参数scale:指定精确到小数点后几位。
参数mode:指定小数部分的取舍模式,通常用四舍五入的模式。取值为BigDecimal.ROUND_HALF_UP。
public class BigDecimalDemo {
public static void main(String[] args) {
double d1 = 1.0;
double d2 = 0.9;
System.out.println(d1-d2);
//对于精度要求高于double,无法精确
//用 BigDecimal
BigDecimal b1 = new BigDecimal("1.0");
BigDecimal b2 = new BigDecimal("0.9");
//加减乘除
BigDecimal add = b1.add(b2);
System.out.println("add.doublevalue():"+add.doublevalue());
BigDecimal subtract = b1.subtract(b2);
System.out.println("subtract.doublevalue():"+subtract.doublevalue());
BigDecimal multiply = b1.multiply(b2);
System.out.println("multiply.doublevalue():"+multiply.doublevalue());
BigDecimal b3 = new BigDecimal("3");
BigDecimal divide = b1.divide(b3,BigDecimal.ROUND_UP);
System.out.println("divide.doublevalue():"+divide.doublevalue());
}
}
6.System
System系统类:主要用于获取系统的属性数据和其他操作。
常用方法:
| 方法名 | 说明 |
|---|---|
| static void arraycopy(…) | 复制数组 |
| static long currentTimeMillis() | 获取当前系统时间,返回的是毫秒值 |
| static void gc | 建议JVM赶快启动垃圾回收 |
| static void exit(int status) | 推出JVM,如果参数是0表示正常退出JVM,非0表示异常退出JVM。 |
示例:
class Student{
@Override
protected void finalize() throws Throwable {
System.out.println("对象垃圾回收之前调用了。。。");
}
}
public class SystemTest {
public static void main(String[] args) {
//
int[] array = {1,2,3,4,5};
int[] newArray = new int[5];
System.arraycopy(array,2,newArray,0,3);
System.out.println("Arrays.toString(newArray):"+ Arrays.toString(newArray));
long time = System.currentTimeMillis();
System.out.println("当前时间的毫秒值:"+time);
new Student();
new Student();
new Student();
//
System.gc();
//退出JVM之后代码旧不执行了
System.exit(0);
System.out.println("程序结束了!");
}
}
7.对象内存分析
按值传递
public class Demo {
public static void changeNum(int num){
num = 34;
System.out.println("改变后!");
}
public static void main(String[] args) {
int num = 10; //按值传递
changeNum(num);
System.out.println("改变之后的num:"+ num);
}
}
按址传递
class Person{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {}
}
public class Demo {
public static void changePerson(Person p){
p.setName("zhangsan");
p.setAge(23);
}
public static void main(String[] args) {
Person p1 = new Person("lisi", 24);
System.out.println(p1);
changePerson(p1);
System.out.println("p1:"+p1);
}
}