zoeding.com

Java 学习笔记

Substring 方法

  1. String substring(int beginIndex, int endIndex)
  2. 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 方法

  1. boolean endsWith(String suffix)
  2. boolean startsWith(String prefix)
  3. 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

  1. int compareIgnoreCase(String str)
  2. boolean equals(Object anObject)
  3. boolean equalsIgnoreCase(String anotherString)

String 的其他重要方法

具体看 java doc。

  1. String[] split(String regex)

  2. String trim() It returns a string whose value is this string, with any leading and trailing whitespace removed.

  3. String toLowerCase()

  4. String toUpperCase()

  5. int indexOf(int ch)

  6. int lastIndexOf(int ch)

  7. String replace(char oldChar, char newChar) ...

StringBuilder

同样具体看 java doc。

  1. append()
  2. insert()
  3. delete()
  4. deleteCharAt(int index)
  5. reverse()
  6. replace(int start, int end, String str)
  7. setLength()

StringBuilder和StringBuffer的区别

Number and Strings Conversion

int i = 0;

  1. String s = i + "";
  2. String s = String.valueOf(i);
  3. String s = Integer.toString(i);

String s = "11"

  1. Integer.valueOf(s);
  2. Integer.parseInt(s);

Integer and Character Conversion

  1. int i = c - '0' (interpret the content of the char)
  2. int i = (int) c (only care about the index of the char in ASCII table)
  1. char c = '0' + i (convert a digit into its string representation)
  2. 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: 抽象类和接口的区别?

  1. 抽象类中可以定义构造器,可以有抽象方法和具体方法;接口比抽象类更加抽象,接口中不能定义构造器而且其中的方法全部都是抽象方法。
  2. 抽象类中的成员可以是private、默认、protected、public的;而接口中的成员全都是public的。
  3. 抽象类中可以定义成员变量,而接口中定义的成员变量实际上都是常量。
  4. 有抽象方法的类必须被声明为抽象类,而抽象类未必要有抽象方法。

reference

Q: When to use abstract class? Interface?

To use abstract class:

  1. Plan on using inheritance, since it provides a common base class implementation to derived classes.
  2. Want to be able to declare non-public members. In an interface, all methods must be public.

To use interface:

  1. When you think that the API will not change for a while
  2. When you want to have something similar to multiple inheritance, since you can implement multiple interfaces.

reference

Access Modifier

public - protected - no modifier(default) - private

Exceptions

Exceptions:

  1. 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.
  2. Checked Exceptions: Exceptions other than RuntimeException, including IOException, ClassNotFoundException, CloneNotSupportedException. Must use either try/catch blocks or throws.

Difference between Throw and Throws: