java.lang 该包提供了Java编程的基础类,例如 Object类、Thread类、String、Math、System、Runtime、Class、Exception、Process等,是Java的核心类库。

Object类在java.lang包下,是所有类的根。任何类的对象,都可以调用Object类中的方法,包括数组对象。

定义Java类时如果没有显示的指明父类,那么就默认继承了 Object 类。例如:

public class Demo{ 
 } 
 实际上是下面代码的简写形式: 
 public class Demo extends Object{ 
 }

equals() 方法

public boolean equals(Object obj)


例如:
obj1.equals(obj2);
equals()方法只能比较引用类型,“==”可以比较引用类型及基本类型。用“==”进行比较时,符号两边的数据类型必须一致(可自动转换的数据类型除外),否则编译出错,而用 equals 方法比较的两个数据只要都是引用类型即可。

hashCode() 方法

在java中,有一个这样的规定,就是两个相同的对象(即equals运算为true),它们的hash code也必须相同。在Object类中有一个hashCode方法,可以调用它来查看对象的hash code。

package test;
public class Test {
 public static void main(String args[]){
  String str1 = "aaa";
  String str2 = str1;
  String str3 = "bbb";
  System.out.println(str1.equals(str2));
  System.out.println("str1.hashCode():"+str1.hashCode());
  System.out.println("str2.hashCode():"+str2.hashCode());
  System.out.println("str3.hashCode():"+str3.hashCode());
 }
}

输出

true 
 str1.hashCode():96321 
 str2.hashCode():96321 
 str3.hashCode():97314

toString() 方法

toString() 方法是 Object 类中定义的另一个重要方法,是对象的字符串表现形式,语法为:
public String toString()
返回值是 String 类型,用于描述当前对象的有关信息。Object 类中实现的 toString() 方法是返回当前对象的类型和内存地址信息,但在一些子类(如 String、Date 等)中进行了 重写,也可以根据需要在用户自定义类型中重写 toString() 方法,以返回更适用的信息。

clone()方法

clone方法是用来复制一个对象。不同于“=”。
对于值类型的数据是可以通过“=”来实现复制的。但是对于引用类型的对象,“=”只能复制其内存地址,使对象的引用指向同一个对象,而不会创建新的对象。clone则可以创建与原来对象相同的对象。如:
有一个Car类

Car c1 = new Car(); 
 Car c2 = c1;

这两句事实上只创建了一个对象。只不过c1和c2指向了同一个对象。
如果上面的两句改为:

Car c1 = new Car(); 
 Car c2 = c1.clone();

那么就有了两个对象,而且这两个对象的内容是一样的。(所有的属性值相同)

finalize() 方法

当垃圾回收器决定回收某对象时,就会运行该对象的finalize()方法。

protected void finalize() 
 { 
 super.finalize(); 
 // other finalization code… 
 }

当在一段代码块定义一个变量时,Java在栈中为这个变量分配内存空间,当该变量退出其作用域后,Java会自动释放掉为该变量所分配的内存空间,该内存空间可以立即被另作他用。finalize就是应对那些不是new出来的对象释放内存用的。当java类调用本地方法库,一旦gc准备好释放该java类,将首先调用其finalize()方法,所以你打算用finalize的时候,就能在java对象被回收之前,调用finalize方法释放内存。

wait()方法
让当前线程(持有锁的线程)处于等待(阻塞)的状态,并且释放它持有的锁。该线程将处于阻塞状态,直到其它线程调用notify()或者notifyAll()方法唤醒,线程进入就绪状态。
wait(long)方法
让当前线程(持有锁的线程)处于等待(阻塞)的状态,直到其它线程调用notify()或者notifyAll()方法或者超过指定的时间,线程进入就绪状态。
notify()方法
notify():唤醒持有锁上的其中一个线程。让那个线程从等待状态变成就绪状态。
notify()方法
notifyAll():唤醒持有锁上的所有线程。让线程从等待状态变成就绪状态。

public class ThreadDemo extends Thread{
Object object = null;
private String name ;
public ThreadDemo(Object object,String name){
    this.object = object;
    this.name = name;
}
public void run()  {
    while(true){
        synchronized(object){
            try {
                Thread.sleep(1000);
                object.notify();//唤醒锁上的一个线程,被唤醒的线程处于就绪状态,等待被处理器调用
                System.out.println(name +"-----run");
                object.wait();//阻塞,释放锁
            }catch (Exception e) {
                e.printStackTrace();
            }
        } 
    }
}
public static void main(String[] args) {
    Object o = new Object();
    ThreadDemo thread1 = new ThreadDemo(o, "thread1");
    ThreadDemo thread2 = new ThreadDemo(o, "thread2");
    thread1.start();
    thread2.start();
    }
}

输出

thread1—–run 
 thread2—–run 
 thread1—–run 
 thread2—–run 
 thread1—–run 
 thread2—–run 
 thread1—–run 
 thread2—–run 
 thread1—–run

String 类
String类是final的,不可被继承。public final class String。
String类是的本质是字符数组char[], 并且其值不可改变。private final char value[];String类对象有个特殊的创建的方式,就是直接指定比如String x = “abc”,”abc”就表示一个字符串对象。而x是”abc”对象的地址,也叫做”abc”对象的引用。

获取字符串长度。

public int length() { 
 return value.length; 
 } 
 判断是否为空。 
 public boolean isEmpty() { 
 return value.length == 0; 
 } 
 字符串比较 
 public int compareTo(String anotherString) { 
 …… 
 }


Ps:如果两个字符串相等,那么返回0;如果这个String 比参数的String 要小,那么返回 一个负数;如果这个String 比参数的String 要大,那么返回一个整数。

比较字符串是否相等(忽略大小写)

public boolean equalsIgnoreCase(String anotherString) { 
 return (this == anotherString) ? true 
 : (anotherString != null) 
 && (anotherString.value.length == value.length) 
 && regionMatches(true, 0, anotherString, 0, value.length); 
 }

判断字符串是否以固定的字符串固定的位置开始
if(a.startsWith(b)) //判断字符串a 是不是以字符串b开头。
判断是否以固定字符串结尾
例如:if(a.endsWith(b)) //判断字符串a 是不是以字符串b结尾

返回特定字符串第一次出现的位置

public int indexOf(String str) { 
 return indexOf(str, 0); 
 }

返回特定字符串最后一次出现的位置

public int lastIndexOf(String str) { 
 return lastIndexOf(str, value.length); 
 }

连接(把参数字符串连接到调用者字符串下)

public String concat(String str) { 
 int otherLen = str.length(); 
 if (otherLen == 0) { 
 return this; 
 } 
 int len = value.length; 
 char buf[] = Arrays.copyOf(value, len + otherLen); 
 str.getChars(buf, len); 
 return new String(buf, true); 
 }

替换

“mesquite in your cellar”.replace(‘e’, ‘o’) 
 returns “mosquito in your collar” 
 “the war of baronets”.replace(‘r’, ‘y’) 
 returns “the way of bayonets” 
 “sparring with a purple porpoise”.replace(‘p’, ‘t’) 
 returns “starring with a turtle tortoise” 
 “JonL”.replace(‘q’, ‘x’) returns “JonL” (no change)

截取 index1 到 index2 固定的字符串

public substring(int beginIndex, int endIndex)
“hamburger”.substring(4, 8) returns “urge” 
 “smiles”.substring(1, 5) returns “mile”

分割函数 public String[] split(String regex)
例如,字符串”boo:and:foo”使用以下表达式得到以下结果:

Regex Result 
 : { “boo”, “and”, “foo” } 
 o { “b”, “”, “:and:f” }

trim()的作用:去掉字符串首尾的空格。

public static void main(String arg[]){ 
 String a=” hello world “; 
 String b=”hello world”; 
 System.out.println(b.equals(a)); 
 a=a.trim(); 
 //去掉字符串首尾的空格 
 System.out.println(a.equals(b)); 
 }


执行结果:

a: hello world ,false 
 a:hello world,truetoCharArray()


将字符串对象中的字符转换为一个字符数组
例如:

String myString=”abcd”; 
 char myChar[]=myString.toCharArray(); 
 System.out.println(“myChar[1]=”+myChar[1]);


输出:

myChar[1]=b

class类

getClass 方法

String string=new String(); 
 //使用已经存在的对象的getClass()方法获取Class对象 
 Class class1=string.getClass();

forName(String className)
如果我们有一个类的完整路径,就可以使用 Class.forName(“类完整的路径”) 来得到相应的 Class,这个方法只能用于引用类型,所谓类的完整路径是:包名.类名 例如:java.lang.String。
Class

public static void main(String[] args) {

        int[] arr1 ={5,6,7,0,6,6,1,2,3};

        int[] arr2 ={12,14,67};

        //数组拷贝

        //第一个参数:要拷贝数组

        //第二个参数:要拷贝数组的起始索引

        //第三个参数:目标数组

        //第四个参数:目标数组的索引起始位置

        //第五个参数:要拷贝的长度

        //把原来的位置的参数替换

        System.arraycopy(arr2, 1 , arr1, 3 , 2);

         for (inti = 0; i < arr1.length; i++) {

        System.out.print(arr1[i]+ ",");

      }

        System.out.println();

输出 5,6,7,14,67,6,1,2,3

System.currentTimeMillis()

long tm = System.currentTimeMillis(); 
 System.out.println(“从1970年到现在的毫秒数:” + tm);


输出
从1970年到现在的毫秒数:1521189519381

System.gc()
调用垃圾回收器,注意,这里的调用不是实时生效的,因为它相当于通知了JVM要调用GC回收器去加回收空间,但GC的什么时间去执行,则由JVM来分配。

System.exit(1):
终止JAVA虚拟机的运行,文档说明:“终止当前正在运行的java虚拟机启动的顺序关闭。这种方法通常不返回。该参数作为状态代码;按惯例,一个非零状态码表示异常终止。”

System.getProperties()
获取系统属性,包括系统版本、JDK版本等
示例代码如下:

public static void main(String[] args) { 
 System.out.println(System.getProperties()); 
 }


System.getProperty(key)
根据参数返回系统属性。
示例如下:

public static void main(String[] args) { 
 System.out.println(System.getProperty(“os.name”)); 
 }


运行结果如下 :
Windows 7

Runtime类
Runtime类封装了运行时的环境。每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。一般不能实例化一个Runtime对象,应用程序也不能创建自己的 Runtime 类实例,但可以通过 getRuntime 方法获取当前Runtime运行时对象的引用。一旦得到了一个当前的Runtime对象的引用,就可以调用Runtime对象的方法去控制Java虚拟机的状态和行为。

ecec()方法
返回一个Process对象,可以使用这个对象控制Java程序与新运行的进程进行交互。

下面的例子是使用ecec()方法启动windows的记事本notepad。

class ExecDemo { 
 public static void main(String args[]){ 
 Runtime r = Runtime.getRuntime(); 
 Process p = null; 
 try{ 
 p = r.exec(“notepad”); 
 } catch (Exception e) { 
 System.out.println(“Error executing notepad.”); 
 } 
 } 
 }


totalMemory() freeMemory()
Java提供了无用单元自动收集机制。通过totalMemory()和freeMemory()方法可以知道对象的堆内存有多大,还剩多少。
Java会周期性的回收垃圾对象(未使用的对象),以便释放内存空间。但是如果想先于收集器的下一次指定周期来收集废弃的对象,可以通过调用gc()方法来根据需要运行无用单元收集器。一个很好的试验方法是先调用gc()方法,然后调用freeMemory()方法来查看基本的内存使用情况,接着执行代码,然后再次调用freeMemory()方法看看分配了多少内存。

class MemoryDemo{ 
 public static void main(String args[]){ 
 Runtime r = Runtime.getRuntime(); 
 long mem1,mem2; 
 Integer someints[] = new Integer[1000]; 
 System.out.println(“Total memory is :” + r.totalMemory()); 
 mem1 = r.freeMemory(); 
 System.out.println(“Initial free is : ” + mem1); 
 r.gc(); 
 mem1 = r.freeMemory(); 
 System.out.println(“Free memory after garbage collection : ” + mem1); 
 //allocate integers 
 for(int i=0; i<1000; i++) someints[i] = new Integer(i); 
 mem2 = r.freeMemory(); 
 System.out.println(“Free memory after allocation : ” + mem2); 
 System.out.println(“Memory used by allocation : ” +(mem1-mem2)); 
 //discard Intergers 
 for(int i=0; i<1000; i++) someints[i] = null; 
 r.gc(); //request garbage collection 
 mem2 = r.freeMemory(); 
 System.out.println(“Free memory after collecting ” + “discarded integers : ” + mem2); 
 } 
 }

输出

Total memory is :2031616 
 Initial free is : 1818488 
 Free memory after garbage collection : 1888808 
 Free memory after allocation : 1872224 
 Memory used by allocation : 16584 
 Free memory after collecting discarded integers : 1888808

Exception类

Java Exception被分为三类:Error,checked exception和runtime exception。在设计类时,这三种Exception这样使用为佳: 
 Error:用于JVM相关的错误,例如resource deficiences,invariant failures以及其他使JVM无法正常运行的异常。 
 Runtime Exception:用于编程错误,JDK自带的很多就是用于编程错误 
 Checked Exception:用于可以恢复的异常。