Java 常用类的使用例子(整理)

可变字符序列——StringBuffer

  StringBuffer类和String类的方法几乎一样,不过StringBuffer对象表示的字符串是可以改变的,而String对象保存的字符串是不可变的。

public class Demo {
	public static void main(String[] args) throws Exception {
		// StringBuffer([int capacity]) 不指定容量时,默认capacity为16
		StringBuffer s = new StringBuffer(4);
		System.out.println(s.capacity()); 	//4
		System.out.println(s.length());		//0
		
		// 如果字符串的长度大于原来的容量,则会扩充容量
		s.append("hello");
		System.out.println(s.capacity()); 	//10
		System.out.println(s.length());		//5
	}
}

  

 

日期类——Date

import java.util.Date;

public class Demo {
	public static void main(String[] args) throws Exception {
		System.out.println(new Date());
		// Thu Nov 29 16:01:26 CST 2018
		
		// 获取自1970年1月1日起的毫秒数
		System.out.println(new Date().getTime());
		// 1543478551775
		
		// 传入某个时刻的时间戳,转换为当时的时间标准格式
		System.out.println(new Date(1543478551775L));
		// Thu Nov 29 16:02:31 CST 2018
	}
}

  

更易用的日期类——SimpleDateFormat

import java.util.Date;
import java.text.SimpleDateFormat;

public class Demo {
	public static void main(String[] args)  {
		SimpleDateFormat d1 = new SimpleDateFormat();
		System.out.println(d1.format(new Date())); 
		// 18-11-29 下午4:12
		
		SimpleDateFormat d2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(d2.format(new Date())); 
		// 2018-11-29 16:16:14
		
		// 将时间戳转化为标准格式
		System.out.println(d2.format(new Date(1543478551775L)));
		// 2018-11-29 16:02:31
	}
}

  

 

数学计算类——Math

  注意Math类是java.lang包下面,所以Math类不用import。

 

转载于:https://www.cnblogs.com/-beyond/p/6240829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值