Java Basic Notes (iii)

Source: Internet
Author: User

exception : An abnormal condition that occurs when a program is running
Classification of exceptions:
Throwable:
Error: Wrong. Caused by the system, it is usually the system resource allocation conflict or the system crashes and other reasons.
For programmers, error is not handled.
Exception: Exception. Usually caused by the program, General operations, IO, etc., can be processed

The default is for the JVM to handle exception handling. The way you handle printing exception names, exception information, where an exception occurs when an exception occurs, the program breaks, and the code below the exception is not executed.

      因为大部分异常java内部已经定义好了,所以当发生异常时,系统会自动 创建该异常的对象。因为main方法不能处理该异常,所以抛给了jvm。      jvm默认的处理方式将该异常信息打印 printStackTrace();

Throw: An exception is manually thrown inside the method.
If the exception being thrown is an exception to be inspected, it needs to be declared at the declaration by throws
throw new Exception Class (["Exception information"])
Throws: The method declaration section declares that the method may throw an exception,
Methods that use throws do not handle exceptions, who call who handles
Method Name () throws Exception class List {*
}

Throw + Exception Object
List of throws+ exception classes

After throws throws an exception, the caller must handle:
1) Handling with Try-catch
2) Continue to throw through throws

try{possible exception code (resource allocation)} catch (...) {Code with exception handling} finally{code that executes regardless of whether an exception occurs
(Release Resources)}

  思考:如果try中包含return,finally语句中也包含return,执行顺序? try - catch -finally: 如果try没有异常:try-finally 如果try有异常:try-catch-finally  

--–>finally is always executed

If the try contains return,finally, it is executed before return.

Exception handling: Abnormal, non-inspected exception

If the exception that occurs is runtimeexception or its subclasses, then
1 Throw exception object using throw inside function, without processing, compile can pass
2 throws an exception after a function by throws declaration, without processing, compiled by

Exceptions are divided into two categories: exceptions detected at compile time (checked exceptions), exceptions not detected at compile time (non-checked exceptions runtimeexception and subclasses)

Basic class:
/*
* wrapper class: Byte byte
* Short short
* int Integer
* Long Long
* Char C Haracter
* Float float
* Double Double
* Boolean boolean
* wrapper class, easy to use.
* can be used for conversions between base types and string Types
* string integer.tostring (int i)
* string double.tostring (Double D)
* String converted to base type
* int Integer.parseint ("123")
* Double double.parsedouble ("1.2")
* binary Conversion integer.tohexstring () Integer.tooc Talstring ()
* integer.tobinarystring ()
* Integer.parseint ("," ")
* Boxed: Base type-Reference type
* Unboxing: Reference type-Basic type
*/
Integer i = 10;//Auto Boxing new Integer (ten)
i = i + 100;//First auto unpacking i.intvalue () +100 re-boxed new Integer ()
//Java Default , the -128~127 constant is created in the constant pool
Integer m = 127;
Integer n = 127;
System.out.println (M = = n);//True

    Integer a = 128;    Integer b = 128;    System.out.println(a == b);// false    // 正数的hashCode()就是其本身,long类型可能会不同    System.out.println(a.hashCode());    System.out.println(b.hashCode());    Long l = new Long(12345678900000L);    System.out.println(l.hashCode());

Use of date:
Date date = new Date ();//Get System Current time
SYSTEM.OUT.PRINTLN (date);

    long time = date.getTime();    Date d2 = new Date(time);    // 使用定义好的日期格式化工具类    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);    System.out.println(df.format(date));    // 将字符串转换成Date对象    try {        Date d3 = df.parse("15-03-04");    } catch (ParseException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    // 自定义格式格式化日期和时间    // 注意: 月MM 分 mm 秒:ss 毫秒:SSS    SimpleDateFormat sdf = new SimpleDateFormat("yyy/MM/dd hh:mm:ss:SSS");    System.out.println(sdf.format(new Date()));

use of calendar:
Calendar calendar = Calendar.getinstance ();
int year = Calendar.get (calendar.year);
int month = Calendar.get (calendar.month);
Int week = Calendar.get (Calendar.day_of_week);
SYSTEM.OUT.PRINTLN (year);
string[] months = {"January", "February", "March", "April", "May", "June", "July", "August"};
System.out.println (Months[month]);//0-11
String[] weeks = {"", "Sunday", "Monday", "Tuesday"};
System.out.println (Weeks[week]);
System.out.println (Calendar.get (calendar.day_of_month));
System.out.println (Calendar.get (Calendar.hour_of_day));//24 hours

    String str = String.format("%d年", year);    System.out.println(str);    // %s String %c char %d int %f float double    System.out.println(String.format("%.2f", 10 / 3.0));

StringBuffer:
StringBuffer class: A container of strings, the contents of which can be changed. Thread safety

StringBuilder jdk1.5 Thread is unsafe and highly efficient

Store:
StringBuffer Append ()
StringBuffer Insert (int offset,string s)

Delete:
StringBuffer Delete (int start,int end)
StringBuffer deletecharat (int index)

Modify:
StringBuffer replace (int start,int end,string str)
void Setcharat (int index,char ch)

Get:
char charAt (int index)
int IndexOf ()
int Lashindexof ()

int Length ()

Reverse:
StringBuffer reverse ()

List
List interface: Features: Store objects in order, can be repeated
Added: void Add (int index,object o)
Boolean addall (int index, Collection c)
Delete:
Object Remove (int index)
Modify:
Object set (int index,object O): Returns the original element
Inquire:
Listiterator Listiterator ()
List sublist (int fromindex,int toindex)
Object get (int index)
ArrayList class: The implementation class of the list interface is operated by subscript, similar to an array. Can be thought of as an array of variable-length arrays in order: FIFO First Out

  ListIterator:父接口Iterator  List特定的迭代器,可以镶嵌和向后获取数据,支持增删改的操作  hasNext() next() hasPreivious() previous() previousIndex()      add() set()

Set:
Set interface: unordered (the order of storage is inconsistent with the order of addition). Unable to store duplicate elements

HashSet class: The data structure used is a hash table, the thread is unsafe

保证加入集合的对象的唯一性:    int hashCode()    boolean equals(Object obj)

The process of comparison:
The Hashcode () method of the object is called first, and if the hash value is different, it is added directly to the collection.
If Hashcode () is the same, the Equals () method is called to determine whether the content is the same, or false to indicate that the content is different and added directly to the collection
If true, it cannot be added to the collection

Hashes of the same hash value are not necessarily the same object, and the hash value of the same object must be the same.

Steps:
1) Custom class,
2) Rewrite hashcode (): Custom algorithm
A, eclipse automatic generation
b, usually let the hashcode () of the property and return, the basic type is directly summed, the reference type by calling Hashcode ()
3) override the Equals () method
A, eclipse automatic generation
b, compare the values of the property in turn all equal

TreeSet: The underlying data structure used is a two-fork tree, and threads are unsafe. The objects that are stored in the collection are sorted.
*
* Ensure that the objects that are added to the collection are sortable:
* 1) Let the custom class implement the comparable interface, int compareTo ()
* 2) Custom Comparator:
* Create comparator, implement comparator interface, interface int compare ()
* Pass the Comparer object as a parameter to the constructor of the collection
instance:
Class Dog implements comparable {
Private String name;
private int age;

Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}    Public Dog (String name, int age) {super ();    THIS.name = name; This.age = age;} Public Dog () {super ();} @Overridepublic String toString () {return "Dog [name=" + name + ", age=" + Age + "]";}    @Overridepublic int hashcode () {final int prime = 31;    int result = 1;    result = Prime * result + age;    result = Prime * result + ((name = = null)? 0:name.hashcode ()); return result;}    @Overridepublic boolean equals (Object obj) {if (this = = obj) return true;    if (obj = = null) return false;    if (getclass () = Obj.getclass ()) return false;    Dog other = (dog) obj;    if (age! = Other.age) return false;    if (name = = null) {if (other.name! = null) return false;    } else if (!name.equals (Other.name)) return false; return true;} @Overridepublic int compareTo (Object o) {dog d = (dog) o;    if (This.age < d.age) return-1;    else if (This.age > D.age) return 1; else return This.name.compareTo (d.name); The same age and then continue to compare names}

}

Custom Comparators
Compare names if they are the same, and then sort by age
Class Mycompare implements Comparator {

@Overridepublic int compare(Object o1, Object o2) {    if (!(o1 instanceof Dog))        throw new ClassCastException("类型转换出错");    if (!(o2 instanceof Dog))        throw new ClassCastException("类型转换出错");    Dog d1 = (Dog) o1;    Dog d2 = (Dog) o2;    int n = d1.getName().compareTo(d2.getName());    return n == 0 ? d1.getAge() - d2.getAge() : n;}

}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Basic Notes (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.