java基础篇(二)——数据转换和内存分配

一、基本数据类型的转换

byte->short,char -> int -> long      
float -> double
int -> float
long -> double
记住小可转大,大转小会失去精度!!!

例1:

	int i = 4;
	short s = 4;
	short s2 = (short)40000;

	//s = i;
	s = (short)(s + 1);  
	s = (short)(s + s2);
java在计算时会把数据类型自动转换为int,然后计算。所以左值是int,赋值给short,故会造成

精度丢失,编译不通过,需要强转。

例2:

	int   a = 3;
	float f = (float)3.14;
	float f2 = 3.14f;
java中默认的整数类型是int类型,如果要定义为float型,则要在数值后加上l或L;
默认的浮点型也是双精度浮点,如果要定义为float型,则要在数值后加上f或F。

二、引用数据类型的内存分配

	/* Java has no pointer */
	//int* p = malloc(10*sizeof(int));
	int p[] = new int[10];
	int p2[] = {1,2,4}; /* static alloc */
		
	//char str[100];
	char str[] = new char[100];

	//char str2[] = "abc";
	String str2 = "abc";

在栈中可以直接分配内存的数据是基本数据类型。  
引用数据类型:是数据的引用在栈中,但是他的对象在堆中。  

以 int p[] = new int[10];为例



p在栈中栈四个字节,指向堆中分配的内存的首地址。只要是引用数据类型都是这样。但是在C语言中除了用malloc分配的内存在堆中,其他的都是在栈中分配的内存。

java中用new分配的内存不需要释放它,只需要赋值为null即可。当堆中的内存没有被指向是,虚拟机的垃圾回收机制会自动

回收。


三、此程序的源代码

public class Var {
	public static void main(String args[]) {
		int   a = 3;
		float f = (float)3.14;
		float f2 = 3.14f;

		int i = 4;
		short s = 4;
		short s2 = (short)40000;

		//s = i;
		s = (short)(s + 1);  
		s = (short)(s + s2);

		/* Java has no pointer */
		//int* p = malloc(10*sizeof(int));
		int p[] = new int[10];
		int p2[] = {1,2,4}; /* static alloc */
		
		//char str[100];
		char str[] = new char[100];

		//char str2[] = "abc";

		String str2 = "abc";

		p = null;
		p2 = null;
		str = null;
		str2 = null;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值