- Java is using Unicode set
- Java is case sensitive
- Comments, C/C++ style
- abstract, const, final, int, public, throw, assert, continue, finally, interface, return, throws, boolean, default, float, long, short, transient, break, do, for, native, static, true, byte, double, goto, new, strictfp, try, case, else, if, null, super, void, catch, enum, implements, package, switch, volatile, char, extends, import, private, synchronized, while, class, false, instanceof, protected, this
- Currency symbols are used in generated codes, avoid using these symbols can prevent collisions with automatically generated symbols
- CJK glyphs can be used as identifiers
- Punctuations: seperators (){}[]... @ :: ; ,. operators + - * / % & | ^ << >> >>> += -= *= /= %= &= |= ^= <<= >>= >>>= = == != < <= >= ! ~ && || ++ -- ?: ->
- Types: boolean 1b, char 16b, byte 8b, short 16b, int 32b, long 64b, float 32b, double 64b
- Java thought accept char type as UTF-8, internally as fixed-16bits wide
- \xxx (discouraged ASCII) \uxxxx (encouraged Unicode) \377 \u0020
- New versions of Unicode standard sized 0x000000~0x10FFFF(21b), use int to hold the codepoint of a supplementary chars, or encode it into a so-called "surrogate pair" of two char values
- Java String can include all the escape texts within double quotes "'This' is a String!" is Okay
- integer types are signed and no unsigned integer types as C/C++
- To specify 1.0 as a float type, add 'f' as 1.0f, otherwise it's a double
- Float arithmatics never thows exceptions, because /0.0 is defined as NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN(when 0.0/0.0), not int
- boolean cannot convert and be converted to from byte short char int long float double
- skipped instanceof operator, next time take a good look at it
- → lambda exp.
- for(var:iterable) labeled for, break label, continue label
-
int[] p = new int[]{2,3,5,7,11,13,17,19};
for(int n:p)
system.out.println(n); - foreach will not tell the offset where it is
-
- throw, try..catch..finally
- synchronized methods in an instance is guaranteed to run 1 at a time; static synchronized methods in a class is also guaranteed to run 1 at a time
- use synchronized(exp){statements} to prevent multithread corruption in exp where doing statements can cause corruption. exp is an obj. or array
- methods specifiers: abstract, final, native(like abstract, used in JNI), (public, private, protected), static, strictfp, synchronized(used to represent a threadsafe method, do not rely on this spec., though it will lock the instance of the class)
-
public static int max(int first, int... rest) {
int max = first;
for(int i : rest) { // legal because rest is actually an array
if (i > max) max = i;
}
return max;
}
//arrays can be pass to the function above,
//however, variable-arguments can not be
//passed to the function below.
public static int max(int first, int[] rest){
int max = first;
for(int i: rest){
if(i > max) max = i;
}
return max;
} - in C++, string, in Java, String, using '+' frequently
- in C/C++, NULL, in java, null
- array init at runtime, like C++
- copying array, arrays are all Cloneable, use .clone() method to shallow copy
-
int[] data = {1, 2, 3};
int[] copy = (int[]) data.clone(); - System.arrayCopy(src,sOff,dest,dOff,size); same as .clone(), except that it is realized in JNI, and faster a bit
- java.util.Arrays class contains a number of static methods, heavily overloaded, sort(), binarySearch(), equals(), Arrays.toString(), deepEquals(), deepHashCode(), deepToString()
- int[][][] = new int[2][][] ✅
- 5 ref types: class, array, interface, enumerated, annotation
- ref in Java is somewhat like ref in C/C++, except that it cannot be converted to int or increment/decrement, in Java, there is no '&', '*', "->", pointer are used as (*pointer) implicitly
- .equals() methods inits as "==" compare, so ref types are possible to get unwanted result, however, String class rewrites .equals() function. if insist, use java.util.Arrays.equals()
- packages: collection of classes, interfaces, ref types. Group related classes and define the namespace for the classes
- packages: java.util, java.lang, java.io, java.net, java.lang.reflect, java.util.regex, classes: java.lang.String
- import static java.util.Arrrays.sort actually import more than more method
- Java do not have the virtual keyword,
-
class A { // Define a class named A
int i = 1; // An instance field
int f() { return i; } // An instance method
static char g() { return 'A'; } // A class method
}
class B extends A { // Define a subclass of A
int i = 2; // Hides field i in class A
int f() { return -i; } // Overrides method f in class A
static char g() { return 'B'; } // Hides class method g() in class A
}
public class OverrideTest {
public static void main(String args[]) {
B b = new B(); // Creates a new object of type B
System.out.println(b.i); // Refers to B.i; prints 2
System.out.println(b.f()); // Refers to B.f(); prints -2
System.out.println(b.g()); // Refers to B.g(); prints B
System.out.println(B.g()); // A better way to invoke B.g()
A a = (A) b; // Casts b to an instance of class A
System.out.println(a.i); // Now refers to A.i; prints 1
System.out.println(a.f()); // Still refers to B.f(); prints -2
System.out.println(a.g()); // Refers to A.g(); prints A
System.out.println(A.g()); // A better way to invoke A.g()
}
} - if need to invoke overridden functions or hidden variables & class functions, use super.blabla, remember that super.super.blabla is not legal
- super() is a method calling the constructor of ancestor, is not same as the super. here used, it can only be used at the very first statement of a constructor
- Java packages are not nested, so java.a.b package is different from java.a package, they may be actually un-related
- protected fields is visible to every class in the same package, same type instance can see each other's protected fields
- Every instance of subclass does include a complete instance of the superclass
- public: used for API of the class
- protected: used for fields & methods to be inherited from different packages
- default: fields & methods used inside this package, cooperating other classes in the package
- private: fields & methods used only inside class
- primitives & object refs: 8 non-ref as primitives
- Java: pass-by-value
- all classes inherited from java.Lang.Object, with 5 functions:
- toString(): return the class name and 0xXX representation of hashCode() of the object (instance function) .. not very useful
- equals(): an overrideable function when comparing two objects
- hashCode(): Whenever override equals, this function must be override as well. Very critical: when two objects equals <=> hashCode()s equals. So two identical objects must be hashCode()-equaled, if need a identity-based hashCode() method, use the static function System.identityHashCode()
- Comparable::compareTo(), defined in java.lang. Comparable interface other than Object. return negtive/0/positive
- clone(): unusual reason: 1. works only if implements java.lang.Cloneable interface(a marker interface which do not define any methods(consider it empty)); 2. protected method, so if need to be cloneable by other classes, implement Cloneable and override the clone() method, making it public
- interfaces are collection of abstract methods without body; however, abstract classes are collection of methods with some no-body, some realized
- using interface: if added new API to interface, every class implements interface need to add implementation of the new API, however, using abstract class: if added new API to abstract class, providing implementation inside the class will not result in adding implementation to every descendant inherits it
- singleton pattern, private init, private expr, public getInst() to check expr & init
- while using unicode as parameter method names is okay, cases are rare
- use @ to add compile-time info
- portable programs do not: use native spec. methods; use Runtime.exec() to execute local commands; use System.getenv()[Enviromental Vars]; use Undocumented as part of Java platform classes; use java.awt.peer package; use standard extensions, if not installed, exit with info; use no hardcoded file or directory names; use no \n \r \r\n, use println() of PrintStream or PrintWriter, see java.util.Formatter's printf() & format() methods for more
- in java.util, lists based on arrays, linked lists, maps sets based on hash tables or binary-trees, Iterator, Iterable
- new a hash set, Collection<String> c = new HashSet(); Map<short,int> m = new TreeMap(); Collection<SelfDefinedClass> sdc = new LinkedList();
- Collection.add(), .remove(), .clear(), .retainAll(), .removeAll(), .addAll(), .size(), .contains(), .containsAll()
- iterator in List:
-
List<String> c = new ArrayList<String>();
// ... add some Strings to c
for(String word : c) {
System.out.println(word);
} //is re-written as:
// Iteration with a for loop
for(Iterator<String> i = c.iterator(); i.hasNext();) {
System.out.println(i.next());
}
//Iterate through collection elements with a while loop.
//Some implementations (such as lists) guarantee an order of iteration
//Others make no guarantees.
Iterator<String> iterator() = c.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
-
- interface iterator & iterable, next() has 2 functions, 1 advances through the collection & return the head value of the collection
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
public interface Iterable<E> {
java.util.Iterator<E> iterator();
}
- random access to lists: implements the RandomAccess marker interface, test for this interface with instanceof if to ensure enough rights: (ArrayList is instanceof RandomAccess)
// Arbitrary list we're passed to manipulate
List<?> l = ...;
// Ensure we can do efficient random access. If not, use a copy
// constructor to make a random-access copy of the list before
// manipulating it.
if (!(l instanceof RandomAccess)) l = new ArrayList<?>(l);
- Do not use vector & stack class, they are legacy classes
- some methods used in Map: .get(), .put(), .remove(), .putAll(), containsKey(), containsValue(), .keySet(), .values(), .entrySet(), .retainAll(), .clear(), .size(), .isEmpty(), .equals(empty)
- Sets, Lists, Maps, Queues
- Collections.emptySet(), Collections.emptyList(), Collections.emptyMap(), Collections.nCopies(10,0)
- set/list.toArray(), Arrays.asList(), Arrays.sort(), .Arrays.binarySearch()[must sort() before using it], Arrays.fill()
- String.valueOf(), String operator+, String's immutability, in order to append, create StringBuilder instance
- String is immutable except that String's hash is not immutable, but it's calc from the other fields of the immutable part, so the String is effectively immutable
- regexs: P273
// Any number of letters, which must all be in the range 'a' to 'j'
// but can be upper- or lowercase
pStr = "([a..jA..J]*)";
p = Pattern.compile(pStr);
m = p.matcher(text);
System.out.print(pStr + " matches " + text + "? " + m.find());
System.out.println(" ; match: " + m.group());
- representing Integer Types in Java: if byte type, 0bXXXX_XXXX, functions: Math.abs(), .max(), .min(), .floor(), .pow(), .exp(), .log(), .log10(), Math.random(), the built-in pseudo random number gen is not very complicated
- do not use java.util.Date, a new package java.time .chrono, .format, .temporal, .zone
- nanosecond is the most precisely java can represent, time is long(64bit)
- java.time.Duration class
- Java IO: File class, represent files/directories, File f = new File(dir, "file"); File.renameTo(dir,"file");
- File class cannot read file directly, .canExecute(), .canRead(), .canWrite(), .setReadOnly(), setExecutable(), .setReadable(), .setWritable(), .getAbsoluteFile(), .getCanonicalFile()[analyze link path to real path], .getParent(), .getName(), .toURI(), .delete(), setLastModified(), File.createTempFile(), .deleteOnExit(), dir.list(), .listFiles()
- Use FileInputStream to read file: InputStream is = new FileInputStream("file"); is.read(dest);
- Java NetWorking: java.net, javax.net.ssl, URL class, support http://, ftp://, file://, https:// to be determined, download a particular URL:
URL url = new URL("http://www.jclarity.com/");
try (InputStream in = url.openStream()) {
Files.copy(in, Paths.get("output.txt"));
} catch(IOException ex) {
ex.printStackTrace();
}
- request methods defined by HTTP: GET, POST, HEAD, PUT, DELETE, OPTIONS, TRACE
- search function to find news about java:
URL url = new URL("http://www.bbc.co.uk/search");
String rawData = "q=java";
String encodedData = URLEncoder.encode(rawData, "ASCII");
String contentType = "application/x-www-form-urlencoded";
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType );
conn.setRequestProperty("Content-Length",
String.valueOf(encodedData.length()));
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write( encodedData.getBytes() );
int response = conn.getResponseCode();
if (response == HttpURLConnection.HTTP_MOVED_PERM
|| response == HttpURLConnection.HTTP_MOVED_TEMP) {
System.out.println("Moved to: "+ conn.getHeaderField("Location"));
} else {
try (InputStream in = conn.getInputStream()) {
Files.copy(in, Paths.get("bbc.txt"),
StandardCopyOption.REPLACE_EXISTING);
}
}
- TCP: Connection based; Guaranteed delievery; Error Checked; 2 classes: Socket, ServerSocket; Postel's Law: Be strict about what you send, and liberal about what you will accept.
- IP is the "lowest common denominator" transport, it's a useful abstraction over the physical network technologies to move bytes from A to B, using IP to transport is not guaranteed, a pack can be lost everywhere along the path, the packs are destined, but have no routine data, it rely on the physical transports along the route to actually deliver the data
- Class<?> c = o.getClass(); return the object o's Class, because getClass() is public method, same as ClassName.class;
- use .class to find Deprecated methods from certain class:
Class<?> clz = getClassFromDisk();
for (Method m : clz.getMethods()) {
for (Annotation a : m.getAnnotations()) {
if (a.annotationType() == Deprecated.class) {
System.out.println(m.getName());
}
}
}
- use .getSuperclass() to find common ancestor of 2 classes:
public static Class<?> commonAncestor(Class<?> cl1, Class<?> cl2) {
if (cl1 == null || cl2 == null) return null;
if (cl1.equals(cl2)) return cl1;
if (cl1.isPrimitive() || cl2.isPrimitive()) return null;
List<Class<?>> ancestors = new ArrayList<>();
Class<?> c = cl1;
while (!c.equals(Object.class)) {
if (c.equals(cl2)) return c;
ancestors.add(c);
c = c.getSuperclass();
}
c = cl2;
while (!c.equals(Object.class)) {
for (Class<?> k : ancestors) {
if (c.equals(k)) return c;
}
c = c.getSuperclass();
}
return Object.class;
}
- .class file format if ack by JVM: (magic number: CafeBabe)
Magic number (all class files start with the four bytes CA FE BA BE in hexadecimal)
Version of class file standard in use
Constant pool for this class
Access flags ( abstract , public , etc.)
Name of this class
Inheritance info (e.g., name of superclass)
Implemented Interfaces
Fields
Methods
Attributes
- javap can be used to comprehend .class files
- Constant pool is designed so that the bytecode can refer to them by index
- phase of class loading: Loading-Verification-Prepare|Resolve-Initialization
- Only class can start a new process and execute
- to apply knowledge of classloading, fully understand java.lang.ClassLoader, which is an abstract class, a fully functional with no abstract methods, the abstract spec. exist to ensure people subclass it if need to use it
- .defineClass(), .loadClass()
- Reflection, to modify their structure & behavior, self-modify, call any previously unknown method, by using Class::newInstance(), cope with code is unkown untill runtime, like, plug-in architecture, debugger, code browser, REPL
- create reflective framework dealing only with the cases that are immediately applicable rather than to try to account for all the possible circumstances
- Java's Reflection API is often the only way to deal with dynamically loaded code, some setbacks:
Heavy use of Object[] to represent call arguments and other instances.
Also Class[] when talking about types.
Methods can be overloaded on name, so we need an array of types to distinguish between methods.
Representing primitive types can be problematic—we have to manually box and unbox.
- non-public methods: instead of Method(), use getDeclaredMethod(), and then use setAccessible() to allow it to be executed
- last piece of Java Reflection is dynamically created proxies, classes extends from java.lang.reflect.Proxy,
- method lookup, performed on class, call Lookup l = MethodHandles.lookup(); include .findVirtual(), .findConstructor(), .findStatic(). MethodHandles are not like Reflection, they have access control, a Lookup object can only return methods that are accissible to the context where the lookup is created, that means no equivalent of setAccessible() in Reflection hack. l.findVirtual(rcvr.getClass(), "hashCode", MethodType);
- after getting handles by calling MethodHandles.lookup(), time to invoke it- (MethodType)l.invoke(args) & (MethodType)l.invokeExact(args)
- Nashorn-a new JS implementation that runs on JVM, comformance to JS ECMA spec.
- non-java language run on JVM, possible because JVM & java have loose ties, some run on JVM more like JS other than Java, Nashorn makes it possible that JS not specifically written for Nashorn can be easily deployed on the platform, unlike JRuby, Nashorn compiles JS to JVM bytecode & executes directly
- motivation? : 1. help JS developers to discover power of JVM; 2. help strengthen JS language
- Using Java classes in JS:
jjs> var clz = Java.type("java.lang.Object");
jjs> var obj = new clz;
jjs> print(obj);
java.lang.Object@73d4cc9e
jjs> print(obj.hashCode()); // Note that this syntax does not work
jjs> var obj = clz.new;
jjs> print(obj);
undefined
- foreach in JS: for each (js in jsArgs){print(js);}
- Platform tools & profiles:
- javac java jar javadoc jdeps jps jstat jstatd jinfo jstack jmap javap
- jar files are ZIP format files that contain Java classes, resources, and metadata usually, jar 5 operations - create, update, index, list, extract-cuitx
- javadoc produces documents from reading java source files
- jdeps- static analysis tool for analyzing the dependencies of packages or classes, by calling jdeps com.me.MyClass
jps provides a list of all active JVM processes on the local machine (or a remote machine, if a suitable instance of jstatd is running on the remote side).
- jstat <pid>, displays basic statistics about a java process, a local process, if remote process, an instance of jstatd should be running on the remmote machine
- jinfo <pid>|<core file>: display systme properties and JVM options
- jstack <pid> produces a stack trace for each Java thread in the process
- jmap <process>: mem allocs of a certain Java process
- javap: disassembler
- Compact profiles:
• java.io
• java.lang
• java.lang.annotation
• java.lang.invoke
• java.lang.ref
• java.lang.reflect
• java.math
• java.net
• java.nio
• java.nio.channels
• java.nio.channels.spi
• java.nio.charset
• java.nio.charset.spi
• java.nio.file
• java.nio.file.attribute
• java.nio.file.spi
• java.security
• java.security.cert
• java.security.interfaces
• java.security.spec
• java.text
• java.text.spi
• java.time
• java.time.chrono
• java.time.format
• java.time.temporal
• java.time.zone
• java.util
• java.util.concurrent
• java.util.concurrent.atomic
• java.util.concurrent.locks
• java.util.function
• java.util.jar
• java.util.logging
• java.util.regex
• java.util.spi
• java.util.stream
• java.util.zip
• javax.crypto
• javax.crypto.interfaces
• javax.crypto.spec
• javax.net
• javax.net.ssl
• javax.script
• javax.security.auth
• javax.security.auth.callback
• javax.security.auth.login
• javax.security.auth.spi
• javax.security.auth.x500
• javax.security.cert• java.rmi
• java.rmi.activation
• java.rmi.dgc
• java.rmi.registry
• java.rmi.server
• java.sql
• javax.rmi.ssl
• javax.sql
• javax.transaction
• javax.transaction.xa
• javax.xml
• javax.xml.datatype
• javax.xml.namespace
• javax.xml.parsers
• javax.xml.stream
• javax.xml.stream.events
• javax.xml.stream.util
• javax.xml.transform
• javax.xml.transform.dom
• javax.xml.transform.sax
• javax.xml.transform.stax
• javax.xml.transform.stream
• javax.xml.validation
• javax.xml.xpath
• org.w3c.dom
• org.w3c.dom.bootstrap
• org.w3c.dom.events
• org.w3c.dom.ls
• org.xml.sax
• org.xml.sax.ext
• org.xml.sax.helpers
• javax.xml.crypto.dsig
• javax.xml.crypto.dsig.dom
• javax.xml.crypto.dsig.keyinfo
• javax.xml.crypto.dsig.spec
• org.ietf.jgss• java.lang.instrument
• java.lang.management
• java.security.acl
• java.util.prefs
• javax.annotation.processing
• javax.lang.model
• javax.lang.model.element
• javax.lang.model.type
• javax.lang.model.util
• javax.management
• javax.management.loading
• javax.management.modelmbean
• javax.management.monitor
• javax.management.openmbean
• javax.management.relation
• javax.management.remote
• javax.management.remote.rmi
• javax.management.timer
• javax.naming
• javax.naming.directory
• javax.naming.event
• javax.naming.ldap
• javax.naming.spi
• javax.security.auth.kerberos
• javax.security.sasl
• javax.sql.rowset
• javax.sql.rowset.serial
• javax.sql.rowset.spi
• javax.tools
• javax.xml.crypto
• javax.xml.crypto.dom
- Done.
C style variable-length argument list (treat ... as array, converse is not true)
inherit class can override instance functions, hide variables & static class functions, where override means instances' functions are replaced whether they are compulsorily converted to their ancestors, and the instances' function use the childs' variables and functions as well. But hide means ancestors' variable and class functions can be referred to when they are compulsorily converted to their ancestors, see the following example