Java 学习笔记
Substring 方法
- String substring(int beginIndex, int endIndex)
- String substring(int beginIndex)
注意 endindex 是 exclusive 的,实际 substring 取 beginIndex 到 endIndex - 1。
e.g.:
String s1 = "abcde";
s2 = s1.substring(1); // "bcde"
s2 = s1.substring(2, 4); // "cd"
s2 = s1.substring(2, 5); // "cde"
s2 = s1.substring(2, 6); // StringIndexOutOfBoundException, 6 > s1.length()
s2 = s1.substring(2, 2); // ""
Compare 方法
- boolean endsWith(String suffix)
- boolean startsWith(String prefix)
- int compareTo(String anotherString)
This method is to compare two strings lexicographically, based on Unicode value of each character in the string. ("abc" < "abcd", "abc" < "abd", "abc" < "b').
It returns an integer indicating whether this string is greater than (result > 0), equal to (result = 0), or less than (result < 0) the argument.
To be more specific, it returns the difference of the lengths of the strings, that is, the value this.length() - anotherString.length().
e.g.:
System.out.println("abc".compareTo("abc")); // 0
System.out.println("abc".compareTo("abd")); // -1
System.out.println("ab".compareTo("abcd")); // -2
- int compareIgnoreCase(String str)
- boolean equals(Object anObject)
- boolean equalsIgnoreCase(String anotherString)
String 的其他重要方法
具体看 java doc。
-
String[] split(String regex)
-
String trim() It returns a string whose value is this string, with any leading and trailing whitespace removed.
-
String toLowerCase()
-
String toUpperCase()
-
int indexOf(int ch)
-
int lastIndexOf(int ch)
-
String replace(char oldChar, char newChar) ...
StringBuilder
同样具体看 java doc。
- append()
- insert()
- delete()
- deleteCharAt(int index)
- reverse()
- replace(int start, int end, String str)
- setLength()
StringBuilder和StringBuffer的区别
- They do exactly the same thing
- StringBuffer is thread-safe, each of the methods are synchronized
- StringBuilder is not thread-safe, it is intended to be used in single thread environment.
Number and Strings Conversion
- Number to Strings:
int i = 0;
- String s = i + "";
- String s = String.valueOf(i);
- String s = Integer.toString(i);
- Strings to Number:
String s = "11"
- Integer.valueOf(s);
- Integer.parseInt(s);
Integer and Character Conversion
- char to int
- int i = c - '0' (interpret the content of the char)
- int i = (int) c (only care about the index of the char in ASCII table)
- int to char
- char c = '0' + i (convert a digit into its string representation)
- char c = (char) i (just want to interpret an intefer as ASCII code)
String Literal
String literal: By literal we mean any number, text, or other information that represents a value. String literal is a series of characters in code that is enclosed in double quotes "abc". 用了双引号,就会涉及到string literal.
**String literal constant pool: ** JVM 维护了一个 string literal pool,用来存储 string literal。
String 是常量;它们的值在创建之后不能更改。因为 String 对象是不可变的,所以可以共享。There is no need for maintaining several copies of String objects with the same literal.
String 有一个 intern 方法。字符串池初始为空,它由类 String 私有地维护。String类自己维护了一个池,把程序中的String对象放到那个池里面,于是我们代码中只要用到值相同的String,就是同一个String对象,节省了空间。Usually compiler and JVM will optimize the number of String objects created, it will maintain an intern area in heap, for the same string literal, it will only have one String object associated.
举例:
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2); // TRUE!!
但是要注意:
String s1 = "abc";
String s2 = new String("abc");
System.out.println(s1 == s2); // FALSE
System.out.println(s1.equals(s2)); // TRUE
(The String objects created with "new" will not use the intern pool)
Polymorphism
A call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
Example:
Employee e1 = new Programmer(...);
e1.calculateSalary(0.95);
Employee e2 = new Manager(...);
e2.calculateSalary(0.85);
Override vs. Overload
Both are ways to realize polymorphism.
Override is when you redefine a method that has been defined in a parent class using the same signature. Resolved at runtime.(运行时的多态性)
Overload is when you define two methods with the same name, in the same class, distinguished by their different signatures. Resolved at compile time. (编译时的多态性)
** Constructor cannot be inherited, thus it cannot be overrided, but it can be overloaded.
Interface vs. Abstract Class
抽象类和接口都不能够实例化,但可以定义抽象类和接口类型的引用。
A class must be declared abstract when it has one or more abstract methods. A method is declared abstract when it has a method heading, but no body - which means that an abstract method has no implementation code inside like normal methods do.
An interface differs from an abstract class that has only abstract methods. A class can only derive from one class, but it can implement multiple interfaces.
Q: 抽象类和接口的区别?
- 抽象类中可以定义构造器,可以有抽象方法和具体方法;接口比抽象类更加抽象,接口中不能定义构造器而且其中的方法全部都是抽象方法。
- 抽象类中的成员可以是private、默认、protected、public的;而接口中的成员全都是public的。
- 抽象类中可以定义成员变量,而接口中定义的成员变量实际上都是常量。
- 有抽象方法的类必须被声明为抽象类,而抽象类未必要有抽象方法。
Q: When to use abstract class? Interface?
To use abstract class:
- Plan on using inheritance, since it provides a common base class implementation to derived classes.
- Want to be able to declare non-public members. In an interface, all methods must be public.
To use interface:
- When you think that the API will not change for a while
- When you want to have something similar to multiple inheritance, since you can implement multiple interfaces.
Access Modifier
public - protected - no modifier(default) - private
- public: everyone can access
- protected: only my children and same package can access
- default: only the same package can access
- private: only myself can access
Exceptions
- An exception indicates conditions that a reasonable application might want to catch
- An error indicates serious problems that a reasonable application should not try to catch
Both error and exceptions extend from Throwable: "The Throwable class is the superclass of all errors and exceptions in the Java language."
Exceptions:
- Unchecked exceptions: Runtime Exception (including Arithmetic Exception, ClassCast Exception, Illegal argument exception, IndexOutOfBoundException, NoSuchElement Exception, NullPointerException, etc.) No need to catch if we don't want to.
- Checked Exceptions: Exceptions other than RuntimeException, including IOException, ClassNotFoundException, CloneNotSupportedException. Must use either try/catch blocks or throws.
Difference between Throw and Throws:
- Throw is an action;
- Throws is an indicator of a function