21xrx.com
2024-09-19 10:14:53 Thursday
登录
文章检索 我的文章 写文章
Java基础:介绍Java的基本数据类型
2023-06-13 03:09:22 深夜i     --     --
Java 基础数据类型 编程

Java是一种面向对象的编程语言,它支持8种基本数据类型,分为两类:数值型和非数值型。接下来让我们一起来学习一下这些基本数据类型以及它们的使用。

数值类型:

1. byte

占用1个字节,取值范围为-128到127。

2. short

占用2个字节,取值范围为-32,768到32,767。

3. int

占用4个字节,取值范围为-2,147,483,648到2,147,483,647。

4. long

占用8个字节,取值范围为-9,223,372,036,854,775,808到9,223,372,036,854,775,807。

5. float

占用4个字节,取值范围为3.4e-038到3.4e+038。

6. double

占用8个字节,取值范围为1.7e-308到1.7e+308。

非数值类型:

1. char

占用2个字节,表示一个Unicode字符,取值范围为'\u0000'到'\uffff'。

2. boolean

占用1个字节,表示逻辑值,只能取值true或false。

下面是基本数据类型的示例代码:


public class BasicDataType {

  public static void main(String[] args) {

   byte b = 100;

   short s = 10000;

   int i = 1000000;

   long l = 1000000000L;

   float f = 3.1415f;

   double d = 3.1415926;

   char c = 'A';

   boolean bool = true;

   System.out.println("byte b = " + b);

   System.out.println("short s = " + s);

   System.out.println("int i = " + i);

   System.out.println("long l = " + l);

   System.out.println("float f = " + f);

   System.out.println("double d = " + d);

   System.out.println("char c = " + c);

   System.out.println("boolean bool = " + bool);

  }

}

这个程序将会输出以下结果:


byte b = 100

short s = 10000

int i = 1000000

long l = 1000000000

float f = 3.1415

double d = 3.1415926

char c = A

boolean bool = true

从上面的代码可以看出,对于取值范围较小的变量,我们可以使用占用空间较小的数据类型来定义,这样可以减小内存占用。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复