那些你可能不熟悉的Java基础知识之数据类型

目录

●数据类型

●布尔型敲黑板!!!

●字符串类型

●拼接

●转义字符

●变量与常量

●变量

●变量的命名规则

●变量的作用域

●常量

●类型转换

一.数据类型

1.数据类型的分类

2.数据类型的大小

由此可见各个类型所占的字节数

3.布尔型

●在java中只有两种取值:true为真,false为假(注意!不是1和0)

●在JVM的规范中:并没有直接规定布尔类型的大小,有些书会说是1bit


由此可见,不同的类型不能够直接进行运算

 4.字符串类型(C语言中是没有的)

" "引起若干字符串;在Java中可直接赋值给某个变量

//java中可直接赋值给某个变量的示范
String str="hello";
System.out.println(str);
//输出结果
hello

 二、拼接

●拼接符号:+

可以用于不同类型之间的拼接(各种细节如下图)

public class TestDemo {
    public static void main(String[] args) {
        //将两个字符串拼接
        System.out.println("hello" + "world");//helloworld
        //其它类型和字符串进行拼接
        
        //①字符串hello先和10拼接成新的字符串hello10后;再与20拼接
        System.out.println("hello" + 10 + 20);//hello1020
        //②先是同种类型进行拼接加为30后;再与hello拼接
        System.out.println(10 + 20 + "hello");//30hello
        //③与①不同在于相当于先强制拼接后者后的结果;再与hello拼接
        System.out.println("hello" + (10 + 20));//hello30
        //④相当于用空字符串隔开同种类型的直接拼接
        System.out.println(10 + "" + 20 + "hello");//1020hello
        //a=10;b=20的输出
        System.out.println("a=" + 10 + ",b=" + 20);//a=10,b=20
    }
}

三、转义字符(需注意某些特殊的问题)

public class TestDemo {
    public static void main(String[] args) {
String s1="bit";           //           bit
String s2="\"bit\"";       //      "bit"
String s3="\\bit\\";       //      \bit\
String s4="\\\\bit\\\\";   //   \\bit\\
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
    }
}

四、变量与常量

1.变量(!!!在java中没有全局变量的说法)

①变量的命名规则

● 一个变量只能包含字母,数字,下划线,美元符号;且不能以数字开头

●成员变量,局部变量均采用小驼峰(eg.大驼峰:OnePrint;小驼峰:onePrint)

●变量名大小写的含义是不同的

②变量的作用域

即作用范围,通常用{}来对范围进行划定;

2.常量

在程序编译时就已经确定其值,在程序运行过程中是不可更改的

①字面值常量

A=88;

②final修饰的变量(成为常量)

final int A=10;

五、类型转换


原则:小字节赋给大字节OK,大字节赋给小字节要强制类型转换,是有风险

①小字节赋给大字节

public class TestDemo {
    public static void main(String[] args) {
        int a=10;
        long b=a;
        System.out.println(b);
    }
}
//输出结果:10

②大字节赋给小字节

public class TestDemo {
    public static void main(String[] args) {
        long l=10;
        int c=l;
        System.out.println(c);
    }
}

报错如右:

强制类型转换后:

public class TestDemo {
    public static void main(String[] args) {
        long l=10;
        int c=(int)l;//强制类型转换
        System.out.println(c);
    }
}

输出结果:10


!!!各类型是不能与布尔类型相互转换的,以int为例

public class TestDemo {
    public static void main(String[] args) {
    int a=10;
    boolean b=true;
    b=(boolean) a;
    }
}
//编译报错,出现不兼容类型

③int和String之间的相互转换

1.将整数转换为字符串

public class TestDemo {
    public static void main(String[] args) {
        int num=10;
//将某类型转换为字符串类型
//需要的结构String.valueof();
        String ret=String.valueOf(num);
        System.out.println(ret);
    }

}

2.将字符串转换成整数

public class TestDemo {
    public static void main(String[] args) {
        String str="123";
        int i=Integer.valueOf(str);
        System.out.println(i+1);
    }

}
//输出结果:124

猜你喜欢

转载自blog.csdn.net/weixin_58850105/article/details/121008534