Learning Java 8 Syntax (Java in a Nutshell 6th)

  1. Java is using Unicode set
  2. Java is case sensitive
  3. Comments, C/C++ style
  4. 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
  5. Currency symbols are used in generated codes, avoid using these symbols can prevent collisions with automatically generated symbols
  6. CJK glyphs can be used as identifiers
  7. Punctuations: seperators (){}[]... @ :: ; ,. operators + - * / % & | ^ << >> >>> += -= *= /= %= &= |= ^= <<= >>= >>>= = == != < <= >= ! ~ && || ++ -- ?: ->
  8. Types: boolean 1b, char 16b, byte 8b, short 16b, int 32b, long 64b, float 32b, double 64b
  9. Java thought accept char type as UTF-8, internally as fixed-16bits wide
  10. \xxx (discouraged ASCII) \uxxxx (encouraged Unicode) \377 \u0020
  11. 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
  12. Java String can include all the escape texts within double quotes "'This' is a String!" is Okay
  13. integer types are signed and no unsigned integer types as C/C++
  14. To specify 1.0 as a float type, add 'f' as 1.0f, otherwise it's a double
  15. Float arithmatics never thows exceptions, because /0.0 is defined as NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN(when 0.0/0.0), not int
  16. boolean cannot convert and be converted to from byte short char int long float double
  17. skipped instanceof operator, next time take a good look at it
  18. → lambda exp.
  19. for(var:iterable) labeled for, break label, continue label  
    1. int[] p = new int[]{2,3,5,7,11,13,17,19};
      for(int n:p)
      system.out.println(n);

        

    2. foreach will not tell the offset where it is
  20. throw, try..catch..finally
  21. 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
  22. use synchronized(exp){statements} to prevent multithread corruption in exp where doing statements can cause corruption. exp is an obj. or array
  23. 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)
  24. C style variable-length argument list (treat ... as array, converse is not true)

    1.   
      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;
      }
  25. in C++, string, in Java, String, using '+' frequently
  26. in C/C++, NULL, in java, null
  27. array init at runtime, like C++
  28. copying array, arrays are all Cloneable, use .clone() method to shallow copy
    1.   
       int[] data =  {1, 2, 3};
      int[] copy = (int[]) data.clone();
  29. System.arrayCopy(src,sOff,dest,dOff,size); same as .clone(), except that it is realized in JNI, and faster a bit
  30. java.util.Arrays class contains a number of static methods, heavily overloaded, sort(), binarySearch(), equals(), Arrays.toString(), deepEquals(), deepHashCode(), deepToString()
  31. int[][][] = new int[2][][] ✅
  32. 5 ref types: class, array, interface, enumerated, annotation
  33. 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
  34. .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()
  35. packages: collection of classes, interfaces, ref types. Group related classes and define the namespace for the classes
  36. packages: java.util, java.lang, java.io, java.net, java.lang.reflect, java.util.regex, classes: java.lang.String
  37. import static java.util.Arrrays.sort actually import more than more method
  38. Java do not have the virtual keyword,
  39. 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

    1.   
      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()
      }
      }
  40. if need to invoke overridden functions or hidden variables & class functions, use super.blabla, remember that super.super.blabla is not legal
  41. 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
  42. Java packages are not nested, so java.a.b package is different from java.a package, they may be actually un-related
  43. protected fields is visible to every class in the same package, same type instance can see each other's protected fields
  44. Every instance of subclass does include a complete instance of the superclass
  45. public: used for API of the class
  46. protected: used for fields & methods to be inherited from different packages
  47. default: fields & methods used inside this package, cooperating other classes in the package
  48. private: fields & methods used only inside class
  49. primitives & object refs: 8 non-ref as primitives
  50. Java: pass-by-value
  51. all classes inherited from java.Lang.Object, with 5 functions:
    1. toString(): return the class name and 0xXX representation of hashCode() of the object (instance function) .. not very useful
    2. equals(): an overrideable function when comparing two objects
    3. 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()
    4. Comparable::compareTo(), defined in java.lang. Comparable interface other than Object. return negtive/0/positive
    5. 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
  52. interfaces are collection of abstract methods without body; however, abstract classes are collection of methods with some no-body, some realized
  53. 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
  54. singleton pattern, private init, private expr, public getInst() to check expr & init
  55. while using unicode as parameter method names is okay, cases are rare
  56. use @ to add compile-time info
  57. 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
  58. in java.util, lists based on arrays, linked lists, maps sets based on hash tables or binary-trees, Iterator, Iterable
  59. new a hash set, Collection<String> c = new HashSet();  Map<short,int> m = new TreeMap(); Collection<SelfDefinedClass> sdc = new LinkedList();
  60. Collection.add(), .remove(), .clear(), .retainAll(), .removeAll(), .addAll(), .size(), .contains(), .containsAll()
  61. iterator in List: 
    1.   
      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());
      }
  62. interface iterator & iterable, next() has 2 functions, 1 advances through the collection & return the head value of the collection
    1.  public interface Iterator<E> {  
      boolean hasNext();
      E next();
      void remove();
      }
      public interface Iterable<E> {
      java.util.Iterator<E> iterator();
      }
  63. random access to lists: implements the RandomAccess marker interface, test for this interface with instanceof if to ensure enough rights: (ArrayList is instanceof RandomAccess)
    1.  // 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);
  64. Do not use vector & stack class, they are legacy classes
  65. some methods used in Map: .get(), .put(), .remove(), .putAll(), containsKey(), containsValue(), .keySet(), .values(), .entrySet(), .retainAll(), .clear(), .size(), .isEmpty(), .equals(empty)
  66. Sets, Lists, Maps, Queues
  67. Collections.emptySet(), Collections.emptyList(), Collections.emptyMap(), Collections.nCopies(10,0)
  68. set/list.toArray(), Arrays.asList(), Arrays.sort(), .Arrays.binarySearch()[must sort() before using it], Arrays.fill()
  69. String.valueOf(), String operator+, String's immutability, in order to append, create StringBuilder instance
  70. 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
  71. regexs: P273
    1. Learning Java 8 Syntax (Java in a Nutshell 6th)
    2. // 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());
  72. 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
  73. do not use java.util.Date,  a new package java.time .chrono, .format, .temporal, .zone
  74. nanosecond is the most precisely java can represent, time is long(64bit)
  75. java.time.Duration class
  76. Java IO: File class, represent files/directories, File f = new File(dir, "file"); File.renameTo(dir,"file");
  77. 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()
  78. Use FileInputStream to read file: InputStream is = new FileInputStream("file"); is.read(dest);
  79. Java NetWorking: java.net, javax.net.ssl, URL class, support http://, ftp://, file://, https:// to be determined, download a particular URL:
    1.  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();
      }
  80. request methods defined by HTTP: GET, POST, HEAD, PUT, DELETE, OPTIONS, TRACE
  81. search function to find news about java:
    1.  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);
      }
      }
  82. 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.
  83. 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
  84. Class<?> c = o.getClass(); return the object o's Class, because getClass() is public method, same as ClassName.class;
  85. use .class to find Deprecated methods from certain class:
    1.  Class<?> clz = getClassFromDisk();
      for (Method m : clz.getMethods()) {
      for (Annotation a : m.getAnnotations()) {
      if (a.annotationType() == Deprecated.class) {
      System.out.println(m.getName());
      }
      }
      }
  86. use .getSuperclass() to find common ancestor of 2 classes:
    1.  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;
      }
  87. .class file format if ack by JVM: (magic number: CafeBabe)
    1.  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
  88. javap can be used to comprehend .class files
  89. Constant pool is designed so that the bytecode can refer to them by index
  90. phase of class loading: Loading-Verification-Prepare|Resolve-Initialization
  91. Only class can start a new process and execute
  92. 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
  93. .defineClass(), .loadClass()
  94. 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
  95. create reflective framework dealing only with the cases that are immediately applicable rather than to try to account for all the possible circumstances
  96. Java's Reflection API is often the only way to deal with dynamically loaded code, some setbacks:
    1.  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.
  97. non-public methods: instead of Method(), use getDeclaredMethod(), and then use setAccessible() to allow it to be executed
  98. last piece of Java Reflection is dynamically created proxies, classes extends from java.lang.reflect.Proxy,
  99. 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);
  100. after getting handles by calling MethodHandles.lookup(), time to invoke it- (MethodType)l.invoke(args) & (MethodType)l.invokeExact(args)
  101. Nashorn-a new JS implementation that runs on JVM, comformance to JS ECMA spec.
  102. 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
  103. motivation? : 1. help JS developers to discover power of JVM; 2. help strengthen JS language
  104. Using Java classes in JS: 
    1.  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
  105. foreach in JS: for each (js in jsArgs){print(js);}
  106. Platform tools & profiles: 
    1. javac java jar javadoc jdeps jps jstat jstatd jinfo jstack jmap javap
  107. jar files are ZIP format files that contain Java classes, resources, and metadata usually, jar 5 operations - create, update, index, list, extract-cuitx
  108. javadoc produces documents from reading java source files
  109. jdeps- static analysis tool for analyzing the dependencies of packages or classes, by calling jdeps com.me.MyClass
  110. 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).

  111. 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
  112. jinfo <pid>|<core file>: display systme properties and JVM options
  113. jstack <pid> produces a stack trace for each Java thread in the process
  114. jmap <process>: mem allocs of a certain Java process
  115. javap: disassembler
  116. Compact profiles:
    1. • 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
    2. • 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
    3. • 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
  117. Done.
上一篇:Django学习笔记(现学现写,实时更新)


下一篇:(jms)ActiveMQ 安装配置.