你好,世界!
源代码组织方式
Java程序由package+class组成,package对应目录的相对路径,class对应文件,如
E:\Workspaces\MyEclipse 10\JavaStudy\src\com\happyframework\javastudy\hello\Hello.java
1 package com.happyframework.javastudy.hello; 2 3 public final class Hello { 4 public static void hello(){ 5 System.out.println("hello!"); 6 } 7 }
关于class有如下几点规则:
- 文件的名字必须和class的名字一致(public级别的class名字)。
- 文件必须只包含一个public访问基本的class(可以包含多个非public级别的class)。
- package名字必须和目录一致。
入口方法
App.java
1 public class App { 2 public static void main(String[] args) { 3 com.happyframework.javastudy.hello.Hello.hello(); 4 } 5 }
最终的项目结构
数据类型
8种原子类型
- 整数类型:byte、short、int和long。
- 小数类型:float和double。
- 字符类型:char。
- 布尔类型:bool。
除此之外的是interface、class和array。
小数类型的常量默认是double类型,声明float类型的常量需要使用F作为后缀。
1 public class Program { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 float age = 28.0F; 8 System.out.println(age); 9 } 10 11 }
运算符
- 算术运算符:+、-、*、/ 和 %,两个整数相除,结果还是整数。
- 赋值运算符:=、+=、-=、*=、/=、%=、&=、|=、~=、^=、<<=、>>= 、 >>>=、++ 和 --。
- 比较运算符:==、!=、<、<=、> 和 >=。
- 逻辑运算符:&&、|| 和 !。
- 位运算符:&、|、~、^、<<、>> 和 >>>。
字符串
String是拥有“值语义”的引用类型,字符串常量实现了“享元模式”,equals会按照内容进行比较,==按照地址比较。
1 public class Program { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 String x = "段光伟"; 8 String y = new String("段光伟"); 9 10 System.out.println(x.equals(y)); // true 11 System.out.println(x == y); // false 12 } 13 14 }
为了高效的修改字符串Java引入了StringBuffer。
1 { 2 StringBuffer sb = 3 new StringBuffer() 4 .append("段") 5 .append("光") 6 .append("伟"); 7 8 System.out.println(sb.toString()); 9 }
数组
声明语法
DataType[] name 或 DataType name[]。
初始化语法
DataType[] name = new DataType[length]。
DataType[] name = new DataType[] { element1, element2, ...elementn }。
DataType[] name = { element1, element2, ...elementn }。
1 public class Program { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 { 8 String[] strs = { "段", "光", "伟" }; 9 10 for (String item : strs) { 11 System.out.print(item); 12 } 13 } 14 } 15 16 }
多维数组
只有不等长多维数组DataType[][],没有DataType[xxx, xxx]。
控制结构
- 条件:if-else if-else、switch-case-default和三元运算符(?:)。
- 循环:while、do-while、for和foreach。
- Labeled block。
1 public class Program { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 task: { 8 int age = 25; 9 10 System.out.println("start"); 11 12 if (age < 30) { 13 break task; 14 } 15 16 System.out.println("end"); 17 } 18 } 19 }
最近觉得label是个不错的东西,最起码多了一种选择。
方法
Java中所有的赋值和方法调用都是“按值“处理的,引用类型的值是对象的地址,原始类型的值是其自身。
Java支持变长方法参数。
1 public class Program { 2 3