一、JAVA的基本特性
1.1 JAVA语言特性
1.简单性:相对于其他如C++编程语言,JAVA不支持多继承,屏蔽了指针的概念。JAVA底层为C++。
2.面向对象:JAVA是纯面向对象的。
3.可移植性:JAVA可以实现跨平台,一次编译,可以到处运行,基于JVM实现。
4.多线程:JAVA程序支持多线程。
5.健壮性:JAVA的JVM带有垃圾回收机制(GC),JAVA程序内存垃圾自动回收。
6.安全性
二、JAVA基础语法
2.1 标识符
1.标识符由数字、字母、下划线、$组成;
2.JAVA区分大小写;
3.JAVA关键字不能做标识符;
4.标识符不能以数字开头。
2.2 字面值
1.常量
2.整数:int、byte、short、long
3.布尔:boolean
4.字符和字符串:char
2.3 作用域
主要是区分成员变量与局部变量的作用域
1.作用域为{}以内的局部变量
//这段代码中,当for结束时,变量j就被释放了。
for(int j = 0; j < 10 ; j++){
System.out.println("j");
}
//这段代码中,当for结束时,变量j为10,也就是说j的作用域在for之外,但j为局部变量,作用域在主方法的{}之内
int j;
for(j = 0; j < 10 ; j++){
System.out.println("j");
}
2.4 类型转换
2.4.1 混合计算计算,类型转换:byte < short < int < long < float < double ,其中char与short相等,但当char和short同时存在,则转换为char
2.4.2 强制类型转换: ( int ) a
int a = 10;
System.out.println((double)a);
2.5 基本运算符与三元运算符
2.5.1 基本运算符
+ | - | * | / | % | ++ | — — |
---|---|---|---|---|---|---|
> | < | >= | <= | == | != | |
|或 | &与 | !非 | ^异或 | ||短路或 | &&短路与 |
2.5.2 三元运算符
布尔表达式 ? 表达式1 : 表达式2;
int x = 1;
int y = 2;
int a = x > y ? x : y;
//如果x > y布尔表达式为true,则a = x,否则a = y
2.6 if判断语句
注意else{}样式的格式,一定会运行JAVA代码。
//if语句的四种格式用法
//第一种
if(true){}
//第二种
if(true){}
else {}
//第三种
if(true){} else if(true){}
//第四种
if(true) else if(true){} else{}
2.7 switch分支语句
2.8 for、while 、do while、foreach循环语句
// for
for(int i = 0 ;i < 100 ;i++){
System.out.println(i);
}
// while
while(i < 100){
System.out.println(i);
i++;
}
// do while
do{
System.out.println(i);
i++;
}
while(i<100); // 注意!!!!!!!!do while 中,while结束时要带分号 ;
// 增强for循环,foreach,优点是简洁,缺点是没有下标
int [] arr = {1,2,3,4,5,6};
for(int data : arr){
System.out.println(data);
}
2.9 break与continue
//break直接终止for循环
for(int i = 0 ;i < 100 ;i++){
System.out.println(i);
if(i == 50){
break;
}
}
//continue跳过此次循环,直接进入下一次循环
for(int i = 0 ;i < 100 ;i++){
System.out.println(i);
if(i == 50){
continue;
}
}
2.10 方法的定义与方法内存
//方法的定义为:修饰符列表 + 返回值类型 + 方法名 + 方法体
public static //这是修饰符列表
void //这是返回值类型
Show //这是方法名
//这是方法体
{
System.out.println("黑鸭黑鸭拔萝卜!");
}
//定义方法
public static void Show(){
System.out.println("黑鸭黑鸭拔萝卜!");
}
2.11 方法重载
方法重载,重载的方法,只有参数列表不同!
//例如,这里有一个方法Sum(a , b),作用是求整数a与b的和
public static void Sum(int a, int b){
a+b;
}
//现在需要改进,希望可以计算double,甚至String类型的参数加法,但希望只修改Sum方法的参数,则可以重载
public static void Sum(double c, double d){
c+d
}
2.12 方法递归
递归重在思想,需要理解栈区的程序运行原理
//利用递归求和1~4
public class test
{
public static int Sum(int n)
{
if(n == 1) return n;
else{
n = Sum(n-1)+n;
}
return n;
}
public static void main(String args[])
{
int n = 4;
int b = 0;
b = Sum(n);
System.out.println(b);
}
}