1. 引用import
import java.io.*;
2. 类的静态变量
- 静态变量通过类访问
- 当静态变量被作为public static final 声明时,则为常量
- 静态方法中不允许出现非静态变量
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
}
}
3. 运算符
除了常规的算数、关系、位运算、逻辑、赋值、条件运算符外,还有:
- Instanceof
- 用法: instance1 Instanceof Class1。可以理解为instance1 (is a)Instanceof Class1。
- 这种操作符只用于对象引用变量,不用于基础数据类型。
- 这种操作符检查对象是否是独特类型(类型或接口类型),左边操作元显式声明的类型与右边操作元必须是同种类或有继承关系,即位于继承树的同一个分支上,否则会编译出错。
- null用操作符instanceof测试任何类型时都是返回false
interface A{}
class B implements A{
}
class C extends B {
}
class instanceoftest {
public static void main(String[] args){
A a=null;
B b=null;
boolean res;
System.out.println("instanceoftest test case 1: ------------------");
res = a instanceof A;
System.out.println("a instanceof A: " + res);
res = b instanceof B;
System.out.println("b instanceof B: " + res);
System.out.println("/ninstanceoftest test case 2: ------------------");
a=new B();
b=new B();
res = a instanceof A;
System.out.println("a instanceof A: " + res);
res = a instanceof B;
System.out.println("a instanceof B: " + res);
res = b instanceof A;
System.out.println("b instanceof A: " + res);
res = b instanceof B;
System.out.println("b instanceof B: " + res);
System.out.println("/ninstanceoftest test case 3: ------------------");
B b2=(C)new C();
res = b2 instanceof A;
System.out.println("b2 instanceof A: " + res);
res = b2 instanceof B;
System.out.println("b2 instanceof B: " + res);
res = b2 instanceof C;
System.out.println("b2 instanceof C: " + res);
}
}
/*
result:
instanceoftest test case 1: ------------------
a instanceof A: false
b instanceof B: false
instanceoftest test case 2: ------------------
a instanceof A: true
a instanceof B: true
b instanceof A: true
b instanceof B: true
instanceoftest test case 3: ------------------
b2 instanceof A: true
b2 instanceof B: true
b2 instanceof C: true
*/
- 待补充…
4. 实现与继承
interface A{}
class B implements A{
}
class C extends B {
}
5. for循环在Java 中新特性
传统的while, do…while, for循环的用法就不多说了。截至Java5,对增强的for循环进行了介绍。这主要是用于数组。
public class Test {
public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
6. switch用法
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
7. 数字
- 通常情况下,当我们处理数字时,使用原始数据类型,如 byte,int,long,double 等。
- 然而,在开发中,我们会遇到需要使用对象而不是原始数据类型的情况。为了实现这个, Java 为每个原始数据类型提供包装类。 如Integer, Long, Byte, Double, Float, Short。
- 所有的包装类都继承于抽象类Number。
- Number 是 java.lang 包的一部分。
- 当一个原始数据类型被使用,当需要一个对象时,编译器将原始数据放入其包装类,此为装箱。同样地,编译器也能将对象取出返回到原始数据类型,此为拆箱。
public class Test{
public static void main(String args[]){
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
System.out.println(x);
}
}
- 以下是对Number 类实现的所有子类中实现的实例方法的常用方法:
- xxxValue() : 这个Number对象的值转换为XXX的数据类型并返回。
- compareTo(): 把这个Number对象与参数做比较。
- equals(): 确定这个数字对象是否等于参数。
- valueOf(): 返回其原型数值,此为类方法。
- toString(): 返回字符串。
- parseInt: 此方法用于获取某个字符串的原始数据类型,此为类方法。
public class Test{
public static void main(String args[]){
//将原始数字类型转换为包装类,装箱
int a1 = 5;
Integer a2 = Integer.valueOf(a);
//将包装类转换为原始数字类型,拆箱
Integer b1 = new Integer(5);
int b2 = b1.intValue();
//将数据类型转换为字符串
Integer c1 = 5;
String c2 = c1.toString();
//将字符串转为数据类型
String d1 = "5";
int d2 = Integer.parseInt(d1);
}
}
8. 字符
- char对应的包装类是Character。
- Character提供了一些重要方法:
- isLetter
- isDigit
- isWhitespace
- isUpperCase
- isLowerCase
- toUpperCase
- toLowerCase
- toString
9. 字符串
- 在 Java 编程语言中,字符串是对象。
- String 类是不可变的,因此,一旦创建了 String 对象那么是不能改变的。如果需要大量修改字符的字符串,那么应该使用 StringBuffer & StringBuilder 类。
- 取字符串长度: str.length();
- 创建格式化字符串: 通过String类的静态format方法进行格式化
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
- 其它一些重要的方法:
- compareTo
- concat
- replace
- replaceAll
- split
- substring
- trim
- valueOf
10. 数组
- dataType[] arrayRefVar = new dataType[arraySize];
- dataType[] arrayRefVar = {value0, value1, …, valuek};
- Arrays类提供了一些静态方法对数组能进行搜索、比较、排序的方法
11. 日期和时间
- Java 在 java.util 包中提供了 Date 类,这个类封装了当前的日期和时间。
- Date date = new Date();
- 使用 SimpleDateFormat对象的format方法格式化日期
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
- 使用 SimpleDateFormat对象的parse方法将字符串转换为Date
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
String input = "1818-11-11";
Date t= ft.parse(input);
System.out.println(t);
}
}
- 使用 System.currentTimeMillis来进行测试执行时间
import java.util.*;
public class DiffDemo {
public static void main(String args[]) {
try {
long start = System.currentTimeMillis( );
System.out.println(new Date( ) + "\n");
Thread.sleep(5*60*10);
System.out.println(new Date( ) + "\n");
long end = System.currentTimeMillis( );
long diff = end - start;
System.out.println("Difference is : " + diff);
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}
12. 正则表达式
可以参考: Java正则表达式用法
java.util.regex 包主要包含了下面的三个类:
Pattern 类:一个 Pattern 对象是正则表达式编译表示。 Pattern 类没有提供公共的构造函数。要创建一个 Pattern 对象,你必须首先调用他的公用静态编译方法来获得 Pattern 对象。这些方法的第一个参数是正则表达式。
Matcher 类:一个 Matcher 对象是用来解释模式和执行与输入字符串相匹配的操作。和 Pattern 类一样 Matcher 类也是没有构造方法的,你需要通过调用 Pattern 对象的 matcher 方法来获得 Matcher 对象。
PatternSyntaxException: 一个 PatternSyntaxException 对象是一个不被检查的异常,来指示正则表达式中的语法错误。
13. Java文件和IO
- 在 Java 中 java.io包中包含了所有的I/O类。
- 流可以被定义为一个序列的数据。输入流用来从一个源中读数据,输出流用来向一个目的地写数据。
- 字节流: FileInputStream 类和 FileOutputStream 类
- 字符流: FileReader和FileWriter。可以理解FileReader/FileWriter是对FileInputStream/FileOutputStream的封装
- File对象
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
14. Java异常处理
- 所有的异常类都是 java.lang.Exception 类的子类型。所有异常类都是 Throwable类的子类。Error 类也是由 Throwable 类产生的的子类。
- 打印Throwable:
try{
...
}
catch(Exception e){
String stackTrace = getStackTrace(e);
}
public String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
t.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
throws和throw
- throw是语句抛出一个异常,如throw new Exception();
- throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常),如public void function() throws Exception{……}
当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理。如:
public static void function() throws NumberFormatException{ String s = "abc"; System.out.println(Double.parseDouble(s)); } public static void main(String[] args) { try { function(); } catch (NumberFormatException e) { System.err.println("非数据类型不能转换。"); //e.printStackTrace(); } }
好的编程习惯:
在写程序时,对可能会出现异常的部分通常要用try{…}catch{…}去捕捉它并对它进行处理;
用try{…}catch{…}捕捉了异常之后一定要对在catch{…}中对其进行处理,那怕是最简单的一句输出语句,或栈输入e.printStackTrace();
如果是捕捉IO输入输出流中的异常,一定要在try{…}catch{…}后加finally{…}把输入输出流关闭;
如果在函数体内用throw抛出了某种异常,最好要在函数名中加throws抛异常声明,然后交给调用它的上层函数进行处理。
声明自己的异常
//声明自己的异常,和普通类一样的设计,不过可以当做Exception来使用
class MyException extends Exception{
}