1. 程式人生 > >Java基礎案例教程

Java基礎案例教程

靜態程式碼塊


public class Main {
    static {
        System.out.println("測試類的靜態程式碼執行");
    }
    public static void main(String[] args){
        Person p1=new Person();
        Person p2=new Person();
    }
}

class Person{
    static{
        System.out.println("Person類中靜態程式碼塊執行");
    }
}

成員內部類


public class Main {
    public static void main(String[] args) {
        outer.inner in = new outer().new inner();
        in.show();
    }
}

class outer {
    int num = 4;

    class inner {
        void show() {
            System.out.println(num);
        }
    }
}

內部類

public class
Solution { public static void main(String[] args){ //定義一個內部類Cat實現Animal介面 class Cat implements Animal{ public void shout(){ System.out.println("喵喵。。。"); } } animalShout(new Cat());//呼叫方法,並傳入物件 } private static void animalShout
(Animal an) { an.shout();//呼叫傳入物件的方法 } } //定義Animal介面 interface Animal{ void shout();//定義抽象方法 }

匿名內部類

public class Solution {
    public static void main(String[] args){

        //定義匿名內部類作為引數傳給AnimalShout()方法
        animalShout(new Animal() {
            @Override
            public void shout() {
                System.out.println("喵喵。。。");
            }
        });
    }

    private static void animalShout(Animal an) {
        an.shout();//呼叫傳入物件的方法
    }
}

//定義Animal介面
interface Animal{
    void shout();//定義抽象方法
}

String類的初始化


public class Main {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		String str1 = new String();
		String str2 = new String("abcd");
		char[] charArray = new char[] { 'D', 'E', 'F' };
		String str3 = new String(charArray);
		System.out.println("a" + str1 + "b");
		System.out.println(str2);
		System.out.println(str2);
	}

}

統計字串的個數

public class Solution {
    public static void main(String[] args) {
        String str = "nbaernbatnbaynbauinbaopnba";
        String key = "nba";
        int count = getKeyStringCount(str, key);
        System.out.println(count);
    }

    private static int getKeyStringCount(String str, String key) {
        int count = 0;
        //if(!str.contains(key))//不包含key
        if (str.indexOf(key) == -1)
            return count;
        int index = 0;//記錄key出現的位置
        while ((index = str.indexOf(key)) != -1) {
            str = str.substring(index + key.length());
            count++;
        }
        return count;
    }

}

定位字串


public class Main {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		String s = "ababcdedcba";
		System.out.println(s.length());
		System.out.println("first index of 'c':" + s.indexOf('c'));
		System.out.println("last index of 'c':" + s.lastIndexOf('c'));
		System.out.println("first index of \"ab\":" + s.indexOf("ab"));
		System.out.println("last index of \"ab\":" + s.lastIndexOf("ab"));
	}

}

字串的替換和去除空格的操作

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String s = "itcast";
        //字串替換操作
        System.out.println("將it替換為cn.it:" + s.replace("it", "cn.it"));
        //字串去除空格操作
        String str = "     i t c a s t     ";
        System.out.println("去除字串兩端的空格:" + str.trim());
        System.out.println("去除字串所有的空格:" + str.replace(" ", ""));
    }
}

字串判斷操作

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String s1 = "string", s2 = "str", s3 = "string";
        System.out.println("判斷是否以str開頭:" + s1.startsWith("str"));
        System.out.println("判斷是否是以ng結尾:" + s1.endsWith("ng"));
        System.out.println("判斷是否包含字串abc:"+s1.contains("abc"));
        System.out.println("判斷兩個字串是否相等:"+s2.equals(s1));
    }
}

獲取系統全部屬性

import java.util.*;
public class Main {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		//獲取當前系統屬性
		Properties properties=System.getProperties();
		System.out.println(properties);
		
		System.exit(0);//停止執行
		System.exit(1);//非0標識異常退出
		
		//獲取所有系統屬性的key(屬性名),返回SET物件
		Set<String> propertyNames=properties.stringPropertyNames();
		for(String key:propertyNames) {
			//獲取當前鍵key(屬性名)所對應的值(屬性值)
			String value =System.getProperty(key);
			System.out.println(key+"------>"+value);
		}
	}

}

獲取時間和陣列拷貝

import java.util.*;
public class Main {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		long startTime=System.currentTimeMillis();//迴圈開始的當前時間
		int sum=0;
		for(int i=0;i<(int)1e9;i++) {
			sum+=i;
		}
		long endTime=System.currentTimeMillis();
		System.out.println((endTime-startTime)+"毫秒");
		int[] fromArray= {10,20,30};
		int[] toArray=new int[10];
		System.arraycopy(fromArray, 0, toArray, 1, 3);
		System.out.println(Arrays.toString(toArray));
	}
}

虛擬機器執行時的狀態

import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        Runtime rt = Runtime.getRuntime();//獲取虛擬機器執行的狀態
        System.out.println("處理器的個數:" + rt.availableProcessors());
        System.out.println("空閒記憶體大小:" + rt.freeMemory() / 1024 / 1024 + "MB");
        System.out.println("最大可用記憶體數量:" + rt.maxMemory() / 1024 / 1024 + "MB");

        rt.exec("notepad.exe");//命令開啟一個記事本程式

        Process process = rt.exec("notepad.exe");//得到表示程序的Process物件
        Thread.sleep(3000);//程式休眠3秒
        process.destroy();//殺掉程序
    }
}

Iterator介面

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        ArrayList list = new ArrayList();
        list.add("data_1");
        list.add("data_2");
        list.add("data_3");

        //遍歷方法1:Iterator介面
        Iterator it = list.iterator();//獲取Iterator物件
        while (it.hasNext()) {
            Object obj = it.next();
            System.out.println(obj);
        }
        
        //遍歷方法2:foreach迴圈
        /*
        foreach(容器中元素型別 臨時變數:容器變數){
            執行語句
        }
         */
        for (Object obj : list) {
            System.out.println(obj);
        }
    }
}

HashSet集合

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        HashSet set = new HashSet();
        for (int i = 1; i <= 5; i++) {
            set.add(i);
            set.add(i);//新增重複元素
        }
        Iterator it = set.iterator();
        while (it.hasNext()) {//判斷是否有重複元素
            Object obj = it.next();
            System.out.println(obj);
        }
    }
}

HashMap集合

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Map map = new HashMap();//建立Map集合
        map.put("1", "Jack");
        map.put("2", "Rose");
        map.put("3", "Luck");
        map.put("3", "Tom");//覆蓋

        Set keySet = map.keySet();//獲取鍵的集合
        Iterator it = keySet.iterator();//迭代鍵的集合
        while (it.hasNext()) {
            Object key = it.next();
            Object value = map.get(key);//獲取每個鍵所對應的值
            System.out.println(key + ": " + value);
        }
    }
}