Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 视频教程 | 打赏(Donations) | About
知乎专栏多维度架构 微信号 netkiller-ebook | QQ群:128659835 请注明“读者”

1.4. 类型

数据类型的最大值和最小值。

	

基本类型:int 二进制位数:32
包装类:java.lang.Integer
最小值:Integer.MIN_VALUE= -2147483648 (-2的31次方)
最大值:Integer.MAX_VALUE= 2147483647  (2的31次方-1)

基本类型:short 二进制位数:16
包装类:java.lang.Short
最小值:Short.MIN_VALUE=-32768 (-2的15此方)
最大值:Short.MAX_VALUE=32767 (2的15次方-1)

基本类型:long 二进制位数:64
包装类:java.lang.Long
最小值:Long.MIN_VALUE=-9223372036854775808 (-2的63次方)
最大值:Long.MAX_VALUE=9223372036854775807 (2的63次方-1)

基本类型:float 二进制位数:32
包装类:java.lang.Float
最小值:Float.MIN_VALUE=1.4E-45 (2的-149次方)
最大值:Float.MAX_VALUE=3.4028235E38 (2的128次方-1)

基本类型:double 二进制位数:64
包装类:java.lang.Double
最小值:Double.MIN_VALUE=4.9E-324 (2的-1074次方)
最大值:Double.MAX_VALUE=1.7976931348623157E308 (2的1024次方-1)	
	
	

1.4.1. var 本地变量类型推断

		
var javastack = "javastack";
就等于:
String javastack = "javastack";		
		
		

1.4.2. Integer

		
十进制转成十六进制:   
  
Integer.toHexString(int i)   
  
十进制转成八进制   
  
Integer.toOctalString(int i)   
  
十进制转成二进制   
  
Integer.toBinaryString(int i)   
  
十六进制转成十进制   
  
Integer.valueOf("FFFF",16).toString()   
  
八进制转成十进制   
  
Integer.valueOf("876",8).toString()   
  
二进制转十进制   
  
Integer.valueOf("0101",2).toString()   
  
  
  
有什么方法可以直接将2,8,16进制直接转换为10进制的吗?   
  
java.lang.Integer类   
  
parseInt(String s, int radix)   
  
使用第二个参数指定的基数,将字符串参数解析为有符号的整数。   
  
examples from jdk:   
  
parseInt("0", 10) returns 0   
  
parseInt("473", 10) returns 473   
  
parseInt("-0", 10) returns 0   
  
parseInt("-FF", 16) returns -255   
  
parseInt("1100110", 2) returns 102   
  
parseInt("2147483647", 10) returns 2147483647   
  
parseInt("-2147483648", 10) returns -2147483648   
  
parseInt("2147483648", 10) throws a NumberFormatException   
  
parseInt("99",throws a NumberFormatException   
  
parseInt("Kona", 10) throws a NumberFormatException   
  
parseInt("Kona", 27) returns 411787    
  
  
例二   
  
  
int i=100;   

String binStr=Integer.toBinaryString(i);   
String otcStr=Integer.toOctalString(i);   
String hexStr=Integer.toHexString(i);   
System.out.println(binStr);   
  

  
  
  
  
例二   
 
Integer factor = Integer.valueOf(args[0]);   
  
String s;   

  
s = String.format("%d", factor);     
System.out.println(s);   
  
s = String.format("%x", factor);   
System.out.println(s);   
  
s = String.format("%o", factor);   
System.out.println(s);   
  
其他方法:   
  
  
  
Integer.toHexString(你的10进制数);   
  
例如   
  
String temp = Integer.toHexString(75);   
  
输出temp就为 4b     		
		
		

1.4.2.1. 前面补零

			
public static String frontCompWithZore(int sourceDate,int formatLength) {  
  
  String newString = String.format("%0"+formatLength+"d", sourceDate);   
  return newString;  
}  			
			
			

1.4.3. String

Java 11 增加了一系列的字符串处理方法,如以下所示。

		
// 判断字符串是否为空白
" ".isBlank(); // true
// 去除首尾空格
" Javastack ".strip(); // "Javastack"
// 去除尾部空格
" Javastack ".stripTrailing(); // " Javastack"
// 去除首部空格
" Javastack ".stripLeading(); // "Javastack "
		
		

1.4.3.1. 查找字符重现的位置

			
package cn.netkiller.test;

public class Test {

	public static void main(String[] args) {

		String string = new String("http://www.netkiller.cn");

		System.out.println("查找字符 . 第一次出现的位置: " + string.indexOf('.'));
		System.out.println("从第15个字符位置查找字符 . 出现的位置:" + string.indexOf('.', 15));
	}
}	
			
			

1.4.3.2. 行数统计

			
"A\nB\nC".lines().count(); // 3			
			
			

1.4.3.3. 复制字符串

			
"Java".repeat(3);// "JavaJavaJava"			
			
			

1.4.3.4. 随机字符串

			
	public String randomString(String chars, int length) {
		Random rand = new Random();
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < length; i++) {
			buf.append(chars.charAt(rand.nextInt(chars.length())));
		}
		return buf.toString();
	}
	
	/**
     * 获取4位随机验证码
     * @return
     */
    public static String getValidationCode(){
        return String.valueOf((new Random().nextInt(8999) + 1000));
    }

    /**
     * 获取6位随机验证码
     * @return
     */
    public static String getValidationCode(){
        return String.valueOf((new Random().nextInt(899999) + 100000));
    }	
			
			

1.4.3.5. 字符串替换处理

			
public class Test {

	public Test() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("2010-09-11T20:00:30".replace("T", " "));
	}
}
			
			
			
				{"status":0,"message":"","bankcode":"ABOC;IBC;CCTB;ICBC"}
				转换后
				{\"status\":0,\"message\":\"\",\"bankcode\":\"ABOC;IBC;CCTB;ICBC\"}
			
			
package test;

public class str {

	public static void main(String[] args) {
		String jsonString = "{\"status\":0,\"message\":\"\",\"bankcode\":\"ABOC;IBC;CCTB;ICBC\"}";
		System.out.println(jsonString);
		System.out.println(jsonString.replace("\"", "\\\""));
	}

}
			
			
1.4.3.5.1. 正则表达式查找与替换

查找特定字符并替换为找到的内容

				
package cn.netkiller.type;

public class ragexTest {

	public ragexTest() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String str = "<html>Netkiller</html>";
		String regex = "<html>|</html>";
		//运行结果返回 Netkiller
		System.out.println(str.replaceAll(regex, ""));
		
		// 运行结果返回 Neo
		System.out.println("CN/NETKILLER/WWW/Neo_Chen".replaceAll(".*/(.+)_Chen", "$1"));
	}
}
				
				
1.4.3.5.2. 利用正则快速转换时间格式
				
// 20200303 => 2020-03-03
date = date.replace(/(.{4})/, "$1-");
date = date.replace(/(.{7})/, "$1-");				
				
				

1.4.3.6. substring

			
例如:
String str = "helloword!!!";

System.out.println(str.substring(1,4));

System.out.println(str.substring(3,5));

System.out.println(str.substring(0,4));

将得到结果为:

ell

lo 

hell
			
			

1.4.3.7. string to timestamp

Timestamp转化为String:

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //定义格式,不显示毫秒
				Timestamp now = new Timestamp(System.currentTimeMillis());
				//获取系统当前时间
				String str = df.format(now);
			

String转化为Timestamp:

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String time = df.format(new Date());
				Timestamp ts = Timestamp.valueOf(time);
			

1.4.3.8. String.strip

java11对String类新增了strip,stripLeading以及stripTrailing方法,除了strip相关的方法还新增了isBlank、lines、repeat(int)等方法

			
	@Test
    public void testStrip(){
        String text = "  \u2000a  b  ";
        Assert.assertEquals("a  b",text.strip());
        Assert.assertEquals("\u2000a  b",text.trim());
        Assert.assertEquals("a  b  ",text.stripLeading());
        Assert.assertEquals("  \u2000a  b",text.stripTrailing());
    }
			
			

1.4.3.9. Ascii

			
		String string = "佛山市123南海区ABC精密abc机械有限公司􁵪􁻠􁴹􄲀􀞜􀨨,";

		String clean = string.replaceAll("\\P{Print}", "");
		System.out.println(clean);			
			
			

1.4.3.10. 字符串处理,删除中文以外的字符

Unicode 码表 https://www.ssec.wisc.edu/~tomw/java/unicode.html

			
	String string = "2017-12-18 netkiller http://www.netkiller.cn -  网站正常";
	System.out.println(string.replaceAll("[^\u4e00-\u9fa5]", ""));			
			
			

1.4.3.11. 取出字符串中的中文字符

Unicode 码表 https://www.ssec.wisc.edu/~tomw/java/unicode.html

			
		String string = "2017-12-18 netkiller http://www.netkiller.cn -  网站正常";
		String regex = "[\u4e00-\u9fa5]";
		System.out.println(string.replaceAll(regex, ""));			
			
			

1.4.4. 类型转换

1.4.4.1. Long to String

			
	public class MainClass {

	  public static void main(String[] arg) {
	    long b = 12L;
	    System.out.println(String.valueOf(b));   
	
	  }
	}
			
			

1.4.5. Date

java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp 区别

		
package cn.netkiller.java.date;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) {
		System.out.println("Hello World!");

		// Get standard date and time
		java.util.Date utilDate = new java.util.Date();
		long javaTime = utilDate.getTime();
		System.out.println("The Java Date is:" + utilDate.toString());

		// Get and display SQL DATE
		java.sql.Date sqlDate = new java.sql.Date(javaTime);
		System.out.println("The SQL DATE is: " + sqlDate.toString());

		// Get and display SQL TIME
		java.sql.Time sqlTime = new java.sql.Time(javaTime);
		System.out.println("The SQL TIME is: " + sqlTime.toString());
		
		// Get and display SQL TIMESTAMP
		java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(javaTime);
		System.out.println("The SQL TIMESTAMP is: " + sqlTimestamp.toString());
	}
}

		
		
			The Java Date is:Thu Aug 24 16:51:57 CST 2017
			The SQL DATE is: 2017-08-24
			The SQL TIME is: 16:51:57
			The SQL TIMESTAMP is: 2017-08-24 16:51:57.234
		

1.4.5.1. SimpleDateFormat

				public static void main(String[] args) {

				DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				//get current date time with Date()
				Date date = new Date();
				System.out.println(dateFormat.format(date));

				//get current date time with Calendar()
				Calendar cal = Calendar.getInstance();
				System.out.println(dateFormat.format(cal.getTime()));

				}
			

1.4.5.2. Timestamp

				Timestamp timestamp = new Timestamp(System.currentTimeMillis());

				Date date = new Date();
				Timestamp timestamp = new Timestamp(date.getTime());
			

1.4.5.3. TimeZone

				package cn.netkiller.example;

				import java.sql.Timestamp;
				import java.text.SimpleDateFormat;
				import java.util.Calendar;
				import java.util.Date;
				import java.util.GregorianCalendar;
				import java.util.TimeZone;

				public class TimeZoneTest {

				public TimeZoneTest() {
				// TODO Auto-generated constructor stub
				}

				public static void main(String[] args) {
				// TODO Auto-generated method stub

				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				TimeZone timeZone = TimeZone.getTimeZone("Asia/Harbin");

				Date date = new Date();
				Timestamp timestamp = new Timestamp(date.getTime());

				System.out.println(timestamp);

				timestamp.setHours(timestamp.getHours()+8);
				System.out.println(timestamp);

				simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
				System.out.println(simpleDateFormat.format(date));

				simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Harbin"));
				System.out.println(simpleDateFormat.format(date));

				Calendar calendar = new GregorianCalendar();
				calendar.setTime(date);
				calendar.setTimeZone(timeZone);
				System.out.println(simpleDateFormat.format(calendar.getTime()));
				}

				}
			

1.4.5.4. String to Date

			
package cn.netkiller.example;

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

public class StringToDate {

	public StringToDate() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = "2008-8-8 8:8:8";

		try {

			Date date = formatter.parse(dateString);
			System.out.println(date);
			System.out.println(formatter.format(date));

		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

}			
			
			

1.4.5.5. 比较两个日期与时间

			
package cn.netkiller.example;

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

public class DateCompare {

	public DateCompare() {
		// TODO Auto-generated constructor stub
	}

	public void fun1() throws InterruptedException {
		Date d1 = new Date();
		Thread.sleep(5000);
		Date d2 = new Date();
		if (d1.before(d2)) {
			System.out.println(String.format("%s < %s", d1.toString(), d2.toString()));
		} else {
			System.out.println(String.format("%s > %s", d1.toString(), d2.toString()));
		}
		if (d2.after(d1)) {
			System.out.println(String.format("%s > %s", d2.toString(), d1.toString()));
		}

		System.out.println(String.format("%s : %s => %d", d2.toString(), d1.toString(), d1.compareTo(d2)));
		System.out.println(String.format("%s : %s => %d", d1.toString(), d2.toString(), d2.compareTo(d1)));
	}

	public void fun2() throws InterruptedException {

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date date1 = new Date();
		Date date2 = new Date();
		String s1 = dateFormat.format(date1);
		String s2 = dateFormat.format(date2);
		System.out.println(String.format("%s : %s => %d", s1, s2, s1.compareTo(s2)));

		date1 = new Date();
		Thread.sleep(5000);
		date2 = new Date();
		s1 = dateFormat.format(date1);
		s2 = dateFormat.format(date2);
		System.out.println(String.format("%s : %s => %d", s1, s2, s1.compareTo(s2)));
		System.out.println(String.format("%s : %s => %d", s2, s1, s2.compareTo(s1)));
		System.out.println();
	}

	public void fun3() throws InterruptedException, ParseException {
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		//Date time = formatter.parse("2016-09-27 16:29");
		Date time = formatter.parse("2016-08-09 09:15");
		Date startDate = formatter.parse("2016-08-09 09:15");
		Date endDate = formatter.parse("2016-09-27 16:30");
		
		if (time.before(startDate) || time.after(endDate)) {
			System.out.println("Skip");
		}
	}

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		DateCompare dateCompare = new DateCompare();
		dateCompare.fun1();
		System.out.println();
		dateCompare.fun2();
		System.out.println();
		dateCompare.fun3();
	}

}
			
			

1.4.5.6. Calendar

				
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH )+1;
		
		System.out.println(year + "年 " + month + "月");
			
			

1.4.5.7. getToday

			
	public Date getToday(String time) {
		final Calendar cal = Calendar.getInstance();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd " + time);
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = fmt.parse(dateFormat.format(cal.getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	private Date addOneDay(Date date, int day) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, day);
		return cal.getTime();
	}
			
			

1.4.5.8. Yesterday

					
package cn.netkiller.date;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Yesterday {

	public Yesterday() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Yesterday yesterday = new Yesterday();
		System.out.println(yesterday.yesterday());
		System.out.println(yesterday.getYesterday("00:00:00"));
		System.out.println(yesterday.getYesterday("23:59:59"));
	}
	private Date yesterday() {
	    final Calendar cal = Calendar.getInstance();
	    cal.add(Calendar.DATE, -1);
	    return cal.getTime();
	}

	private Date getYesterday(String time) {
	        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd "+time);
	        
	        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        Date date = null;
	        try {
	            date = fmt.parse(dateFormat.format(yesterday()));
	        } catch (ParseException e) {
	            e.printStackTrace();
	        }
	        return date;
	}
}
		

			

1.4.5.9. ISO 8601

			
ISO 8601扩展格式 YYYY-MM-DDTHH:mm:ss.sssZ
			
			

1.4.5.10. LocalDateTime

			
	LocalDateTime localDateTime = LocalDateTime.of(2016, 1, 1, 13, 55);
	ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
	Date date = Date.from(zonedDateTime.toInstant());	
		
	Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
    Instant instant = ldt.toInstant(ZoneOffset.UTC);
    Date date = Date.from(instant);		
				
			
			

1.4.5.11. ZonedDateTime

			
Date.from(java.time.ZonedDateTime.now().toInstant());			
			
			

1.4.6. Array

一定字符串数组

		
String[] str={"AAA","BBB","CCC"};
String str[]={"AAA","BBB","CCC"};		
		
		

String to Array

		
package cn.netkiller.java;

public class StringToArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
		String[] array = null;   
		array = str.split(",");
		for(int i=0; i<array.length; i++){
			System.out.println(array[i]);
		}
	}
}		
		
		

1.4.6.1. for each

			
	public static void main(String[] args) {
		try {
			
			for (String arg : args) {
				System.out.println(arg);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}			
			
			

1.4.6.2. Array to String

			
package cn.netkiller.java;

import java.util.Arrays;

public class ArrayToString {

	public static void main(String[] args) {
		String[] array = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
		System.out.println(Arrays.toString(array));
		System.out.println(Arrays.toString(array).replaceAll(", |\\[|\\]", ""));
	}

}
			
			

			
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));		

Output:
[[John, Mary], [Alice, Bob]]	
			
			

1.4.6.3. 

			
String[] array = {"neo", "chen"};
String string = String.join(",", array)
// 输出结果 "neo,chen"		
			
			

1.4.7. float

float 不能直接做减法运算

			float a = 77.22f;
			float b = 77.2f;

			System.out.println((float)a-b);
			System.out.println((float)a+b);

			输出结果为:
			0.020004272
			154.42
		

		
package cn.netkiller.example;

import java.math.BigDecimal;

public class Math {

	public Math() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {

		float a = 77.22f;
		float b = 77.2f;

		System.out.println((float) a + b);
		System.out.println((float) a - b);
		System.out.println((float) a * b);
		System.out.println((float) a / b);

		System.out.println("-------------");

		System.out.println(add(a, b));
		System.out.println(sub(a, b));
		System.out.println(mul(a, b));
		System.out.println(div(a, b));

	}

	public static float add(float v1, float v2) {
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.add(b2).floatValue();
	}

	public static float sub(float v1, float v2) {
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.subtract(b2).floatValue();
	}

	public static float mul(float v1, float v2) {
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.multiply(b2).floatValue();
	}

	public static float div(float v1, float v2) {
		return div(v1, v2, 5);
	}

	public static float div(float v1, float v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Float.toString(v1));
		BigDecimal b2 = new BigDecimal(Float.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue();
	}

	public static float round(float v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Float.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue();
	}
}

		
		

1.4.8. double

		
package cn.netkiller.example;

import java.math.BigDecimal;

public class Math {

	public Math() {
		// TODO Auto-generated constructor stub
	}

	public static double add(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.add(b2).doubleValue();
	}

	public static double sub(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.subtract(b2).doubleValue();
	}

	public static double mul(double v1, double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	public static double div(double v1, double v2) {
		return div(v1, v2, 8);
	}

	public static double div(double v1, double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static double round(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b = new BigDecimal(Double.toString(v));
		BigDecimal one = new BigDecimal("1");
		return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
}		
		
		

1.4.8.1. String to double

			
double amount = Double.parseDouble(value);			
			
			

1.4.9. BigDecimal

		
package cn.netkiller.example;

import java.math.BigDecimal;

public class BigDecimalTest {

	public BigDecimalTest() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BigDecimal first = new BigDecimal("1.0");
		BigDecimal second = new BigDecimal("1.77");
		System.out.println(String.format("%s, %s", first, second));

		if (first.equals(second))

			System.out.println("equals: true");

		else

			System.out.println("equals: false");

		if (first.compareTo(second) == 0)

			System.out.println("compareTo: true");
		else
			System.out.println("compareTo: false");

		BigDecimal zero = new BigDecimal("0");
		BigDecimal one = new BigDecimal("1");
		BigDecimal minus = new BigDecimal("-1");

		if (zero.compareTo(one) < 0)

			System.out.println("比較演算子[ <  ]: true");

		if (one.compareTo(one) == 0)

			System.out.println("比較演算子[ == ]: true");

		if (zero.compareTo(minus) > 0)

			System.out.println("比較演算子[ >  ]: true");

		if (zero.compareTo(minus) >= 0)

			System.out.println("比較演算子[ >= ]: true");

		if (zero.compareTo(minus) != 0)

			System.out.println("比較演算子[ != ]: true");

		if (zero.compareTo(one) <= 0)
			System.out.println("比較演算子[ <= ]: true");

	}

}
		
		

1.4.9.1. Convert BigDecimal Object to double value

			
BigDecimal.doubleValue()
			
			

1.4.9.2. 去除末尾多余的0

			
System.out.println( new BigDecimal("100.000").stripTrailingZeros().toString());		
			
			

1.4.9.3. 禁用科学计数法

			
有时会输出 1E+2,如果你不希望这种科学计数法输出可以使用 toPlainString() 替代 toString()
System.out.println( new BigDecimal("100.000").stripTrailingZeros().toPlainString());			
			
			

1.4.9.4. 移动小数点位置

			
package cn.netkiller.example.test;

import java.math.BigDecimal;
import java.math.BigInteger;

public class Test {

	public Test() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int decimal = 4;

		BigInteger amount = BigInteger.valueOf(10000000000L);
		BigDecimal balance = new BigDecimal(amount);
		BigDecimal point = new BigDecimal(0.1 / Math.pow(10, decimal));
		balance = balance.multiply(point);
		System.out.println(balance);
	}

}			
			
			

发现输出有问题 100000.000000000008180305391403130954586231382563710212707519531250000000000

换种方法

			
package cn.netkiller.example.test;

import java.math.BigDecimal;
import java.math.BigInteger;

public class Test {

	public Test() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// String i = Integer.valueOf("0x57c457",16).toString();
		// System.out.println(i);

		int decimal = 6;

		BigInteger amount = BigInteger.valueOf(10000000000L);

		System.out.println(amount);

		String tmp = amount.toString();

		String number = new StringBuffer(tmp).insert(tmp.length() - decimal, ".").toString();
		BigDecimal balance = new BigDecimal(number);

		System.out.println(balance);
	}

}			
			
			

最佳方案

			

		int decimal = 6;

		System.out.println(BigDecimal.TEN.pow(decimal));
		BigDecimal balance1 = new BigDecimal("1234");
		BigDecimal value = balance1.divide(BigDecimal.TEN.pow(decimal));
		System.out.println(value);

		BigDecimal balance2 = new BigDecimal("12.107");
		BigDecimal value2 = balance2.multiply(BigDecimal.TEN.pow(decimal)).setScale(0, RoundingMode.DOWN);
		System.out.println(value2);			
			
			

1.4.10. StringBuffer

		
String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();

Or if you need synchronization use the StringBuffer with similar usage :

String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();		
		
		

1.4.11. enum

		
class EnumExample1{

	public enum Season { WINTER, SPRING, SUMMER, FALL }
	
	public static void main(String[] args) {
		for (Season s : Season.values())
			System.out.println(s);
	}
}		
		
		

		
		
package cn.netkiller.api.util;

public enum HttpMethod {
    GET("GET"), POST("POST"), PUT("PUT"), PATCH("PATCH"), DELETE("DELETE");

    private String value;

    private HttpMethod(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}		
		
		

1.4.12. byte 类型

1.4.12.1. string2byte

			
	byte[] bytes = "Helloworld!!! - http://www.netkiller.cn".getBytes();		
			
			

1.4.12.2. byte[] to String

			
	byte[] bytes = "Helloworld!!! - http://www.netkiller.cn".getBytes();
	String str = new String(bytes, StandardCharsets.UTF_8);
	System.out.println(str);
			
			

1.4.12.3. BigInteger2byte

			
BigInteger b= new BigInteger('300');
byte bytes= b.byteValue();			
			
			

1.4.12.4. int to byte array

			
int a= 120;
byte b= (byte)a;			
			
			
			
private byte[] bigIntToByteArray( final int i ) {
    BigInteger bigInt = BigInteger.valueOf(i);      
    return bigInt.toByteArray();
}			
			
			
			
private byte[] intToByteArray ( final int i ) throws IOException {      
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    dos.writeInt(i);
    dos.flush();
    return bos.toByteArray();
}			
			
			
			
private byte[] intToBytes( final int i ) {
    ByteBuffer bb = ByteBuffer.allocate(4); 
    bb.putInt(i); 
    return bb.array();
}						
			
			

位移操作

			
private static byte[] intToBytes(final int a) {
    return new byte[] {
        (byte)((data >> 24) & 0xff),
        (byte)((data >> 16) & 0xff),
        (byte)((data >> 8) & 0xff),
        (byte)((data >> 0) & 0xff),
    };
}			
			
			

1.4.12.5. byte array to int

			
private int convertByteArrayToInt(byte[] intBytes){
    ByteBuffer byteBuffer = ByteBuffer.wrap(intBytes);
    return byteBuffer.getInt();
}			
			
			
			
private int convertByteArrayToInt(byte[] data) {
    if (data == null || data.length != 4) return 0x0;
    // ----------
    return (int)( // NOTE: type cast not necessary for int
            (0xff & data[0]) << 24  |
            (0xff & data[1]) << 16  |
            (0xff & data[2]) << 8   |
            (0xff & data[3]) << 0
            );
}			
			
			

			
	public static byte[] intToByte32(int num) {
        byte[] arr = new byte[32];
        for (int i = 31; i >= 0; i--) {
            // &1 也可以改为num&0x01,表示取最地位数字.
            arr[i] = (byte) (num & 1);
            // 右移一位.
            num >>= 1;
        }
        return arr;
    }

			
	public static int byte32ToInt(byte[] arr) {
        if (arr == null || arr.length != 32) {
            throw new IllegalArgumentException("byte数组必须不为空,并且长度是32!");
        }
        int sum = 0;
        for (int i = 0; i < 32; ++i) {
            sum |= (arr[i] << (31 - i));
        }
        return sum;
    }			
			
			

int array to byte array

			
private byte[] convertIntArrayToByteArray(int[] data) {
        if (data == null) return null;
        // ----------
        byte[] byts = new byte[data.length * 4];
        for (int i = 0; i < data.length; i++)
            System.arraycopy(convertIntToByteArray(data[i]), 0, byts, i * 4, 4);
        return byts;
    }			
			
			

byte array to int array

			
public int[] convertByteArrayToIntArray(byte[] data) {
        if (data == null || data.length % 4 != 0) return null;
        // ----------
        int[] ints = new int[data.length / 4];
        for (int i = 0; i < ints.length; i++)
            ints[i] = ( convertByteArrayToInt(new byte[] {
                    data[(i*4)],
                    data[(i*4)+1],
                    data[(i*4)+2],
                    data[(i*4)+3],
            } ));
        return ints;
    }			
			
			

1.4.12.6. byte2char

			
	byte b1 = 65;
    // char ch = b1;  
          
    char ch = (char) b1;
 
    System.out.println("byte value: " + b1);             // prints 65
    System.out.println("Converted char value: " + ch);   // prints A (ASCII is 65 for A)			
			
			

			
	public static char byte2ToChar(byte[] arr) {
        if (arr == null || arr.length != 2) {
            throw new IllegalArgumentException("byte数组必须不为空,并且是2位!");
        }
        return (char) (((char) (arr[0] << 8)) | ((char) arr[1]));
    }			
    
    public static byte[] charToByte2(char c) {
        byte[] arr = new byte[2];
        arr[0] = (byte) (c >> 8);
        arr[1] = (byte) (c & 0xff);
        return arr;
    }
			
			

1.4.12.7. longToByte64

			
    public static byte[] longToByte64(long sum) {
        byte[] arr = new byte[64];
        for (int i = 63; i >= 0; i--) {
            arr[i] = (byte) (sum & 1);
            sum >>= 1;
        }
        return arr;
    }			
			
			

1.4.12.8. byte64ToLong

			
	public static long byte8ToLong(byte[] arr) {
        if (arr == null || arr.length != 8) {
            throw new IllegalArgumentException("byte数组必须不为空,并且是8位!");
        }
        return (long) (((long) (arr[0] & 0xff) << 56) | ((long) (arr[1] & 0xff) << 48) | ((long) (arr[2] & 0xff) << 40)
                        | ((long) (arr[3] & 0xff) << 32) | ((long) (arr[4] & 0xff) << 24)
                        | ((long) (arr[5] & 0xff) << 16) | ((long) (arr[6] & 0xff) << 8) | ((long) (arr[7] & 0xff)));
    }
    			
	public static byte[] longToByte8(long sum) {
        byte[] arr = new byte[8];
        arr[0] = (byte) (sum >> 56);
        arr[1] = (byte) (sum >> 48);
        arr[2] = (byte) (sum >> 40);
        arr[3] = (byte) (sum >> 32);
        arr[4] = (byte) (sum >> 24);
        arr[5] = (byte) (sum >> 16);
        arr[6] = (byte) (sum >> 8);
        arr[7] = (byte) (sum & 0xff);
        return arr;
    }
    			
	public static long byte64ToLong(byte[] arr) {
        if (arr == null || arr.length != 64) {
            throw new IllegalArgumentException("byte数组必须不为空,并且长度是64!");
        }
        long sum = 0L;
        for (int i = 0; i < 64; ++i) {
            sum |= ((long) arr[i] << (63 - i));
        }
        return sum;
    }			
			
			

1.4.12.9. short2byte

			
    public static byte[] shortToByte16(short s) {
        byte[] arr = new byte[16];
        for (int i = 15; i >= 0; i--) {
            arr[i] = (byte) (s & 1);
            s >>= 1;
        }
        return arr;
    }

    public static short byte16ToShort(byte[] arr) {
        if (arr == null || arr.length != 16) {
            throw new IllegalArgumentException("byte数组必须不为空,并且长度为16!");
        }
        short sum = 0;
        for (int i = 0; i < 16; ++i) {
            sum |= (arr[i] << (15 - i));
        }
        return sum;
    }			
    
    public static short byte2ToShort(byte[] arr) {
        if (arr != null && arr.length != 2) {
            throw new IllegalArgumentException("byte数组必须不为空,并且是2位!");
        }
        return (short) (((short) arr[0] << 8) | ((short) arr[1] & 0xff));
    }
    
    public static byte[] shortToByte2(Short s) {
        byte[] arr = new byte[2];
        arr[0] = (byte) (s >> 8);
        arr[1] = (byte) (s & 0xff);
        return arr;
    }
			
			

1.4.12.10. byte8ToDouble

			
	public static double byte8ToDouble(byte[] arr) {
        if (arr == null || arr.length != 8) {
            throw new IllegalArgumentException("byte数组必须不为空,并且是8位!");
        }
        long l = byte8ToLong(arr);
        return Double.longBitsToDouble(l);
    }

    public static byte[] doubleToByte8(double i) {
        long j = Double.doubleToLongBits(i);
        return longToByte8(j);
    }			
			
			

1.4.12.11. byte4ToFloat

			
    public static float byte4ToFloat(byte[] arr) {
        if (arr == null || arr.length != 4) {
            throw new IllegalArgumentException("byte数组必须不为空,并且是4位!");
        }
        int i = byte4ToInt(arr);
        return Float.intBitsToFloat(i);
    }

    public static byte[] floatToByte4(float f) {
        int i = Float.floatToIntBits(f);
        return intToByte4(i);
    }			
			
			

1.4.12.12. 无符号 byte

			
byte b= -120;
int a= bytes & 0xff;
			
			

			
byte a = (byte)234;
System.out.println(a);

上面的代码,结果是-22,因为java中byte是有符号的,byte范围是-128~127。

如果想输出234,该怎么做呢,首先想到的是将a 赋给大一点的类型,如下:

byte a = (byte)234;
int i = a&0xff;
System.out.println(i);

原因是 0xff是int,占4个字节,a是byte,占1个字节,进行&操作的细节如下:

   00000000 00000000 00000000 11101010    (a)
&
   00000000 00000000 00000000 11111111    (0xff)
---------------------------------------------------------------------
=  00000000 00000000 00000000 11101010

结果是int,但是符号位是0,说明是正数,最后就是正整数234.	
			
			

1.4.12.13. byte to hex

			
byte bv = 10;
String hexString = Integer.toHexString(bv);			
			
			

1.4.12.14. byte[] to hex

			
byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61};
System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(bytes));			
			
			

			
public static String byteArrayToHex(byte[] bytes) {
   StringBuilder sb = new StringBuilder(a.length * 2);
   for(byte b: bytes)
      sb.append(String.format("%02x", b));
   return sb.toString();
}
			
			
			
BigInteger n = new BigInteger(byteArray);
String hexa = n.toString(16));			
			
			

1.4.12.15. 连接两个 byte[]

			
byte[] one = { 1, 2, 3 };
byte[] two = { 6, 8, 9 };
int length = one.Length + two.Length;
byte[] sum = new byte[length];
one.CopyTo(sum,0);
two.CopyTo(sum,one.Length);			
			
			
			
byte[] one = { 1, 2, 3 };
byte[] two = { 6, 8, 9 };
List<byte> list1 = new List<byte>(one);
List<byte> list2 = new List<byte>(two);
list1.AddRange(list2);
byte[] sum2 = list1.ToArray();			
			
			

1.4.12.16. List<Byte> to byte[]

			
		List<Byte> byteList = new ArrayList<Byte>();
        byteList.add((byte) 1);
        byteList.add((byte) 2);
        byteList.add((byte) 3);
        byte[] byteArray = Bytes.toArray(byteList);
        System.out.println(Arrays.toString(byteArray));