20160724------JAVA基本语法[标识符、数据类型、

2017-03-14  本文已影响0人  shallwego_

二、 基础语法
第一段程序:

public class HelloWorld{
    public static void main(String[] args){
        System.out.println(“Hello World!”);
    }
}

1、标识符:

2、数据类型

(1)基本数据类型:四类八种

(2)数据类型排序:

(3)类型转换:

//TestConvert
public class TestConvert {
    public static void main(String arg[]) {
        int i1 = 123; 
        int i2 = 456;
        double d1 = (i1+i2)*1.2;//系统将转换为double型运算
        float f1 = (float)((i1+i2)*1.2);//需要加强制转换符
        byte b1 = 67; 
        byte b2 = 89;
        byte b3 = (byte)(b1+b2);//系统将转换为int型运算,需
                                //要强制转换符
        System.out.println(b3);
        double d2 = 1e200;
        float f2 = (float)d2;//会产生溢出
        System.out.println(f2);

        float f3 = 1.23f;//必须加f
        long l1 = 123;
        long l2 = 30000000000L;//必须加l
        float f = l1+l2+f3;//系统将转换为float型计算
        long l = (long)f;//强制转换会舍去小数部分(不是四舍五入)

    }
}

修正下列代码中的编译错误或者可能产生的溢出:

//TestConvert2
public class TestConvert2 {
    public static void main(String[] args) {
   
    int i=1,j=12;
    float f1=(float)0.1;  //0.1f  0.1是double类型,需要强制类型转换
    float f2=123;
    long l1 = 12345678,l2=8888888888L;//l2必须加L,否则会产生溢出
    double d1 = 2e20,d2=124;
    byte b1 = 1,b2 = 2,b3 = 127;//byte类型的范围是(-128~127)
    j = j+10;//变量必须赋值才能使用
    i = i/10;
    i = (int)(i*0.1);//运算后为double类型,需要强制类型转换
    char c1='a',c2=125;
    byte b = (byte)(b1-b2);//运算后为int类型,需要强制类型转换
    char c = (char)(c1+c2-1);////运算后为int类型,需要强制类型转换
    float f3 = f1+f2;
    float f4 = (float)(f1+f2*0.1);//运算后为double类型,需要强制类型转换
    double d = d1*i+j;
    float f = (float)(d1*5+d2);


    }
}

3、常量、变量

(1)常量:

常量是在程序运行中,值不能改变的量。用final定义。
语法:final<数据类型><常量名>=<初始值>

整型常量:123
实型常量:3.14
字符常量:'a'
字符串常量:"helloworld"
逻辑常量:true、false

(2)变量:

从本质上讲,变量其实是内存中的一小块区域,使用变量名来访问这块区域。因此,没一个变量使用前必须要先声明,然后进行赋值,才能使用。

4、内存分析(←点击看视频讲解)

内存分为堆、栈、方法区。

//内存分析
public class Test{
    public static void main(String [] args){
    Car c1=new Car();
    c1.changeColor("红色");
    c1.showColor();
    System.out.println(Car.typeNum);
    System.out.println(c1.typeNum);

    Car c2=new Cae();
    Engine e=new Engine();
    e.speed=1000;
    e.weight=e;
    c2.engine=e;
    c2.color="黑色";

    c2.typeNum=10;
    System.out.println(c1.typeNum);
    }
}

class Car{
    static int typeNum=4;
    Engine enging;
    String color;

    void changeColor(String c){
        color=c;
    }

    void showColor(){
        System.out.println("我的颜色是:"+color);
    }
}

class Engine{
    int speed;
    int weight;
}

内存分析图:


-------static变量和方法内存分析---------

-------this关键字------

构造方法中,this是隐式参数,this.name指向括号中的name对象:



this不能用于static方法,因为static方法不指向对象。

上一篇 下一篇

猜你喜欢

热点阅读