1. 从最简单的class开始
Java 是面向对象的语言,一切皆对象是 Java 的基本思想。
实例:
public class Program {
public static void main(){
System.out.println("Hello Java!");
}
}
这是 Java 程序的基本范式,从最简单的 Hello World,到复杂的 Spring Boot,网络编程的 Netty,都必须要有一个 main 方法作为程序入口
同时,这也是一个最简单的能编译运行的 Java 程序。
本教程的后续部分,都会在这个基本程序下进行。
2. 类型系统
Java 是强类型的语言,所谓强类型,也称为强类型定义语言,代码里面是由的所有变量,都必须明确类型是什么,变量一旦定义了类型,在整个变量的生命周期类型不能更改。
强类型语言的好处:“让错误的程序编译失败”,可以在程序编译期发现很多错误,可以提前处理掉,不需要等到运行期才发现,对提高程序的健壮性有很大好处。这种好处在小规模的程序里不容易体现出来,但是在大规模的程序中,好处是显而易见的。
Java语言定义了一系列基本的数据类型:
实例1:
int num1 = 10;
long num2 = 100000;
String name = "桃花岛主";
char c = 'A';
实例2:
public class Program {
private int num1 = 10;
private long num2 = 100000;
private String name = "桃花岛主";
private char c = 'A';
public static void main(){
System.out.println("Hello Java!");
}
}
3. 条件控制
if-else if-else 是 Java 标准的条件控制语句,和 C、C++、C# 完全一样,非常经典,不多做解释。
实例1:
int score = 90;
if(score < 60) {
System.out.println("bad");
} else if(score >=60 && score <90) {
System.out.println("ok");
} else{
System.out.println("perfect");
}
实例2:
public class Program {
public static void main(){
print();
System.out.println("Hello Java!");
}
public static void print(){
int score = 90;
if(score < 60) {
System.out.println("bad");
} else if(score >=60 && score <90) {
System.out.println("ok");
} else{
System.out.println("perfect");
}
}
}
4. 循环控制
Java 循环有 while 和 for 循环,对集合类型,还有迭代器模式,但是本质上,还是 while 和 for 循环
实例1
// for 循环
int score = 90;
for( int i=0; i<score; i++){
System.out.println(i);
}
// while 循环
int i = 0;
while(true){
System.out.println(i);
i++;
if(i>=score){
break;
}
}
实例2:
public class Program {
public static void main(){
print();
System.out.println("Hello Java!");
}
public static void print(){
// for 循环
int score = 90;
for( int i=0; i<score; i++){
System.out.println(i);
}
// while 循环
int i = 0;
while(true){
System.out.println(i);
i++;
if(i>=score){
break;
}
}
}
}
5. 对象实例化
综合前面的几个基础知识点,封装一个自定义 class 类型Program,并通过 new 实例化一个对象,调用 print 方法,Java 的最基本的入门基本OK了
实例
public class Program {
private int num1 = 10;
private long num2 = 100000;
private String name = "桃花岛主";
private char c = 'A';
public static void main(){
Program instance = new Program();
instance.print();
}
public void print(){
// for 循环
int score = 90;
for( int i=0; i<score; i++){
System.out.println(i);
}
// while 循环
int i = 0;
while(true){
System.out.println(i);
i++;
if(i>=score){
break;
}
}
}
}