Java
- A method's declaration tells the computer what happens if you call the method into action.
- if you give a method the name main, that method is called into action automatically.
- a statement is a direct instruction that tells the computer to do something.
- /** this is a javadoc comment */; you can't nest comments inside one another. Better off using end-of-line(//) comments as tools for experimenting with your code.
- variables vs literals: literals do not change.
- For most programs, just use double.
- Most languages use ASCII, Java uses Unicode.
- Any part of a Java program that has a value is an expression.
- System.out.println() tells the program to display a line break.
- Every Java class is a reference type.
- ClassName variableName;: a variable variableName refers to an instance of class ClassName.
- import static java.lang.System.out; // out.println("blablabla");
- java.util.Scanner 类:
import java.uitl.Scanner; // ... Scanner sc = new Scanner(System.in); int a = sc.nextInt(); String b = sc.next(); // nextDouble(); nextBoolean(); ...
- javax.swing下的JOptionPane:
1 import javax.swing.JOptionPane; 2 //... 3 String username = JOptionPane.showInputDialog("Username:"); 4 String password = JOptionPane.showInputDialog("Password"); 5 // int num1 = Integer.parseInt(JOptionPane.showInputDialog("How many cows?")); 6 // double num2 = Double.parseDouble(JOptionPane.showInputDialog("doble?"));
- In java7, you can use a string as a case of switch statement. But in java 6 you cannot.
- sc.findWithinHorizon(".", 0).charAt(0); 获取字符串首个字符
- File evidence = new File("cookedBooks.txt"); evidence.delete(); // make a File object; java.io.File, delete it.
- Location: /System/Library/Frameworks/JavaVM.framework/Commands
- java.util.Random: http://www.cs.geneseo.edu/~baldwin/reference/random.html
- A child class can't directly reference the private fields of its parent class
- @Override annotation tells java compiler to lookout for a common coding error:
public class PartTimeWithOver extends PartTimeEmployee { @Override public double findPaymentAmount(int hours) { // some code } }
The annotation says “make sure that the method immediately following this annotation has the same stuff (the same name, the same parameters, and so on) as one of the methods in the super- class. If not, then display an error message.”
@Override can watch out for an overriden method, and, from Java 6 onward, you can also use @Override to signal an interface method’s implementation
- Order of setting up a frame:
- Add things to the frame
- pack();
- setVisible(true)
- Classes need to learn:
- java.text.DecimalFormat (its not thread safe, never share decimal format between multiple threads)
- java.lang.System.out
- The DecimalFormat is a subclass of NumberFormat, for programs that involve money, I use NumberFormat
private static NumberFormat currency = NumberFormat.getCurrencyInstance(); // factory method, returns an object out.print(currency.format(rate));
- main(String args[]): command line arguments are actually strings
- In Java, there are two kind of exceptions,
- checked and unchecked:
- The potential throwing of a checked exception must be acknowledged in the code
- The potential throwing of an unchecked exception doesn't need to be acknowledged in the code
- Acknowledging an checked exception in the code means one of two things:
- he statements (including method calls) that can throw the exception are inside a try clause. That try clause has a catch clause with a matching exception type in its parameter list
- The statements(including mehtod calls) that can throw the exception are inside a method that has a throws clause in its header. The throws clause contains a matching exception type
-
Anything that’s a subclass of RuntimeException (or a sub-subclass, sub-sub-subclass, and so on) is unchecked. Any exception that’s not a descendent of RuntimeException is checked
- checked and unchecked:
- try-with-resource(java 7):
private static void customBufferStreamCopy(File source, File target) { try (InputStream fis = new FileInputStream(source); OutputStream fos = new FileOutputStream(target)){ byte[] buf = new byte[8192]; int i; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } } catch (Exception e) { e.printStackTrace(); } }
closable resource will be automatically closed in the try paranthesis
- In java, the default access for a member of a class is package-wide access, while protected member not only can be accessed in the same package, but also can be accessed from subclasses. A protected member is available to subclasses outside the package, but the member is also available to code (subclasses or not) within the member’s package.
- public classes can be referenced from every where in your code, while non-public classes can only assecced in that class's package.
- In command line use:
$ appletviewer [+ xxx.html]
to view java applet
- Checked and Unchecked exception, check this out: http://www.javapractices.com/topic/TopicAction.do?Id=129
- Apache commons: Useful Java library: http://commons.apache.org/
- Eclipse shortcut:
- Generate Element Comment: Option+Command+j
- Import Organization: Shift+Command+o
- Source: Option+Command+s
- Refactor: Option+Command+t
- javadoc: To generate HTML formatted documentation, run the
javadoc
command-line tool on your source files to generate the HTML API files (including indexes):javadoc -d /path/to/output /path/to/*.java
http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html
- In case you didn't know the default java class path includes. If you place jars here they will be found by default:
/Library/Java/Extensions
- Default CLASSPATH: The default value of the class path is ".", meaning that only the current directory is searched.
- The classpath is the connection between the Java runtime and the filesystem. It defines where the interpreter looks for .class files to load. The basic idea is that the filesystem hierarchy mirrors the Java package hierarchy, and the classpath specifies which directories in the filesystem serve as roots for the Java package hierarchy: http://www.ibm.com/developerworks/library/j-classpath-unix/
- compile to specific place:
$ javac -d bin src/com/wei/math/Fraction.java // we are in Project folder // Project has src and bin folder
- ORDER:
public class MTest extends D2{ public static void main(String[] args) { MTest mt = new MTest(); } private static int m = pt("MTest static"); private int ii = pt("before MTest constructor"); } class Root { public Root() { System.out.println("Root "); } private static int i = pt("Root static"); private int ii = pt("before Root constructor"); static int pt(String s) { System.out.println(s); return 47; } } class D1 extends Root { public D1() { System.out.println("D1 "); } private static int i = pt("D1 static"); private int ii = pt("before D1 constructor"); } class D2 extends D1 { public D2() { System.out.println("D2 "); } private static int j = pt("D2 static"); private int ii = pt("before D2 constructor"); } ///:~ /** Output Root static D1 static D2 static MTest static before Root constructor Root before D1 constructor D1 before D2 constructor D2 before MTest constructor */
- Scanner and Readable: http://lihaozy.blog.51cto.com/1112871/285597
- How to sort a Map:
// version 1: SortedSet<String> keys = new TreeSet<String>(map.keySet()); for (String key : keys) { String value = map.get(key); // do something } // version 2: String[] keys = map.keySet().toArray(new String[0]); Arrays.sort(keys); Map<String,String> map2 = new LinkedHashMap<String,String>(); for(String key : keys) { map2.put(key, m1.get(key)); System.out.println(m2); }
// version 3List sortedKeys = newArrayList(yourMap.keySet());
Collections.sort(sortedKeys); - Collections & Collection:
- Interface Collection: Collection is the most basic interface for all collections in Java
- Class Collections: Collections is a utility class providing useful static methods to use on Collection objects.
- How to use toArray():
String[] y = x.toArray(new String[0]);
x is a collection that contains only string
- Arrays.asList: List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
- Sort string of keys, case insensitive: Collections.sort(keys, String.CASE_INSENSITIVE_ORDER);
- An example of writing an iterator:
import java.util.*; class PetSequence { protected Pet[] pets = Pets.createArray(8); // create 8 pets } public class NonCollectionSequence extends PetSequence { public Iterator<Pet> iterator() { return new Iterator<Pet>() { private int index = 0; public boolean hasNext() { return index < pets.length; } public Pet next() { return Pets[next++]; } public void remove() { // not implemented throw new UnsupportedOperationException(); } } } }
- Format specifier: %[argument_index$][flags][width][precision]conversion
- Covariance & Contravariance:
public class Test { public class A {} public class B extends A {} public class C extends B {} public void testCoVariance(List<? extends B> myBlist) { B b = new B(); C c = new C(); myBlist.add(b); // does not compile myBlist.add(c); // does not compile A a = myBlist.get(0); } public void testContraVariance(List<? super B> myBlist) { B b = new B(); C c = new C(); myBlist.add(b); myBlist.add(c); A a = myBlist.get(0); // does not compile } }
- Usually, classes which are collection-like can accept subclasses, and classes which are comparator-like can accept superclasses
- implementing java.lang.Comparable interface:
class Person implements Comparable { private String firstName; private String lastName; private int age; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int compareTo(Object anotherPerson) throws ClassCastException { if (!(anotherPerson instanceof Person)) throw new ClassCastException("A Person object expected."); int anotherPersonAge = ((Person) anotherPerson).getAge(); return this.age - anotherPersonAge; }
public static Comparator FirstNameComparator = new Comparator() { // anonymous class comparator public int compare(Object person, Object anotherPerson) { String lastName1 = ((Person) person).getLastName().toUpperCase(); String firstName1 = ((Person) person).getFirstName().toUpperCase(); String lastName2 = ((Person) anotherPerson).getLastName().toUpperCase(); String firstName2 = ((Person) anotherPerson).getFirstName().toUpperCase(); if (!(firstName1.equals(firstName2))) return firstName1.compareTo(firstName2); else return lastName1.compareTo(lastName2); } };
}
import java.util.Arrays; import java.util.ArrayList; public class Testing { public static void main(String[] args) { Person[] persons = new Person[4]; persons[0] = new Person(); persons[0].setFirstName("Elvis"); persons[0].setLastName("Goodyear"); persons[0].setAge(56); persons[1] = new Person(); persons[1].setFirstName("Stanley"); persons[1].setLastName("Clark"); persons[1].setAge(8); persons[2] = new Person(); persons[2].setFirstName("Jane"); persons[2].setLastName("Graff"); persons[2].setAge(16); persons[3] = new Person(); persons[3].setFirstName("Nancy"); persons[3].setLastName("Goodyear"); persons[3].setAge(69); System.out.println("Natural Order"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons, new LastNameComparator()); System.out.println(); System.out.println("Sorted by last name"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } Arrays.sort(persons); System.out.println(); System.out.println("Sorted by age"); for (int i=0; i<4; i++) { Person person = persons[i]; String lastName = person.getLastName(); String firstName = person.getFirstName(); int age = person.getAge(); System.out.println(lastName + ", " + firstName + ". Age:" + age); } } }
- ulp: unit in the last place or unit of least precision (ULP) is the spacing between floating-point numbers, i.e., the value the least significant digit represents if it is 1
- Comparable & Comparator: http://www.codeproject.com/Articles/566609/Difference-between-Comparator-and-Comparable-in-Ja
- final argument: This declares that the variable passed in cannot be reassigned:
void foo( final String bar ) { bar = something; // wrong! }
- Difference between == and equals() method:
- ==:
- meaning it checks to see if both objects reference the same place in memory
- equals:
- by default, equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.
- ==:
- n
- n
- n
- n
- n
- n
- n
- n
- n
- n
- n