Getting Started with Java study notes (full)

JAVA

https://zhuanlan.zhihu.com/p/21454718
reference laboratory building part of the code, invasion delete
read through the document and then try to personally review them again endorsed standard process

= B + C = 1.A = - ~ DA = (B + = (C = - (~ D)))
2. If the number of operands + a
string, another string will be converted to . If you want to connect and addition used together, be sure to use
brackets. For example:
System.out.println ( "the Total:" + +. 4. 3); // Print "Total: 34", instead of 7!
3. While the operands modulo operator is generally an integer, floating point numbers may be used. For example, 4.3% 2.1
Results 0.1.
4.System.out.println ( ". 7 / 3.0 IS" + (Double) 7/3);
5. The == If compare two numbers or characters, and different types of two operands, before the comparison will narrow range of operand value is converted into a wide range of types of operands. For example, the comparison value of type short and float
value type will first convert the value of type short in comparison to the prior float.
B = 12 is 6.int;
System.out.println (~ B);
bitwise
7 >> signed shift right >>> unsigned right shift.
-50 >> 2 >> 2 = 11110011 // 11001110 -13 =! = -50/4
-50 0xFFFFFFCE >>> >>> 2 // 2 = 0x3FFFFFF3 1,073,741,811

// true:所有字符串都是String类的实例
"string" instanceof String
// true:字符串也是Object类的实例
"" instanceof Object
// false:null不是任何类的实例
null instanceof String
Object o = new int[] {1,2,3};
o instanceof int[] // true:这个数组是int数组
o instanceof byte[] // false:这个数组不是byte数组
o instanceof Object // true:所有数组都是Object类的实例
// 使用instanceof确保能放心校正对象
if (object instanceof Point) {
 Point p = (Point) object;
}
switch 语句可以使用多个 case 子句标注同一个希望执行的语句。例如下面这个方法中的
switch 语句:
boolean parseYesOrNoResponse(char response) {
 switch(response) {
 case 'y':
 case 'Y': return true;
 case 'n':
 case 'N': return false;
 default:
 throw new IllegalArgumentException("Response must be Y or N");
 }
}
// 这些是我们想打印的数字
int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
// 这是打印这些数字的循环
for(int n : primes)
 System.out.println(n);

11.synchronized exclusive lock // multithreaded
the synchronized (expression) {
statements
}
calculation expression of the expression must be an object or an array. statements that could lead to the destruction of the code
block, must be placed in curly braces.
The statements before, Java interpreter first calculation expression obtained for the array of objects or acquire an exclusive lock
(exclusive lock), until the finished block of statements before release. As long as a thread that owns the object exclusive lock, other
threads can no longer acquire the lock.

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Hello!Fucking World!");
        int sum=1;
        double ans=(1.0*sum)/Math.sqrt(1.234*4);
        System.out.println(ans);
        System.out.println("1234"+5+6);
        System.out.println(4.3%2.1);
        System.out.println("7/3.0 is"+(double)7/3);
        
        int []primes= {1,2,3,4,5,6,7,8,9};
        for(int n:primes)
        {
            System.out.print();
            
        }
    }
    

}

constant

final double pi = 3.14 constant
constants can be declared re-assignment, but can only be assigned once, with different C ++
String is a constant whose value can not be modified after creation
equals () to determine whether two strings are the same , with the \ (O (mn) \) method
used "==" compare two objects is stored in the memory address is the same.
And the use of the connection, not only the connection string, may be connected to other types. However, when required elements are connected to at least one string


public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s1="java";
        String s2=new String("Java");
        System.out.println(s1.equals(s2));//false
        System.out.println(s1.equalsIgnoreCase(s2));//true无视大小写
        boolean b=(s1==s2);
        System.out.println(b);
        String s3=s1+s2;
        String s4=s1.concat(s2);
        System.out.println(s3);
        System.out.println(s4);
        System.out.println();
        int len=s1.length();
        for(int i=0;i<len;i++)
        {
            System.out.println(s1.charAt(i));//相当于C++的取分量
        }

        
    }
    

}

indexOf (ch) search for the first occurrence of the character ch index
indexOf (String) search for the first occurrence of the substring index
lastIndexOf () the last occurrence

public class StringTest {
    public static void main(String[] args) {
         String s = "abcdefabc";
         System.out.println("字符a第一次出现的位置为"+s.indexOf('a'));
         System.out.println("字符串bc第一次出现的位置为"+s.indexOf("bc"));
         System.out.println("字符a最后一次出现的位置为"+s.lastIndexOf('a'));
         System.out.println("从位置3开始到结束的字符串"+s.substring(3));
         System.out.println("从位置3开始到6之间的字符串"+s.substring(3,6));
    }
}
字符a第一次出现的位置为0
字符串bc第一次出现的位置为1
字符a最后一次出现的位置为6
从位置3开始到结束的字符串defabc
从位置3开始到6之间的字符串def

Removing the string class using the scanner space


import java.util.Scanner;
public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        String s=sc.nextLine();
        int len=s.length();
        String ans="";
        for(int i=0;i<len;i++)
        {
            if(s.charAt(i)!=' ')
            {
                ans=ans+s.charAt(i);
            }
        }
        System.out.println(ans);    
    }
    

}
import java.util.Scanner;

public class HelloWorld {
    public static void func()
    {
        System.out.println("wait!I will rape your mother.");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        func();
        
    }
}

switch(表达式){
    case 值1:
        代码块1
        break;
    case 值2:
        代码块2
        break;
    ...
    default:
        默认执行的代码块
}

int [] ages = {12,18,9,33,45,60} ; // declare and initialize an integer array, which has six elements
char [] symbol = new char [ 10] // declaration and partitioned a char length of array 10

Unlike C ++, it is placed in front of the brackets

int [] a1 = {1,2,3};
int [] a2;
a2 = a1;

a2 where a1 is a reference to the

int []a= {1,2,3,4,5,6};
        for(int num:a)
        {
            System.out.println(num);
        }//这样可以auto遍历数组
这样一直输入
Scanner in=new Scanner(System.in);
        String temp;
        //temp=in.nextLine();
        while(true)
        {
            temp=in.nextLine();
            System.out.println(temp);
            if(temp.equals("end"))
            {
                break;
            }
        }
        

Object-Oriented

1 == two will determine whether the same address of the object, without reloading
2.final modified class, then the class is not allowed to be inherited as a final class
final modification method, the method does not allow to be overwritten (rewritten)
final modifying attributes: the class attribute does not implicitly initialized (initialization class attribute must have a value) or the assignment in the constructor (but only one option)
Final modification variable, the value of this variable is assigned only a value that is constant

  1. Only this class can access private
    by default have access to
    protected subclasses can also access
    public things universally accessible
    inherited subclass extends parent class
    java only single inheritance and Inheritance public
    java no -> operator, are replaced by dots with super to access the parent class object
方法重载有以下几种规则:

方法中的参数列表必须不同。比如:参数个数不同或者参数类型不同。
访问权限,返回值类型和抛出的异常不同不能实现重载
重载的方法中允许抛出不同的异常
可以有不同的返回值类型,但是参数列表必须不同
可以有不同的访问修饰符

Note that allows different exception, it can not be overloaded Anomaly

public class Test{
    public static void main(String args[]){
           Animal a = new Animal(); // Animal 对象
        Dog d = new Dog();   // Dog 对象

          Animal b = new Dog(); // Dog 对象,向上转型为Animal类型,具体会在后面的内容进行详解

          a.bark();// 执行 Animal 类的方法
         d.bark();//执行 Dog 类的方法
          b.bark();//执行 Dog 类的方法
       }
}

When the up-converted (the parent class objects to sub-class reference, the same name in the subclass overrides the parent class)

References to the parent class is not a subclass with reference

java achieve polymorphism has three necessary conditions: · rewrite inheritance and transition Up

abstract abstract

public class CellPhone extends TelePhone {

    @Override
    public void call() {
        System.out.println("我可以打电话!");
    }

    @Override
    public void message() {
        System.out.println("我可以发短信!");
    }

    public static void main(String[] args) {
        CellPhone cp = new CellPhone();
        cp.call();
        cp.message();
    }

}

// Animal.java
interface Animal {
        //int x;
        //编译错误,x需要初始化,因为是 static final 类型
        int y = 5;
        public void eat();
        public void travel();
}
修饰符 interface A extends 接口1,接口2{

}

修饰符 class A implements 接口1,接口2{

} 

Internal class (and is not a concept of nested classes)

内部类提供了更好的封装,可以把内部类隐藏在外部类之内,不允许同一个包中的其他类访问该类
内部类的方法可以直接访问外部类的所有数据,包括私有的数据
内部类所实现的功能使用外部类同样可以实现,只是有时使用内部类更方便
内部类允许继承多个非接口类型(具体将在以后的内容进行讲解)
public class animal {
    public static String s="12345678";
    public class dog
    {
        public void bark()
        {
            System.out.println("my s is"+s);
        }
    }
    public static void main(String args[])
    {
        animal a=new animal();
        dog b=a.new dog();
        b.bark();
    }
}
public class animal {
    public static String s="12345678";
    public String name="fuck";
    public static class dog
    {
        public String name="what a";
        public void bark()
        {
            System.out.println("my in name is"+name);
            System.out.println("my out s is"+animal.s);
            System.out.println("my out name is"+(new animal().name));
        }
    }
    public static void main(String args[])
    {
        dog a=new dog();
        a.bark();
    }
}

    静态内部类不能直接访问外部类的非静态成员,但可以通过 new 外部类().成员 的方式访问
如果外部类的静态成员与内部类的成员名称相同,可通过类名.静态成员访问外部类的静态成员;如果外部类的静态成员与内部类的成员名称不相同,则可通过成员名直接调用外部类的静态成员
创建静态内部类的对象时,不需要外部类的对象,可以直接创建 内部类 对象名= new 内部类();
连::运算符都被.代替了

java still have a local inner class can be defined inside a class method in
an anonymous inner classes, by definition, no internal class name. Because there is no name, so anonymous inner classes can only be used once, it is usually used to simplify writing code. However, the use of anonymous inner classes there is a prerequisite: you must inherit from a parent class or implement an interface.

// Outer.java
public class Outer { 

    public Inner getInner(final String name, String city) { 
        return new Inner() { 
            private String nameStr = name; 
            public String getName() { 
                return nameStr; 
            } 
        };
    } 

    public static void main(String[] args) { 
        Outer outer = new Outer(); 
        Inner inner = outer.getInner("Inner", "NewYork"); 
        System.out.println(inner.getName()); 
    } 
} 
interface Inner { 
    String getName(); 
}

Note java class behind semicolon does not need, what anonymous direct interface (corresponding to a prototype declaration), return new inner () {}; to normal within the braces will be able to define the class

Common categories

import.java.util.Arrays

import java.util.Arrays;
import java.util.Random;
public class Out
{
    public static void main(String args[])
    {
        int arr[]=new int[10];
        //fill  填充
        Arrays.fill(arr,9);
        System.out.println("fill:"+Arrays.toString(arr));
        Random random=new Random();
        for(int i=0;i<arr.length;i++)
        {
            //随机
            arr[i]=random.nextInt(101);
            //这里是一个上开界,100以内的随机数
        }
        System.out.println("random:"+Arrays.toString(arr));
        arr[5]=50;
        Arrays.sort(arr);
        System.out.println("sort:"+Arrays.toString(arr));
        //二分搜索找返回下标
        int i=Arrays.binarySearch(arr, 50);
        System.out.println(i);
        int newarr[]=Arrays.copyOf(arr,arr.length);
        //复制
        System.out.println("copy"+Arrays.toString(arr));
    }
}
/*
fill:[9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
random:[60, 57, 49, 60, 31, 97, 14, 7, 5, 33]
sort:[5, 7, 14, 31, 33, 49, 50, 57, 60, 60]
6
copy[5, 7, 14, 31, 33, 49, 50, 57, 60, 60]*/
 */
 StringBuilder 是一种可以拼接字符串的类,拼接完成后可以用toString转化成字符串
 import java.util.Arrays;
import java.util.Random;
public class Out
{
    public static void main(String args[])
    {
        StringBuilder s = new StringBuilder("I");
        s.append("java");
        s.insert(1, "love");//原来处于1位的字符后移
        System.out.println(s.toString());
    }
}
//Ilovejava

Class Calendar

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarDemo {
    public static void main(String[] args) {
        System.out.println("完整显示日期时间:");
        // 字符串转换日期格式
        DateFormat fdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = fdate.format(new Date());
        System.out.println(str);

        // 创建 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        // 初始化 Calendar 对象,但并不必要,除非需要重置时间
        calendar.setTime(new Date());

        // 显示年份
        System.out.println("年: " + calendar.get(Calendar.YEAR));

        // 显示月份 (从0开始, 实际显示要加一)
        System.out.println("月: " + calendar.get(Calendar.MONTH));


        // 当前分钟数
        System.out.println("分钟: " + calendar.get(Calendar.MINUTE));

        // 今年的第 N 天
        System.out.println("今年的第 " + calendar.get(Calendar.DAY_OF_YEAR) + "天");

        // 本月第 N 天
        System.out.println("本月的第 " + calendar.get(Calendar.DAY_OF_MONTH) + "天");

        // 3小时以后
        calendar.add(Calendar.HOUR_OF_DAY, 3);
        System.out.println("三小时以后的时间: " + calendar.getTime());
        // 格式化显示
        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());
        System.out.println(str);

        // 重置 Calendar 显示当前时间
        calendar.setTime(new Date());
        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());
        System.out.println(str);

        // 创建一个 Calendar 用于比较时间
        Calendar calendarNew = Calendar.getInstance();

        // 设定为 5 小时以前,后者大,显示 -1
        calendarNew.add(Calendar.HOUR, -5);
        System.out.println("时间比较:" + calendarNew.compareTo(calendar));

        // 设定7小时以后,前者大,显示 1
        calendarNew.add(Calendar.HOUR, +7);
        System.out.println("时间比较:" + calendarNew.compareTo(calendar));

        // 退回 2 小时,时间相同,显示0
        calendarNew.add(Calendar.HOUR, -2);
        System.out.println("时间比较:" + calendarNew.compareTo(calendar));

        // calendarNew创建时间点
        System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendarNew.getTime()));
        // calendar创建时间点
        System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime()));
        System.out.println("时间比较:" + calendarNew.compareTo(calendar));
    }
}
编译运行:

$ javac CalendarDemo.java
$ java CalendarDemo
完整显示日期时间:
2018-12-12 15:50:49
年: 2018
月: 11
分钟: 50
今年的第 346天
本月的第 12天
三小时以后的时间: Wed Dec 12 18:50:49 CST 2018
2018-12-12 18:50:49:449
2018-12-12 15:50:49:455
时间比较:-1
时间比较:1
时间比较:1
2018-12-12 15:50:49:456
2018-12-12 15:50:49:455
时间比较:1
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {
    public static void main(String[] args) {
        String strDate, strTime;
        Date objDate = new Date();
        System.out.println("今天的日期是:" + objDate);
        long time = objDate.getTime();
        System.out.println("自1970年1月1日起以毫秒为单位的时间(GMT):" + time);
        strDate = objDate.toString();
        //提取 GMT 时间
        strTime = strDate.substring(11, (strDate.length() - 4));
        //按小时、分钟和秒提取时间
        strTime = "时间:" + strTime.substring(0, 8);
        System.out.println(strTime);
        //格式化时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(formatter.format(objDate));
    }
}
编译运行:

$ javac DateDemo.java
$ java DateDemo
今天的日期是:Wed Dec 12 14:43:15 CST 2018
自1970年1月1日起以毫秒为单位的时间(GMT):1544596995669
时间:14:43:15
2018-12-12 14:43:15

MATH

rint (double numvalue) double Returns the closest integer value NumValue
round (T arg) arg is returned long double, int returns arg nearest integer value returned is a float
Random a double value from 0.0 to 1.0

System

System 使用示例
在/home/project/目录下新建一个源代码文件SystemDemo.java

import java.util.Arrays;

public class SystemDemo {
    public static void main(String[] args) {
        int[] a = {7, 8, 9, 10, 11};
        int[] b = {1, 2, 3, 4, 5, 6};
        //从数组a的第二个元素开始,复制到b数组的第三个位置 复制的元素长度为3
        System.arraycopy(a, 1, b, 2, 3);
        //注意他是用前者覆盖后者
        //输出结果
        System.out.println(Arrays.toString(b));
        System.out.println("当前时间:" + System.currentTimeMillis());
        System.out.println("java版本信息:" + System.getProperty("java.version"));
        //运行垃圾收集器
        System.gc();
        //退出
        System.exit(0);
    }
}

编译运行:

$ javac SystemDemo.java
$ java SystemDemo
[1, 2, 8, 9, 10, 6]
当前时间:1544670501472
java版本信息:11

Random

import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        Random random = new Random();
        //随机生成一个整数 int范围
        System.out.println(random.nextInt());
        //生成 [0,n] 范围的整数  设n=100
        System.out.println(random.nextInt(100 + 1));
        //生成 [0,n) 范围的整数  设n=100
        System.out.println(random.nextInt(100));
        //生成 [m,n] 范围的整数  设n=100 m=40
        System.out.println((random.nextInt(100 - 40 + 1) + 40));
        //随机生成一个整数 long范围
        System.out.print(random.nextLong());
        //生成[0,1.0)范围的float型小数
        System.out.println(random.nextFloat());
        //生成[0,1.0)范围的double型小数
        System.out.println(random.nextDouble());
    }
}

Generics

/*
使用T代表类型,无论何时都没有比这更具体的类型来区分它。如果有多个类型参数,我们可能使用字母表中T的临近的字母,比如S。
*/
class Test<T> {
    private T ob;

    /*
    定义泛型成员变量,定义完类型参数后,可以在定义位置之后的方法的任意地方使用类型参数,就像使用普通的类型一样。
    注意,父类定义的类型参数不能被子类继承。
    */

    //构造函数
    public Test(T ob) {
        this.ob = ob;
    }

    //getter 方法
    public T getOb() {
        return ob;
    }


    //setter 方法
    public void setOb(T ob) {
        this.ob = ob;
    }

    public void showType() {
        System.out.println("T的实际类型是: " + ob.getClass().getName());
        
    }
}

public class TestDemo {
    public static void main(String[] args) {
        // 定义泛型类 Test 的一个Integer版本
        Test<Integer> intOb = new Test<Integer>(88);
        intOb.showType();
        int i = intOb.getOb();
        System.out.println("value= " + i);
        System.out.println("----------------------------------");
        // 定义泛型类Test的一个String版本
        Test<String> strOb = new Test<String>("Hello Gen!");
        strOb.showType();
        String s = strOb.getOb();
        System.out.println("value= " + s);
    }
}
编译运行:

$ javac TestDemo.java
$ java TestDemo
T的实际类型是: java.lang.Integer
value= 88
----------------------------------
T的实际类型是: java.lang.String
value= Hello Gen!

Ob determine the actual type of need only getClass (). GetName ()

java STL

https://www.shiyanlou.com/courses/1230/labs/9469/document
specific usage see here
1.toString can be overloaded, overload cout equivalent
methods 2.ArrayList class, add (node), add ( 0, node) node is inserted at the 0 position, get (i) obtained in the i-th node
3.addAll (ARR), the addAll (0, ARR) insert the whole array node
size size ()
method traverse

/**
     * 通过迭代器来遍历
     * 迭代器的工作是遍历并选择序列中的对象,Java 中 Iterator 只能单向移动
     */
    public void testIterator() {
        // 通过集合的iterator方法,取得迭代器实例
        Iterator<Student> it = students.iterator();
        System.out.println("有如下学生(通过迭代器访问):");
        while (it.hasNext()) {

            Student st = it.next();
            System.out.println("学生" + st.id + ":" + st.name);
        }
    }

    /**
     * 通过for each 方法访问集合元素
     *
     */
    public void testForEach() {
        System.out.println("有如下学生(通过for each):");
        for (Student obj : students) {
            Student st = obj;
            System.out.println("学生:" + st.id + ":" + st.name);
        }
        //使用java8 Steam将学生排序后输出
        students.stream()//创建Stream
                //通过学生id排序
                .sorted(Comparator.comparing(x -> x.id))
                //输出
                .forEach(System.out::println);
    }
 /**
     * 修改List中的元素
     *
     */
    public void testModify() {
        students.set(4, new Student("3", "吴酒"));
    }

    /**
     * 删除List中的元素
     *
     */
    public void testRemove() {
        Student st = students.get(4);
        System.out.println("我是学生:" + st.id + ":" + st.name + ",我即将被删除");
        students.remove(st);
        System.out.println("成功删除学生!");
        testForEach();
    }

Map

public Map <String, Course> courses ; // Map is an interface
courses new new = the HashMap <String, Course,> ();
GET (First) obtained by the second first, if not return null, this mapping can be inserted when it sets Note determining
course.put (Id, newcourse) put the method may be added into the
traversal methods

  public void testKeySet() {
        //通过 keySet 方法,返回 Map 中的所有键的 Set 集合
        Set<String> keySet = courses.keySet();
        //遍历 keySet,取得每一个键,在调用 get 方法取得每个键对应的 value
        for(String crID: keySet) {
            Course cr = courses.get(crID);
            if(cr != null){
                System.out.println("课程:" + cr.name);
            }
        }
    }
public void testEntrySet() {
        //通过 entrySet 方法,返回 Map 中的所有键值对
        Set<Entry<String,Course>> entrySet = courses.entrySet();
        for(Entry<String,Course> entry: entrySet) {
            System.out.println("取得键:" + entry.getKey());
            System.out.println("对应的值为:" + entry.getValue().name);
        }
    }

courses.remove (ID) deletion map
courses.put (crID, newCourse); modify the original map corresponding to the CRID

abnormal

异常通常有四类:

Error:系统内部错误,这类错误由系统进行处理,程序本身无需捕获处理
Exception:可以处理的异常
RuntimeException:可以捕获,也可以不捕获的异常
继承 Exception 的其他类:必须捕获,通常在 API 文档中会说明这些方法抛出哪些异常
平时主要关注的异常是 Exception 下的异常,而 Exception 异常下又主要分为两大类异常,一个是派生于 RuntimeExcption 的异常,一个是除了 RuntimeExcption 体系之外的其他异常。

RuntimeExcption 异常(运行时异常)通常有以下几种:

错误的类型转换
数组访问越界
访问 null 指针
算术异常
一般来说,RuntimeException 都是程序员的问题。

非 RuntimeException(受查异常)一般有:

打开一个不存在的文件
没有找到具有指定名称的类
操作文件异常
受查异常是编译器要求必须处理的异常,必须使用try catch处理,或者向上抛出,给上层处理

throw new exception name ()

throws 声明异常
throws 用于声明异常,表示该方法可能会抛出的异常。如果声明的异常中包括 checked 异常(受查异常),那么调用者必须处理该异常或者使用 throws 继续向上抛出。throws 位于方法体前,多个异常使用,分割。

修改/home/project/下的ThrowsTest.java

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ThrowsTest {

    public static void main(String[] args) throws FileNotFoundException {
        //由方法的调用者捕获异常或者继续向上抛出
        throwsTest();

    }

    public static void throwsTest() throws FileNotFoundException {
        new FileInputStream("/home/project/shiyanlou.file");
    }
}

For the above statement block composed of three words, try statement block is essential, catch, and finally block can select one or all selected according to the situation. You can put statements errors may occur or problems into the try block, the statement will be executed after an exception into the catch block, a finally block and placed inside the statement, regardless of whether an exception occurs, they will be carried out.
the try
the catch () {} // trilogy, the catch brackets which can put an exception object, call the object's braces printStackTrace
exception call stack: main call f, f calling g, g throws an exception, then can pst the output of this circuit

Can put a lot of catch in a try in the different exception eleven captured, according to types of abnormalities can all capture

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class MultipleCapturesDemo {
    public static void main(String[] args) {
        try {
            new FileInputStream("");
        } catch (FileNotFoundException e) {
            System.out.println("IO 异常");
        } catch (Exception e) {
            System.out.println("发生异常");
        }
    }
}

finally

Custom exception

Exception or integrated so long as it can subclasses

// MyAriException.java
public class MyAriException extends ArithmeticException {
    //自定义异常类,该类继承自ArithmeticException

    public MyAriException() {

    }
    //实现默认的无参构造方法

    public MyAriException(String msg) {
        super(msg);
    }
    //实现可以自定义输出信息的构造方法,将待输出信息作为参数传入即可
}

添加一个ExceptionTest类作为测试用,在该类的main()方法中,可以尝试使用throw抛出自定义的异常。

代码片段如下:

// ExceptionTest.java
import java.util.Arrays;

public class ExceptionTest {
    public static void main(String[] args) {
        int[] array = new int[5];
        //声明一个长度为5的数组

        Arrays.fill(array, 5);
        //将数组中的所有元素赋值为5

        for (int i = 4; i > -1; i--) {
            //使用for循环逆序遍历整个数组,i每次递减

            if (i == 0) {
            // 如果i除以了0,就使用带异常信息的构造方法抛出异常

                throw new MyAriException("There is an exception occured.");
            }

            System.out.println("array[" + i + "] / " + i + " = " + array[i] / i);
            // 如果i没有除以0,就输出此结果
        }
    }
}

Lambda

interface an interface, which put some function prototype (function name Operation), the equation defines the interface
(parameter list) -> expression / braces + return

public class LamdbaTest {
    public static void main(String args[]){
        LamdbaTest tester = new LamdbaTest();

          // 带有类型声明的表达式
          MathOperation addition = (int a, int b) -> a + b;

          // 没有类型声明的表达式
          MathOperation subtraction = (a, b) -> a - b;

          // 带有大括号、带有返回语句的表达式
          MathOperation multiplication = (int a, int b) -> { return a * b; };

          // 没有大括号和return语句的表达式
          MathOperation division = (int a, int b) -> a / b;

          // 输出结果
          System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
          System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
          System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
          System.out.println("10 / 5 = " + tester.operate(10, 5, division));

          // 没有括号的表达式            
          GreetingService greetService1 = message ->
          System.out.println("Hello " + message);

          // 有括号的表达式            
          GreetingService greetService2 = (message) ->
          System.out.println("Hello " + message);

          // 调用sayMessage方法输出结果
          greetService1.sayMessage("Shiyanlou");
          greetService2.sayMessage("Classmate");
       }

       // 下面是定义的一些接口和方法

       interface MathOperation {
          int operation(int a, int b);
       }

       interface GreetingService {
          void sayMessage(String message);
       }

       private int operate(int a, int b, MathOperation mathOperation){
          return mathOperation.operation(a, b);
       }
}

# 
只有createNewFile能够成功创建文件
import java.io.*;


public class Fuck {
    
    public static void main(String args[])
    {
        File f1=new File("C:\\Users\\tony\\Desktop\\笔记\\JAVA代码\\1","1.txt");
        File f2=new File(f1,"2.txt");
        try {
            System.out.println(f1.createNewFile());
            
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        File[]files=File.listRoots();
        for(File file:files)
        {
            System.out.println(file);
            if(file.length()>0)
            {
                String[]filenames=file.list();
                for(String filename:filenames)
                {
                    System.out.println(filename);
                }
            }
        }


    }
}
import java.io.*;
public class Fuck
{
    public static void main(String args[])
    {
        try {
            File in = new File("D:\\textbase\\1.txt");
            File out =new File("D:\\textbase\\2.txt");
            FileInputStream fis=new FileInputStream(in);
            FileOutputStream fos=new FileOutputStream(out);
            int c;
            while((c=fis.read())!=-1)
            {
                fos.write(c);
            }
            fis.close();
            fos.close();
            
        }catch(FileNotFoundException e)
        {
            System.out.println("FileStreamtest:"+e);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }   
    }
    ///java要求必须处理IOException,不会出任何错误,但是贼几把麻烦啊啊啊啊啊啊
r:只读,任何写操作都讲抛出 IOException
rw:读写,文件不存在时会创建该文件,文件存在是,原文件内容不变,通过写操作改变文件内容。
rws:打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。
rwd:打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。
import java.io.*;
import java.io.RandomAccessFile;
public class Fuck
{
    public static void main(String args[])
    {
        int arr[]= {1,2,3,44,55};
        try {
            RandomAccessFile randf = new RandomAccessFile("D:/textbase/1.txt","rw");
            for(int i=0;i<arr.length;i++)
            {
                randf.writeInt(arr[i]);
            }
            for(int i=arr.length-1;i>=0;i--)
            {
                randf.seek(i*4L);
                System.out.println(randf.readInt());
            }
            randf.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
import java.io.*;
import java.io.RandomAccessFile;
import java.nio.file.*;//只import nio.*是没有用的
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class Fuck
{
​   public static void main(String args[])
​   {
​       
        try {
            Files.copy(Paths.get("D:/textbase/1.txt"),Paths.get("D:/textbase/2.txt"),StandardCopyOption.REPLACE_EXISTING);
            
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
import java.io.*;
import java.io.RandomAccessFile;
import java.nio.file.*;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class Fuck
{
    public static void main(String args[])
    {
        
        try {
//这里就改了一个move,把1.txt重命名后移动到另一个区域            Files.move(Paths.get("D:/textbase/1.txt"),Paths.get("2.txt"),StandardCopyOption.REPLACE_EXISTING);
            
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
删除文件的三种方法
//删除文件,文件必须存在,否则抛出异常
            Files.delete(Paths.get("/home/project/3.txt"));
            //删除文件,返回是否删除成功 即使文件不存在,也不会保存,直接返回false
            System.out.println(Files.deleteIfExists(Paths.get("/home/project/3.txt")));
            //或者使用File类的delete方法
            File file = new File("/home/project/4.txt");
            System.out.println(file.delete());
File file=new File("1.txt");
        System.out.println("文件或者目录名:" + file.getName());
        System.out.println("绝对路径:" + file.getAbsolutePath());
        System.out.println("父目录:" + file.getParent());
        System.out.println("文件路径:" + file.getPath());
        //判断文件是否是目录
        if (file.isDirectory()) {
            //打印目录中的文件
            Arrays.stream(file.list()).forEach(System.out::println);
        }
        System.out.println("是否隐藏:" + file.isHidden());
        System.out.println("是否存在:" + file.exists());
文件或者目录名:1.txt
绝对路径:C:\Users\tony\Desktop\笔记\JAVA代码\1\1.txt
父目录:null
文件路径:1.txt
是否隐藏:false
是否存在:false        
public class Fuck
{
    public static void main(String args[])
    {
        readDir(new File("C:\\Users\\tony\\Desktop\\笔记"),0);
        
    }
    static void readDir(File file,int k)
    {
        if(file==null)
            return ;
        if(file.isDirectory())
        {
            File files[];
            if((files=file.listFiles())!=null)
            {
                for(File file1:files)
                {
                    readDir(file1,k+1);
                }
            }
        }
        else {
            for(int i=0;i<k;i++)
            {
                System.out.print("  ");
            }
            System.out.println(file.getName());
        }
    }
}

I 流

Byte stream: expressed in bytes to read or write information from the stream the stream. Commonly used to read binary data.
Character stream: Unicode characters to a unit to read or write information from the stream the stream.

public class Fuck
{
    public void copy(InputStream in,OutputStream out)throws IOException
    {
        byte[]buf =new byte[4096];
        int len=in.read(buf);
        while(len!=-1)
        {
            out.write(buf,0,len);
            len=in.read(buf);
        }
    }
    public static void main(String args[])throws IOException
    {
        Fuck f = new Fuck();
        System.out.println("please in put a char");
        f.copy(System.in,System.out);
    }
    
}

Byte stream can be simulated more

使用缓冲流提高效率
public class Fuck
{
    public static void main(String args[])
    {
        try
        {
            FileInputStream fis = new FileInputStream("2.txt");
            InputStreamReader dis = new InputStreamReader(fis);
            BufferedReader reader=new BufferedReader(dis);
            String s;
            while((s=reader.readLine())!=null)
            {
                System.out.println("read"+s);
            }
            dis.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

IO collection skip some of the content

JDBC

MYsql school to learn
destined not all completion ah

Regular expressions can not learn

Swing

package Fuck;

import javax.swing.JFrame;

the extends JFrame class Window {public
// here to make our own MySwingWindow by JFrame class inherits properties and methods has the form

public Window(){
    //在窗体的构造方法中设置窗体的各项属性

    super();
    //使用 super() 来引用父类的成分,用 this 来引用当前对象

    this.setSize(400, 300);
    //设置窗体的大小

    this.getContentPane().setLayout(null);
    //返回此窗体的 contentPane 对象,设置其布局
    //这一句不太懂的话也不用担心,先写着

    this.setTitle("My First Swing Window");
    //设置窗体的标题
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Window window = new Window();
    //声明一个窗体对象 window

    window.setVisible(true);
    //设置这个窗体是可见的
}

}
package Fuck;

import java.awt.;
import javax.swing.
;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

the extends JFrame class Window {public
Private the JLabel M1;
Private JTextField M2;
Private JButton M3;
// here to make our own MySwingWindow have some form of properties and methods class through inheritance JFrame

public Window(){
    //在窗体的构造方法中设置窗体的各项属性

    super();
    //使用 super() 来引用父类的成分,用 this 来引用当前对象

    this.setSize(400, 300);
    //设置窗体的大小

    this.getContentPane().setLayout(null);
    //返回此窗体的 contentPane 对象,设置其布局
    //这一句不太懂的话也不用担心,先写着

    this.setTitle("My First Swing Window");
    //设置窗体的标题
    this.add(getJLabel(),null);
    this.add(getJTextField(),null);
    this.add(getJButton(),null);
    
}
private JLabel getJLabel()
{
    if(m1==null)
    {
        m1 = new JLabel();
        m1.setBounds(5,10,250,30);
        //x y width height
        m1.setText("Fuck you leather man");
    
    }
    return m1;
}
private JTextField getJTextField()
{
    if(m2==null)
    {
        m2 = new JTextField();
        m2.setBounds(5,45,200,30);
        //x y width height
        m2.setText("Fuck you sb");
    
    }
    return m2;
}
private JButton getJButton()
{
    if(m3==null)
    {
        m3 = new JButton();
        m3.setBounds(5,80,300,40);
        m3.setText("Click me and I will hit your ass!");
        //设定它要显示的字符串
        m3.addActionListener(new ActionListener() {
            //为其添加一个事件监听,从而使这个按钮可以响应用户的点击操作
            //ActionListener是用于接收操作事件的侦听器接口。
            //对处理操作事件感兴趣的类可以实现此接口,而使用该类创建的对
            //可使用组件的 addActionListener 方法向该组件注册。
            //在发生操作事件时,调用该对象的 actionPerformed 方法。

            public void actionPerformed(ActionEvent e) {
                //该方法会在发生操作时被调用,我们要做的事情就可以写在这里面
                //比如我们下面要做的事情就是改变之前两个控件里面的文字颜色和背景色

                m1.setForeground(Color.RED);
                //设置此组件的前景色。

                m2.setBackground(Color.BLUE);
                //设置此组件的背景色。
            }
        });
    }




return m3;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Window window = new Window();
    //声明一个窗体对象 window

    window.setVisible(true);
    //设置这个窗体是可见的
}

}

Guess you like

Origin www.cnblogs.com/Tony100K/p/11608379.html