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

来源:互联网 发布:淘宝网的二手市场在哪 编辑:程序博客网 时间:2024/06/06 00:28

一、基本数据类型的转换

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;}}



原创粉丝点击