java学习笔记(二)

基础知识

变长参数实例

public class ParamTest {
    public static void main(String[] args) {
        test("hello", "world", "this", "is", "hahaha");
    }
    public static void test(String... params) {
        for (String str : params) {
            System.out.println(str);
        }
    }
}
View Code

 枚举实例

public class EnumTest {
    public enum Color {red, orange, yellow, green, cyan, blue, purple;}
    public static void main(String[] args) {
        Color c = Color.green;
        switch (c) {
            case red:
                System.out.println("red");
                break;
            case green:
                System.out.println("green");
                break;
            case blue:
                System.out.println("blue");
                break;
            default:
                System.out.println("other color");
                break;
        }
    }
}
View Code

 枚举+foreach实例

public class EnumForeachTest {
    public static void main(String[] args) {
        for (Season s : Season.values()) {
            System.out.println(s);
        }
    }
}
enum Season {
    spring, summer, autumn, winter;
}
View Code

面向对象

日期操作Date+SimpleDateFormat

import java.util.Date;
import java.text.SimpleDateFormat;
public class DateDemo {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date);
        System.out.println(date.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        System.out.println(sdf.format(date));
    }
}
View Code

观察者模式Observable+Observer

import java.util.Observable;
import java.util.Observer;
public class ObserverDemo {
    public static void main(String[] args) {
        Stock s = new Stock("oracle", 1000);
        Investor iv1 = new Investor("aaa");
        Investor iv2 = new Investor("bbb");
        Investor iv3 = new Investor("ccc");
        Investor iv4 = new Investor("ddd");
        s.addObserver(iv1);
        s.addObserver(iv2);
        s.addObserver(iv3);
        s.addObserver(iv4);
        System.out.println(s);
        s.setPrice(8888);
        System.out.println(s);
    }
}
class Stock extends Observable {
    private String name;
    private double price;
    public Stock(String name, double price) {
        this.name = name;
        this.price = price;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        super.setChanged();
        super.notifyObservers(price);
        this.price = price;
    }
    public String toString() {
        return "stock's price is: " + price;
    }
}
class Investor implements Observer {
    private String name;
    public Investor(String name) {
        this.name = name;
    }
    public void update(Observable obj, Object arg) {
        System.out.println(name + " observed price is: " + arg);
    }
}
View Code

集合泛型

Set实例

import java.util.*;
public class SetTest {
    public static void main(String[] args) {
        Set<String> set = new HashSet<String>();
        set.add("a");
        set.add("b");
        set.add("c");
        set.add("d");
        set.add("e");
        set.add("a");
        System.out.println(set.size());
        for (Iterator<String> it = set.iterator(); it.hasNext();) {
            System.out.println(it.next());
        }
        System.out.println("***************************");
        for (String str : set) {
            System.out.println(str);
        }
    }
}
View Code

多线程

继承Thread+实现Runnable

public class ThreadDemo1 {
    public static void main(String[] args) {
        Thread t1 = new Thread1();
        t1.start();
        Thread t2 = new Thread(new Thread2(), "thread2");
        Thread t3 = new Thread(new Thread2(), "thread3");
        t2.start();
        t3.start();
    }
}
class Thread1 extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(currentThread().getName() + "####" + i);
        }
    }
}
class Thread2 implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "####" + i);
        }
    }
}
View Code

线程同步

public class SyncDemo1 {
    public static void main(String[] args) {
        Counter c = new Counter();
        new Thread(c).start();
        new Thread(c).start();
        new Thread(c).start();
        new Thread(c).start();
    }
}
class Counter implements Runnable {
    private int count;
    public void run() {
        while (count < 1000) {
            add();
            System.out.println(count);
        }
    }
    public void add() {
        synchronized (this) {
            count++;
        }
    }
    public synchronized void sub() {
        count--;
    }
}
View Code

生产者消费者+线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerDemo {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Basket b = new Basket();
        Producer p = new Producer(b);
        Consumer c = new Consumer(b);
        service.execute(p);
        service.execute(c);
        service.shutdown();
    }
}
class Basket {
    private int count;
    private Lock lock;
    private Condition empty;
    private Condition full;
    {
        count = 0;
        lock = new ReentrantLock();
        empty = lock.newCondition();
        full = lock.newCondition();
    }
    public void put() throws Exception {
        lock.lock();
        if (count == 100) full.await();
        count++;
        System.out.println("put an apple, count=" + count);
        empty.signalAll();
        lock.unlock();
    }
    public void get() throws Exception {
        lock.lock();
        if (count == 0) empty.await();
        count--;
        System.out.println("get an apple, count=" + count);
        full.signalAll();
        lock.unlock();
    }
}
class Producer implements Runnable {
    private Basket b;
    public Producer(Basket b) {
        this.b = b;
    }
    public void run() {
        while (true) {
            try {
                b.put();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
class Consumer implements Runnable {
    private Basket b;
    public Consumer(Basket b) {
        this.b = b;
    }
    public void run() {
        while (true) {
            try {
                b.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
View Code

I/O

字符流缓冲区实例

import java.io.*;
public class BufRwTest {
    public static void main(String[] args) throws Exception {
        FileWriter fw = new FileWriter("f:/test.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("hello,world.");
        bw.newLine();
        bw.write("this is bufferedRW test.");
        bw.flush();
        bw.close();
        FileReader fr = new FileReader("f:/test.txt");
        BufferedReader br = new BufferedReader(fr);
        String str;
        while ((str = br.readLine()) != null) {
            System.out.println(str);
        }
    }
}
View Code

字节流实例

import java.io.*;
public class ByteStreamTest {
    public static void main(String[] args) throws Exception {
        OutputStream os = new FileOutputStream("f:/test.txt");
        os.write("hello,xxx".getBytes());
        os.close();
        InputStream is = new FileInputStream("f:/test.txt");
        byte[] bt = new byte[is.available()];
        is.read(bt);
        System.out.println(new String(bt));
    }
}
View Code

字节流缓冲区实例

import java.io.*;
public class ByteStreamBufferTest {
    public static void main(String[] args) throws Exception {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("f:/test.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("f:/test.txt.bak"));
        int b = 0;
        while ((b = bis.read()) != -1) {
            bos.write(b);
        }
        bos.close();
        bis.close();
    }
}
View Code

 PrintWriter实例

import java.io.*;
public class PrintWriterTest {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out, true);
        String line;
        while ((line = br.readLine()) != null) {
            if ("end".equals(line)) break;
            pw.println(line.toUpperCase());
        }
    }
}
View Code

反射

通过对象获得类名

public class GetClassName {
    public static void main(String[] args) {
        String s = "hello";
        System.out.println(s.getClass().getName());
    }
}
View Code

通过反射调用类中的方法

import java.lang.reflect.*;
public class InvokeMethod {
    public static void main(String[] args) throws Exception {
        Class<?> c = null;
        c = Class.forName("Person");
        Method m = c.getMethod("introduce");
        m.invoke(c.newInstance());
        Constructor<?> cons[] = c.getConstructors();
        Person p = (Person)cons[0].newInstance("aaa", 33);
        p.introduce();
    }
}
class Person {
    private String name;
    private int age;
    public Person() {
        name = "aaa";
        age = 11;
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void introduce() {
        System.out.println("hello, my name is " + name + ", " + age + " years old.");
    }
}
View Code

通过反射操作类属性

import java.lang.reflect.*;
public class InvokeField {
    public static void main(String[] args) throws Exception {
        Class c = Class.forName("Person");
        Object o = c.newInstance();
        Field name = c.getDeclaredField("name");
        Field age = c.getDeclaredField("age");
        name.setAccessible(true);
        name.set(o, "aaa");
        age.setAccessible(true);
        age.set(o, 33);
        System.out.println(name.get(o));
        System.out.println(age.get(o));
    }
}
class Person {
    private String name;
    private int age;
}
View Code

反射实现工厂模式

public class FactoryDemo {
    public static void main(String[] args) {
        Animal a = Factory.getInstance("Wolf");
        if (a != null) a.eat();
    }
}
class Factory {
    public static Animal getInstance(String className) {
        Animal animal = null;
        try {
            animal = (Animal)Class.forName(className).newInstance();
        } catch (Exception e) {
        }
        return animal;
    }
}
interface Animal {
    void eat();
}
class Sheep implements Animal {
    public void eat() {
        System.out.println("sheep eat grass");
    }
}
class Wolf implements Animal {
    public void eat() {
        System.out.println("wolf eat sheep");
    }
}
View Code

数据库编程

import java.sql.*;
import java.util.*;
public class DB {
    private Connection conn;
    private String driver = "com.mysql.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/test";
    private String username = "root";
    private String password = "123456";
    public DB() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private ResultSet execSQL(String sql, Object ...args) {
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                pstmt.setObject(i + 1, args[i]);
            }
            pstmt.execute();
            return pstmt.getResultSet();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public User checkUser(String username, String password) {
        String sql = "select * from user where username=? and password=?";
        ResultSet rs = execSQL(sql, username, password);
        User user = new User();
        try {
            while (rs.next()) {
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public boolean addInfo(Message ly) {
        String sql = "insert into message(userId,date,title,content) values(?,?,?,?)";
        execSQL(sql, ly.getUserId(), ly.getDate(), ly.getTitle(), ly.getContent());
        return true;
    }
    public boolean insertUser(String username, String password) {
        String sql = "insert into user(username,password) values(?,?)";
        execSQL(sql, username, password);
        return true;
    }
    public ArrayList<Message> findLyInfo() {
        ArrayList<Message> list = new ArrayList<Message>();
        String sql = "select * from message";
        ResultSet rs = execSQL(sql);
        try {
            while (rs.next()) {
                Message ly = new Message();
                ly.setId(rs.getInt("id"));
                ly.setUserId(rs.getInt("userId"));
                ly.setDate(rs.getDate("date"));
                ly.setTitle(rs.getString("title"));
                ly.setContent(rs.getString("content"));
                list.add(ly);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    public String getUserName(int id) {
        String username = null;
        String sql = "select username from user where id=?";
        ResultSet rs = execSQL(sql, id);
        try {
            while (rs.next()) {
                username = rs.getString("username");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return username;
    }
    public static void main(String[] args) {
        DB db = new DB();
//        db.insertUser("bbb", "123");
//        Message ly = new Message();
//        ly.setUserId(1);
//        ly.setDate(new Date());
//        ly.setTitle("hello");
//        ly.setContent("hello, world.");
//        db.addInfo(ly);
        System.out.println(db.getUserName(1));
        System.out.println("DB test.");
    }
}
View Code

网络编程

udp实例

import java.net.*;
public class UdpServer {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds = new DatagramSocket(11111);
        while (true) {
            byte[] buf = new byte[1024];
            DatagramPacket rdp = new DatagramPacket(buf, buf.length);
            ds.receive(rdp);
            InetAddress addr = rdp.getAddress();
            int port = rdp.getPort();
            String str = new String(buf, 0, rdp.getLength());
            System.out.println("ip: " + addr + "port: " + port + "content: " + str);
            buf = str.toUpperCase().getBytes();
            DatagramPacket sdp = new DatagramPacket(buf, buf.length, addr, port);
            ds.send(sdp);
        }
    }
}
View Code
import java.net.*;
import java.io.*;
public class UdpClient {
    public static void main(String[] args) throws Exception {
        DatagramSocket ds = new DatagramSocket();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        InetAddress addr = InetAddress.getByName("127.0.0.1");
        byte[] buf = new byte[1024];
        while ((line = br.readLine()) != null) {
            if ("end".equals(line)) break;
            buf = line.getBytes();
            DatagramPacket sdp = new DatagramPacket(buf, buf.length, addr, 11111);
            ds.send(sdp);
            DatagramPacket rdp = new DatagramPacket(buf, buf.length);
            ds.receive(rdp);
            System.out.println(new String(buf, 0, rdp.getLength()));
        }
        ds.close();
    }
}
View Code
原文地址:https://www.cnblogs.com/feilv/p/4428116.html