Point02(java--基础数据类型)

49 阅读1分钟

java是面向对象语言,但是并非所有类型都是对象。它建立在称为基元的基础数据类型之上。

java基础数据类型包括:

数字类型:

byte (数字,1字节);

short(数字 ,2字节);

int (数字,4字节);

long (数字,8字节);

float (浮点型,4字节);

double (浮点型,8字节);

char (字符型,2字节);

string (字符串);

boolean (布尔型,1字节);

public class Variable {
    public static void main(String[] args){
        int myIntNumber  = 1234567890;
        System.out.println("int:"+myIntNumber);
        long myLong = 1234567890;
        System.out.println("long:"+myLong);
        double myDoubleNumber = 1.2;
        System.out.println("double:"+myDoubleNumber);
        float myFloatNumber = 1.2f;
        System.out.println("float:"+myFloatNumber);
        byte myByte = 1;
        System.out.println("byte:"+myByte);
        short myShort = 12345;
        System.out.println("short:"+myShort);
        char myChar = '你';
        System.out.println("char:"+myChar);
        String myString = "qwhrjwerhjwthrejkgbjkbg";
        System.out.println("String:" + myString);
        boolean isMy = true;
        System.out.println("boolean:"+isMy);
    }
}

特别注意,每种基础数据类型长度大小限制;

注意:如果你想使用 float,你将不得不强制转换:

float numberFloat = (float) 1.2;
System.out.println("numberFloat:" + numberFloat);

或者使用下面方法:

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

他们实现的效果是相同的。

另外String类型的数据也可以通过以下方法进行申明:

String myString = new String("this is string");
System.out.println("myString"+myString);
练习题:

创建具有不同值的所有基元 (long 和 double 除外)。将它们连接成一个字符串并将其打印到屏幕上,以便打印: H3110 w0r1d 2.0 真

String testString = "H";
int testInt  = 3110;
char testChar1 = 'w';
char testChar2 = 'r';
char testChar3 = 'd';
short testShort = 0;
float testFloat = 2.0f;
byte testByte = 1;
boolean testBoolean = true;
//拼接
String word = new String(testString+testInt+" "+testChar1+testShort+testChar2+testByte+testChar3+" "+testFloat+" "+(testBoolean?"真":"假"));
//打印
System.out.println(word);