牛客网基础题-有容乃大
确定不同数据类型在内存中占多少字节 思路:
- Java的基本数据类型有8种,分别是:boolean,char,byte,short,int,long,float,double.java是一个面向对象的语言,它的操作一般都是基于对象,因此为了使用方便将它们当成对象来操作,为每种类型均引入了其对应的包装类型。其中,包装类型属于java.lang.*;
| 基本数据类型 | 包装类型 | 所占空间大小(字节数) |
|---|---|---|
| boolean | Boolean | - |
| char | Character | 2 |
| byte | Byte | 1 |
| short | Short | 2 |
| int | Integer | 4 |
| long | Long | 8 |
| float | Float | 4 |
| double | Double | 8 |
- 这些包装类型封装了一些常用的方法和属性。本题便要使用它们的SIZE属性。使用SIZE可以计算出实际所占空间大小 代码如下:
public class Main {
public static void main(String[] args){
System.out.println("The size of short is "+Short.SIZE/Byte.SIZE+" bytes.");
System.out.println("The size of int is "+ Integer.SIZE/Byte.SIZE+" bytes.");
System.out.println("The size of long is "+Long.SIZE/Byte.SIZE+" bytes.");
System.out.println("The size of long long is "+Long.SIZE/Byte.SIZE+" bytes.");
}
}
运行结果:
The size of short is 2 bytes.
The size of int is 4 bytes.
The size of long is 8 bytes.
The size of long long is 8 bytes.