这只是一篇我自己学习java的流水账笔记,包含了以下内容,全是基础代码示例,希望对正在学习java的小伙伴有帮助
- java编码:编码相关
- java常用代码:Java常用代码示例
- jdbc示例:JDBC编程示例
编码相关
- 隐式类型转换:计算时自动将容量小的类型转换为容量大的类型:byte,short,char->int->long->float->double. important(整数默认是int ,定义byte应该这样定义: byte b = (byte)12 , 浮点数默认是double , 因此,定义float应该这样定义: float f = 12.4f),总之记得一点:大数转换成小数记得加上强制转换!
- 关于int强制转换为byte的问题(默认byte(1字节)的范围在-128~127,如果把int(4字节)的254强制转换成byte,会砍掉多余字节) , 关于原码,反码,补码的文章, 二进制补码百度百科, 二进制加法 [重说三 : 计算机内部用补码来表示数字,正数(最高位是0)原码=反码=补码 ,负数(最高位是1)三码需要转换]
public class Test{ public static void main(String[] args){ byte b1 = (byte)254;//强制转换成byte System.out.println(b1);//结果输出-2 byte b2 = (byte)300; System.out.println(b2);//结果输出44,正数原码和补码相同 byte b3 = (byte)(-1); System.out.println(b3);//打印-1 }}/*解释b1:1:int的254表示为二进制(正数:原=反=补): 0000 0000 0000 0000 0000 0000 1111 1110(补)2:强制转换成byte,丢掉前面三个字节,留下(最高位是1,表示负数): 1111 1110(补)3:补码转反码(最高位符号位不变,其余取反): 1111 1110(补) -->> 1000 0001(反)4:反码求原码: 1000 0001(反) + 0000 0001 = 1000 0010(原)5:因此: 1000 0010表示-2*//*解释b2:1:int的300表示为二进制(正数:原=反=补): 0000 0000 0000 0000 0000 0001 0010 1100(补)2:强制转换成byte,丢掉前面三个字节,留下(最高位是0,表示正数): 0010 1100(补)3:正数原码和补码相同,原码为:0010 1100(原)4:因此: 0010 1100表示44*//*解释b3:1:int的(-1)的原码为:1000 0000 0000 0000 0000 0000 0000 0001(原)2:原码求反码:1111 1111 1111 1111 1111 1111 1111 1110(反)3:反码求补码:1111 1111 1111 1111 1111 1111 1111 1111(补)4:强制转换成byte,丢掉前面三个字节,留下(最高位是1,表示负数): 1111 1111(补)5:补码求反码:1000 0000(反)6:反码求原码:1000 0001(原)7:因此:1000 0001表示-1*/
Java常用代码示例
BigDecimal工具类封装
package com.scriptwang.Test; import java.math.BigDecimal; /** * Created by ScriptWang on 16/11/26. * * BigDecimal可用于精!确!计!算! */public class BigDecimalUtil { public static double add(double a1,double a2){ //将第一个参数转化成字符串构造BigDecimal对象 BigDecimal a = new BigDecimal(String.valueOf(a1)); //将第二个参数转化成字符串构造BigDecimal对象 // (注意两次转化字符串的过程不同) BigDecimal b = new BigDecimal(Double.toString(a2)); //调用BigDecimal的add方法,在调用doubleValue转换成double类型 return a.add(b).doubleValue(); } public static double substract(double a1,double a2){ BigDecimal a = new BigDecimal(String.valueOf(a1)); BigDecimal b = new BigDecimal(String.valueOf(a2)); return a.subtract(b).doubleValue(); } public static double multiply(double a1,double a2){ BigDecimal a = new BigDecimal(String.valueOf(a1)); BigDecimal b = new BigDecimal(String.valueOf(a2)); return a.multiply(b).doubleValue(); } public static double divide(double a1,double a2){ BigDecimal a = new BigDecimal(String.valueOf(a1)); BigDecimal b = new BigDecimal(String.valueOf(a2)); return a.divide(b).doubleValue(); } }
对象池的使用示例(多例模式)
package com.scriptwang.Test; import java.util.HashSet;import java.util.Set; /** * Created by ScriptWang on 16/11/26. * * 对象池的使用示例 */public class Dog { //加载类的时候初始化一个Set对象池,static的 private static Set dogPool = new HashSet<>(); private String name; private int age; //构造方法私有,不允许别人new对象,只允许自己new对象 private Dog(String name,int age){ this.name = name; this.age = age; } /** * * @param name * @param age * @return Dog * 工厂方法,在构造对象的时候,如果对象池里有,就返回已有的对象,不再new * 如果没有,则将new的对象加入到对象池中,并将其返回 */ public static Dog newInstance(String name,int age){ //循环对象池 for (Dog dog : dogPool){ //比较name和age,如果相同,则返回对象池里已有的对象 if (dog.getName().equals(name) && dog.getAge() == age){ return dog; } } //如果对象池里没有该对象,则new出新对象加入对象池并返回 Dog dog = new Dog(name, age); dogPool.add(dog); return dog; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString(){ return "Dog : " + name + " : " + age; }}
字符串反转工具类
package com.scriptwang.Test; /** * Created by ScriptWang on 16/11/26. * * 字符串反转工具类 */public class StringReverseUtil { /** * @param s * @return * 递归,用到length和subString方法 * 从字符串中间掰开,左右互换,一直循环,知道字符串的长度为1返回 */ public static String reverse1(String s){ int len = s.length(); if (len == 1) return s; String left = s.substring(0,len/2); String right = s.substring(len/2,len); return reverse1(right) + reverse1(left); } /** * * @param s * @return * 反向循环 */ public static String reverse2(String s){ String ref = ""; for (int i=s.length() - 1;i >= 0;i--){ //反向循环字符串连接方法 ref += s.charAt(i); } return ref; } /** * * @param s * @return * 正向循环 */ public static String reverse3(String s){ char[] chars = s.toCharArray(); String ref = ""; for (int i=0;i
Set、List和Map遍历方法
package com.scriptwang.Test; import java.util.*; /** * Created by ScriptWang on 16/11/26. * 循环遍历Set,List和Map的方法: * Set和List都可以用Iterator和foreach遍历,List比Set多一种size和get遍历 * Map有三种遍历方法,分别是keySey ; values ; Map.Entry和entrySet遍历,都使用foreach循环 */public class CollectionLoop { public static void main(String[] args){ SetLoop(); print("=======split line======"); ListLoop(); print("========split line====="); MapLoop(); } public static void print(Object o){ System.out.println(o); } /** * 两种循环方法:foreach循环 ; iterator循环 */ public static void SetLoop(){ Set set = new HashSet(); for (int i=0;i<4;i++) set.add(""+i); //foreach loop for(String value : set) print(value); //iterator loop for (Iterator i = set.iterator();i.hasNext();){ String value = i.next(); print(value); } } /** * 三种循环方法:foreach循环 ; iterator循环 ; size get for循环 */ public static void ListLoop(){ List list = new ArrayList(); for (int i=0;i<4;++i) list.add(""+i); //foreach loop for (String value : list) print(value); //iterator loop for (Iterator i = list.iterator();i.hasNext();){ String value = i.next(); print(value); } //size get for loop for (int i=0;i map = new TreeMap(); for (int i=0;i<4;i++) map.put("key:"+i,i); //keySet loop for (String key : map.keySet()){ Integer value = map.get(key); print(key); print(value); } //values loop 缺点:不能循环出key,只能循环出value for (Integer value : map.values()){ print(value); } //Map.Entry和entrySet循环 for(Map.Entry entry : map.entrySet()){ String key = entry.getKey(); Integer value = entry.getValue(); print(key); print(value); } } }
文件复制
package com.scriptwang.Test; import java.io.*; /** * Created by ScriptWang on 16/11/26. * */public class CopyFiles { public static void main(String[] args){ copy("/Volumes/Swap/所有PSD归档.zip","/Volumes/Swap/所有PSD归档1.zip"); } public static void copy(String path,String pathout){ InputStream in = null; OutputStream out = null; byte[] buffer = new byte[256];//准备一个缓冲区 try{ in = new FileInputStream(path); out = new FileOutputStream(pathout); }catch (FileNotFoundException e){ System.out.println("File not found,Please check it!"); } try{ //将文件读取到buffer里面,并返回读取到字节数!! // len是指读取到的字节数 for (int len = in.read(buffer);len > 0;len = in.read(buffer)){ System.out.println(len); //将buffer从0到len写出去! out.write(buffer,0,len); } }catch (IOException e){ e.printStackTrace(); } } }
序列化与反序列化一个对象
package com.scriptwang.Test; import java.io.Serializable; /** * Created by ScriptWang on 16/11/26. * * 被序列化的类要实现Serializable接口 */public class Student implements Serializable{ String name; int age; Student(String name,int age){ this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + ''' + ", age=" + age + '}'; }} package com.scriptwang.Test; import java.io.*; /** * Created by ScriptWang on 16/11/26. * * 序列化与反序列化一个对象 */public class Test4 { public static void main(String[] args){ Student s = new Student("A",12); serialize("/Volumes/Swap/data.dat",s); Student o = (Student) deserialization("/Volumes/Swap/data.dat"); System.out.println(o); } /** * * @param path * @param obj * 序列化一个类 */ public static void serialize(String path,Object obj){ ObjectOutputStream oos = null; try{ //初始化oos oos = new ObjectOutputStream(new FileOutputStream(path)); //将obj写到文件 oos.writeObject(obj); }catch(IOException e){ e.printStackTrace(); } } /** * * @param path * @return * 反序列化 */ public static Object deserialization(String path){ ObjectInputStream ois = null; Object obj = null; try{ //初始化ois ois = new ObjectInputStream(new FileInputStream(path)); //从文件读取对象,会抛出ClassNotFoundException obj = ois.readObject(); }catch(IOException | ClassNotFoundException e){ e.printStackTrace(); } return obj; }}
生产者和消费者模型
package com.scriptwang.Test; /** * Created by ScriptWang on 16/11/26. */public class ProducerAndCostumer { public static void main(String[] agrs){ Stack s = new Stack(4); //将同一个Stack给Producer和Consumer new Thread(new Producer(s)).start(); //可以同时用两个Producer线程,只要他们总的add和pop的个数相同就不会出现死锁 new Thread(new Producer(s)).start(); new Thread(new Consumer(s)).start(); }} class Stack{ String[] datas; int index; //初始化 Stack(int capacity){ datas = new String[capacity]; index = 0; } /** * * @param s * 添加方法 */ public synchronized void add(String s){ /** * 当指针指到栈顶的时候表示Stack已经满了,不能在加了 * 因此告诉Producer线程们该wait了 * 等待Consumer来叫醒Producer线程 */ while (index == datas.length){ try{ this.wait();//等待 }catch(InterruptedException e){ e.printStackTrace(); } } this.notifyAll();//叫醒正在等待的Comsumer线程 datas[index] = s; index ++; } /** * * @return * 移除方法 */ public synchronized String pop(){ /** * 当指针指到栈底时表示Stack已经空了,没有东西可以在pop了 * 这时需要让Consumer线程wait * 让Producer线程叫醒Consumer线程 */ while(index == 0){ try{ this.wait();//Consumer线程等待 }catch(InterruptedException e){ e.printStackTrace(); } } this.notifyAll();//叫醒Producer线程 index --; return datas[index]; }} class Producer implements Runnable{ private Stack s; Producer(Stack s) { this.s = s; } @Override public void run(){ for (int i=1;i<=5;i++){//两个Producer线程时,则每个添加五个 s.add(""+i); System.out.println(i + " has add! ^_^ "); } }} class Consumer implements Runnable{ private Stack s; Consumer(Stack s){ this.s = s; } @Override public void run(){ for (int i=1;i<=10;++i){//pop10个 String pop = s.pop(); System.out.println(pop + " has pop!"); /** * pop一个数据后就等待100ms * 说明Producer比Consumer快! */ try{ Thread.sleep(100); }catch (InterruptedException e){ e.printStackTrace(); } } }}
死锁
package com.scriptwang.Test; /** * Created by ScriptWang on 16/11/26. */public class DeadLock implements Runnable{ //flag用于执行不同的代码块 private boolean flag; /** * 声明o1和o2为static,保证每个DeadLock对象都共享同一份儿o1和o2 * */ private static Object o1; private static Object o2; // 初始化 DeadLock(boolean flag){ this.flag = flag; //初始化o1和o2 o1 = new Object(); o2 = new Object(); } public static void main(String[] args){ new Thread(new DeadLock(false)).start(); new Thread(new DeadLock(true)).start(); } @Override public void run(){ //根据flag执行不同的代码块 if (flag){ /** * 先锁定o1再锁定o2 */ synchronized (o1){ System.out.println("====1"); try{ Thread.sleep(200); }catch (InterruptedException e){ e.printStackTrace(); } synchronized (o2){ try{ Thread.sleep(200); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("====2"); } } } else { /** * 先锁定o2再锁定o1 */ synchronized (o2){ System.out.println("====3"); try{ Thread.sleep(200); }catch(InterruptedException e){ e.printStackTrace(); } synchronized (o1){ try{ Thread.sleep(200); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("====4"); } } } } }
反射(创建对象、访问Field、调用方法、重写toString)
import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method; /** * Created by Script Wang on 2016/11/27. */ class Student { private String name; private int age; Student (){ name = ""; age = 0; } Student (String name,int age){ this.name = name; this.age = age; } public void m(){ System.out.println("I am invoked ===== !!!"); } /** * * @return * 利用反射重写toString */ @Override public String toString(){ StringBuilder sb = new StringBuilder(); Field[] fields = this.getClass().getDeclaredFields();//拿到所有成员变量 //循环成员变量,将变量名值添加到sb中 for (int i=0;i
i++ 和 ++i 的区别
i++ 先取值再做自加运算; ++i 先做自加运算在取值.
public class Test{ public static void main(String[] args){ int i = 10; int i1 = 1 + i++; System.out.println(i1);// 11 System.out.println(i);// 11 i = 10; int i2 = 1 + ++i; System.out.println(i2);// 12 System.out.println(i);// 11 }}
JDBC编程示例
package com.scriptwang.test; import java.sql.*; /** * Created by ScriptWang on 16/11/30. * JDBC的基本使用方法 */public class TestJDBC { public static void main(String[] args){ Connection c = null; Statement s = null; PreparedStatement ps = null; ResultSet r = null; try{ //1:new驱动程序 Class.forName("com.mysql.jdbc.Driver"); //2:通过url,username和pwd拿到Connection c = DriverManager.getConnection("jdbc:mysql://**","*","*"); //3:通过Conenction创建Statement s = c.createStatement(); //4:通过Statement执行sql初始化ResultSet r = s.executeQuery("select * from tablename"); //5:对ResultSet进行操作 while(r.next()){ String value = r.getString(1); } /** * JDBC中比较常用的PreparedStatement的用法 */ //通过Connection初始化ps,ps种通过用问号作为占位符 ps = c.prepareStatement("delete from tablename where id > ?"); ps.setInt(1,2);//将sql语句种第一个问号设置为2 int row = ps.executeUpdate();//执行executeUpdate返回受影响的行数 }catch (ClassNotFoundException e){ e.printStackTrace(); }catch (SQLException e){ e.printStackTrace(); }finally{ try{ if (r != null){ r.close(); r = null; } if (ps != null){ ps.close(); ps = null; } if (c != null){ c.close(); c = null; } }catch (SQLException e){ e.printStackTrace(); } } } public static void print(Object o){ System.out.println(o); }}
JDBC事务的使用
package com.scriptwang.test; import java.sql.*; /** * Created by ScriptWang on 16/11/30. * JDBC的事务使用的基本方法 */public class TestJDBC { public static void main(String[] args){ Connection c = null; Statement s = null; PreparedStatement ps = null; ResultSet r = null; try{ //1:new驱动程序 Class.forName("com.mysql.jdbc.Driver"); //2:通过url,username和pwd拿到Connection c = DriverManager.getConnection("jdbc:mysql://*","*","*"); //3:将自动提交设置为false c.setAutoCommit(false); //4:通过Conenction创建Statement s = c.createStatement(); //5:通过Statement执行sql int row = s.executeUpdate("insert into tablename values (2,'B')"); //6:手动提交 c.commit(); //7:将自动提交还原 c.setAutoCommit(true); }catch (ClassNotFoundException e){ e.printStackTrace(); }catch (SQLException e){ /** * 当以上操作catch到任何的SQLException的时候,需要回滚 * */ try{ //1:回滚数据 c.rollback(); //2:设置自动提交为true c.setAutoCommit(true); }catch (SQLException e1){ e1.printStackTrace(); } e.printStackTrace(); }finally{ try{ if (r != null){ r.close(); r = null; } if (ps != null){ ps.close(); ps = null; } if (c != null){ c.close(); c = null; } }catch (SQLException e){ e.printStackTrace(); } } } public static void print(Object o){ System.out.println(o); }}
JDBC实现数据访问对象层DAO(Data Access Object)
package com.scriptwang.test; import java.sql.*;import java.util.ArrayList;import java.util.List; /** * Created by ScriptWang on 16/11/30. * Dao(Data Access Object)数据访问对象层 * Dao的设计意图是让上层对待底层数据的时候,能够用一个对象的眼光来看待 */public class TestDao { public static void main(String[] args){ List list = new JdbcDao().getAllUsers(); print(list); } public static void print(Object o){ System.out.println(o); }} class User{ private int id; private String name; User(int id,String name){ this.id = id; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString(){ return id + " : " + name; }} class JdbcDao{ /** * 静态初始化Driver,无论多少个JdbcDao对象static语句块始终只执行一次 * 也就是说Driver只初始化一次!!!! */ static { try{ Class.forName("com.mysql.jdbc.Driver"); }catch (ClassNotFoundException e){ e.printStackTrace(); } } /** * * 拿到连接 */ public Connection getConn(){ Connection c = null; String url = "jdbc:mysql://*"; String user = "*"; String pwd = "*"; try{ c = DriverManager.getConnection(url,user,pwd); }catch (SQLException e){ e.printStackTrace(); } return c; } /** * 释放资源 */ public void release(ResultSet r , Statement s , Connection c){ try{ if (r != null){ r.close(); r = null; } if (s!= null){ s.close(); s = null; } if (c != null){ c.close(); c = null; } }catch (SQLException e){ e.printStackTrace(); } } public void release(Statement s , Connection c){ try{ if (s!= null){ s.close(); s = null; } if (c != null){ c.close(); c = null; } }catch (SQLException e){ e.printStackTrace(); } } /** * 查询所有用户(查) */ public List getAllUsers(){ List list = new ArrayList(); Connection c = null; Statement s = null; ResultSet r = null; String sql = "select * from t"; try{ c = this.getConn(); s = c.createStatement(); r = s.executeQuery(sql); while (r.next()){ User user = new User(r.getInt(1),r.getString(2)); list.add(user); } return list; }catch (SQLException e){ e.printStackTrace(); }finally{ release(r,s,c); } return null; } /** * 根据id获取User对象(查) */ public User getUserById(int id){ Connection c = null; PreparedStatement ps = null; ResultSet r = null; String sql = "select * from t where id = ?"; try{ c = this.getConn(); ps = c.prepareStatement(sql); ps.setInt(1,id); r = ps.executeQuery(); if (r.next()){ return new User(r.getInt(1),r.getString(2)); } }catch (SQLException e){ e.printStackTrace(); }finally { this.release(r,ps,c); } return null; } /** * 将旧得User改为新的User,返回新的User(改) */ public User updateUser(User oldU,User newU){ Connection c = null; PreparedStatement ps = null; String sql = "update t set id = ? ,name = ? where id = ? and name = ?"; try{ c = this.getConn(); c.setAutoCommit(false);//事务开始 ps = c.prepareStatement(sql); ps.setInt(1,newU.getId()); ps.setString(2,newU.getName()); ps.setInt(3,oldU.getId()); ps.setString(4,oldU.getName()); int row = ps.executeUpdate(); if (row>0){ c.commit();//提交 return newU; } }catch (SQLException e){ try{ c.rollback(); c.setAutoCommit(true); }catch (SQLException e1){ e1.printStackTrace(); } e.printStackTrace(); }finally { release(ps,c); } return null; } /** * 根据id删除用户(删) */ public boolean deleteUserById(int id){ Connection c = null; PreparedStatement ps = null; String sql = "delete from t where id = ?"; int row = 0 ; try{ c = this.getConn(); c.setAutoCommit(false);// 事务开始 ps = c.prepareStatement(sql); ps.setInt(1,id); row = ps.executeUpdate();//返回受影响的行数,如果没有,返回0 if (row > 0){ c.commit(); //提交事务 return true; } }catch (SQLException e){ try{ /** * 如果上面代码catch到Exception * 第一要做的事情是rollback * 第二是将自动提交设置回原来的值 */ c.rollback(); c.setAutoCommit(true); }catch (SQLException e1){ e1.printStackTrace(); } e.printStackTrace(); }finally{ System.out.println(row + " rows has delete!"); this.release(ps,c); } return false; } /** * 插入用户数据(增) */ public boolean insUser(User user){ Connection c = null; PreparedStatement ps = null; String sql = "insert into t values (?,?)"; try{ c = this.getConn(); c.setAutoCommit(false); //事务开始 ps = c.prepareStatement(sql); ps.setInt(1,user.getId()); ps.setString(2,user.getName()); int row = ps.executeUpdate(); if (row > 0){ c.commit(); //提交 System.out.println("user"+"("+user.getId()+" : "+user.getName()+")"+" has inserted!"); return true; } }catch (SQLException e){ try{ /** * catch到Exception回滚并还原 */ c.rollback(); c.setAutoCommit(true); }catch (SQLException e1){ e1.printStackTrace(); } e.printStackTrace(); }finally{ release(ps,c); } return false; } }