Java基本类型

阅读数:74 评论数:0

跳转到新版页面

分类

python/Java

正文

1、基本类型

在程序设计中经常用到一系列类型(基本类型),它们需要特殊对待。对于这些类型,Java采取与C和C++相同的方法,也就是说,不用new来创建变量,于是创建一个并非引用的变量,这个变量直接存储“值”,并置于堆栈中,因此更加高效。

 

基本类型 包装类型 大小
boolean Boolean -
char Character 16-bit
byte Byte 8-bit
short Short 16-bit
int Integer 32-bit
long Long 64-bit
float Float 32-bit
double Double 64-bit
void Void -

基本类型具有的装类,使得可以在堆中创建一个非基本对象,用来表示对应的基本类型。

public class AutoBoxingTest{
	public static final Integer CONST_A = 1;
	public static final Integer CONST_B = Integer.valueOf("2");
	public static final Integer CONST_C = new Integer(3);

	private Integer status;
	public void setStatus(Integer status){
		this.status = status;
	}
	public void displayStatus(){
		if(status==CONST_A)
			System.out.println("It's CONST_A");
		else if(status==CONST_B)
			System.out.println("It's CONST_B");
		else if(status==CONST_C)
			System.out.println("It's CONST_C");
		else
			System.out.println("Invalid status!");
	}
	public static void main(String[] args){
		AutoBoxingTest abt = new AutoBoxingTest();
		abt.setStatus(1);
		abt.displayStatus();
		abt.setStatus(2);
		abt.displayStatus();
		abt.setStatus(3);
		abt.displayStatus();
	}
}
/**
执行结果:
It's CONST_A
It's CONST_B
Invalid status!
原因:
在自动装箱和调用Integer.valueOf(String)时,返回的Integer是从IntegerCache中获取的,所以都是同一个对象。
延伸一下,如果一边是包装类,一边是基本类型时,使用< 、> 、<=等比较,都会时行值比较。
*/

Java提供了两个用于高精度计算的类:BigInteger、BigDecimal。

import java.math.BigInteger;
public class MainClass{
	public static void main(String[] argv)throws Exception
	{
		BigInteger bigInteger1 = new BigInteger("123456789012345678901234567890");
		BigInteger bigInteger2 = new BigInteger("123456789012345678901234567890");
		//add
		bigInteger1 = bigIntger1.add(bigInteger2);
		System.out.println(bigInteger1);
		//subtract
		bigInteger1 = bigInteger1.subtract(bigInteger2);
		System.out.println(bigInteger1);
		//multiplay
		bigInteger1 = bigInteger1.multiply(bigInteger2);
		System.out.println(bigInteger1);
		//divide
		bigInteger1 = bigInteger1.divide(bigInteger2);
		System.out.println(bigIntger1);
	}
}

2、基本数据类型默认值

若类的某个成员是基本类型,即使没有进行初始化,Java也会确保它获得一个默认值 。

 

基本类型 默认值
boolean false
char ‘/u0000’
byte 0
short 0
int 0
long 0L
float 0.0L
doubl 0.0d

3、数组

Java声明数组时不能指定其长度。

int a[5]//非法
//一维数组声明方式
type var[]或type[] var;
//动态 初始化
MyType data[] = new MyType[3];
data[0] = new MyType(1,2);
data[1] = new MyType(3,4);
//静态初始化
MyType data[]={
   new MyType(1,2),
   new MyType(3,4)
};




相关推荐