数据类型
字符串 String
String,表示字符串
例如
public static void main(String[] args) {
String a = "Hello Java!";
System.out.println(a);
}
其中 a 是一个变量,类型为 Sting ,值为 "Hello Java!"
整数 int
int,表示一个整数(Integer)
例如
public static void main(String[] args) {
int a = 10;
int b = 2 ;
int c = a + b;
System.out.println("c的值是:" + c);
}
其中 a 是一个变量,类型为 int ,值为 10
int 的表示范围:-2147483648 ~ 2147483647
小数 double
double,表示一个小数(Double Float-Point 双精度浮点数)
例如
public static void main(String[] args) {
double pi = 3.14 ;
System.out.println("pi的值是:" + pi);
}
double 可以表示的数值范围很大,一般不用担心不够用
布尔 boolean
boolean,布尔类型
用于表示 “是” 或者 “否”,二选一的值
布尔类型的定义:
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a的值是:" + a );
System.out.println("b的值是:" + b);
}
boolean 类型只能取两种值:true / false ,其它形式会报错。
数组
数组,是一种容器,可以容纳固定数量的元素
public static void main(String[] args) {
// 一个长度为 5 的数组,可以容纳 5 个 int 值
int[] a = new int[5];
//创建数组时,同事初始值
int [] numbers = {10, 20, 30, 40, 50};
a[0]=10;
System.out.println(a[0]);
}
数组中的每个元素,可以用下标访问,其中 a[0] 表示数组的第一个元素。
数组元素的初始默认值 0(或者 0.0 / false /null )
命名规则
变量的命名规则
- 由字母、数字、下划线组成
- 不能以数字开头
- 可读性,最好用英文单词命名
类的使用
定义一个学生类
public class Student {
public int id;
public String name;
public boolean sex;
public int phone;
// 统计数组元素的和
public int count(int[] number){
int total = 0;
for(int x:number){
total = total +x;
}
return total;
}
}
实例化对象,并调用这个类
public class Main {
public static void main(String[] args) {
Student lists = new Student();
lists.id = 1801163;
lists.name = "小王";
lists.sex = false;
lists.phone = 110;
System.out.println(lists.id + lists.name);
// 方法参数传递,并带有返回值
int [] number = {10,20,30,40,50};
int total = lists.count(number);
System.out.println(total);
}
}