`

Java入门 基础数据类型

阅读更多

 

package hello;

public class HelloJava {

	/**
	 * @param args
	 * 
	 * java中的数字类型包括 boolean,byte,char,short,int,long,float,double
	 * 
	 */
	public static void main(String[] args) {
		boolean bValue = true;

		System.out.println(String.format("bValue is %1s", bValue));

		byte byteValue = 1;
		System.out.println(String.format("byteValue is %1s", byteValue));

		int intValue = 1 << 31;
		System.out.println(String.format("1<<31 is %1s", intValue));
		
		long longValue = Long.MAX_VALUE;
		System.out.println(String.format("1<<61 is %1s",longValue));
		
		char c = 'a';
		System.out.println(String.format("c is %s",c));
		
		char chineseChar = '中';
		System.out.println(String.format("chineseChar is %1s",chineseChar));
		
		short shortValue = Short.MIN_VALUE;
		System.out.println(String.format("shortValue is %1s",shortValue));
				
		//7到8位有效数字
		float pi = 3.14159262f;
		System.out.println(String.format("pi is %s",pi));
		
		//15-16为有效数字
		double piDouble = 3.14159262;
		System.out.println(String.format("pi is %s",piDouble));
		
		
		//这些基础类型都有对应的类,int对应Integer
		String strInt = "123,456";
		try{
			int intParsed = Integer.parseInt(strInt);
			System.out.println(String.format("intParsed is %s", intParsed));
		}catch(NumberFormatException formatEx){
			System.out.println(String.format("格式错误:%s",strInt));
		}
		
		String strCorrectInt = "123";
		int parsedValue = Integer.parseInt(strCorrectInt);
		System.out.println(String.format("parsedValue is %s",parsedValue));
		
		//http://liumin1939.iteye.com/blog/271245
		//parseInt和valueOf一样,在valueOf的内部调用了parseInt
		//long对应Long
		//short对应Short
		//char对应Character
		//float对应Float
		//double 对应Double
		
		//类型转换,短类型向长类型转换时可以隐式转换;长类型像短类型方向转换时必须显示转换 
		short shortA = 10;
		//隐式转换
		int intA = shortA;		
		//显示转换
		short shortB = (short)intA;
		
		
		//溢出
		short a = Short.MAX_VALUE;
		//溢出了但是没有异常 http://www.iteye.com/problems/83200
		a += 1;
		System.out.println(String.format("a is %s",a));
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics