变量与数据类型

1、变量的命名规则

  • 必须是字母、下划线、$开头

  • 余下的部分可以是字母、下划线、$、数字

  • 不能是Java中的关键字

2、变量的命名规范

  • 首字母必须小写

  • 驼峰命名法

    • userName、classNo

  • 见名知意,不要使用a,b,c 这类意味不明的变量名

  • 有些情况下变量名会和关键字冲突

    如class,可写为clazz

    3、数据类型

    使用场景:
    * 一.声明变量时,语法:
    数据类型  变量名 = 值;
    * 例如:int a = 10;  String str = "aaa";
    * 二.声明方法时,返回值的类型,语法:
    public 数据类型 方法名(){ return 值;}
    * 例如: public int add(){ return 0; }   public String minus(){ return "aaa"; }
    * 三.声明方法时,形参列表的类型,语法:
    public 数据类型 方法名(数据类型 形参1 , 数据类型 形参2){ return 值; }
    * 例如:public int add(double a , int b){ return 10;}  public String add(double a , String b){ return "bbb";}
    *
    * 1.基本数据类型  八大基本数据类型
    * 整型     byte short int long  默认类型int,默认值0
    * 浮点型   float double         默认类型double,默认值0.0
    * 字符型   char                 默认值'\u0000',例如:'a' 'B' '0' '中'
    * 布尔类型 boolean              值true、false,默认值false
    *
    * 2.引用数据类型
    * 除了基本数据类型以外的都是引用数据类型,例如:String类、System类、自定义TypeDemo类、数组int[] a等等
    */
    1、整型
package net.zx.j2se.day02;
​
public class Text01 {
    public static void main(String[] args){
        //整型
        byte a1=1;
        short a2=2;
        int a3=3;
        long a4=123456L;   \\长整型使用时需在结尾加字母L
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);
        System.out.println(a4);
    }
}
2、浮点型
package net.zx.j2se.day02;
​
public class Text02 {
    public static void main(String[] args) {
        //浮点型
        float a1=1.2F;
        double a2=12.24;
    }
}
3、字符型与boolean
package net.zx.j2se.day02;
​
public class Text03 {
    public static void main(String[] args) {
        char a='A';
        boolean b=true;
        boolean c=false;
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
    }
}

4、基本数据类型之间的转换

    一.自动转换
    1.小转大  byte < short < int < long   float < double
    2.整型转浮点型,默认添加.0
    3.字符型转整型,根据ASCII码表直接转换
    二.强制转换  数据类型 a = (数据类型) b;
    1.大转小
    2.浮点型转整型,且直接干掉小数点后
    3.整型转字符型
package net.wanhe.j2se.day02;
​
public class Text04 {
    public static void main(String[] args) {
        //类型转换
        //小转大
        int a1=65;
        float a2=13.01F;
        char a3='王';
        long a4=a1;
        double a5=a2;
        int a6=a3;
        //强制类型转换
        //大转小
        //强制转换可以让代码强制通过编译 但是存在风险(精度丢失)
        byte a7=(byte)a1;
        char a8=(char)a1;
        float a9=(float)a3;
        System.out.println(a3);
        System.out.println(a4);
        System.out.println(a5);
        System.out.println(a6);
        System.out.println(a7);
        System.out.println(a8);
        System.out.println(a9); 
    }
}

  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值