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) 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;
          forint i: rest){
              if(i > max) max = i;
          }
          return max;
      }

       

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

       

  38. if need to invoke overridden functions or hidden variables & class functions, use super.blabla, remember that super.super.blabla is not legal
  39. 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
  40. Java packages are not nested, so java.a.b package is different from java.a package, they may be actually un-related
  41. protected fields is visible to every class in the same package, same type instance can see each other's protected fields
  42. Every instance of subclass does include a complete instance of the superclass
  43. public: used for API of the class
  44. protected: used for fields & methods to be inherited from different packages
  45. default: fields & methods used inside this package, cooperating other classes in the package
  46. private: fields & methods used only inside class
  47. primitives & object refs: 8 non-ref as primitives
  48. Java: pass-by-value
  49. 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
  50. interfaces are collection of abstract methods without body; however, abstract classes are collection of methods with some no-body, some realized
  51. 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
  52. singleton pattern, private init, private expr, public getInst() to check expr & init
  53. while using unicode as parameter method names is okay, cases are rare
  54. use @ to add compile-time info
  55. 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
  56. in java.util, lists based on arrays, linked lists, maps sets based on hash tables or binary-trees, Iterator, Iterable
  57. new a hash set, Collection<String> c = new HashSet();  Map<short,int> m = new TreeMap(); Collection<SelfDefinedClass> sdc = new LinkedList();
  58. Collection.add(), .remove(), .clear(), .retainAll(), .removeAll(), .addAll(), .size(), .contains(), .containsAll()
  59. 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());
      }
  60. interface iterator & iterable, next() has 2 functions, 1 advances through the collection & return the head value of the collection
    1. 1 public interface Iterator<E> {  
      2     boolean hasNext();
      3     E next();
      4     void remove();
      5 }
      6 public interface Iterable<E> {
      7     java.util.Iterator<E> iterator();
      8 }
  61. 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. 1 // Arbitrary list we're passed to manipulate
      2 List<?> l = ...;
      3 // Ensure we can do efficient random access. If not, use a copy
      4 // constructor to make a random-access copy of the list before
      5 // manipulating it.
      6 if (!(l instanceof RandomAccess)) l = new ArrayList<?>(l);
  62. Do not use vector & stack class, they are legacy classes
  63. some methods used in Map: .get(), .put(), .remove(), .putAll(), containsKey(), containsValue(), .keySet(), .values(), .entrySet(), .retainAll(), .clear(), .size(), .isEmpty(), .equals(empty)
  64. Sets, Lists, Maps, Queues
  65. Collections.emptySet(), Collections.emptyList(), Collections.emptyMap(), Collections.nCopies(10,0)
  66. set/list.toArray(), Arrays.asList(), Arrays.sort(), .Arrays.binarySearch()[must sort() before using it], Arrays.fill()
  67. String.valueOf(), String operator+, String's immutability, in order to append, create StringBuilder instance
  68. 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
  69. regexs: P273
    1. // 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());
  70. 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
  71. do not use java.util.Date,  a new package java.time .chrono, .format, .temporal, .zone
  72. nanosecond is the most precisely java can represent, time is long(64bit)
  73. java.time.Duration class 
  74. Java IO: File class, represent files/directories, File f = new File(dir, "file"); File.renameTo(dir,"file");
  75. 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()
  76. Use FileInputStream to read file: InputStream is = new FileInputStream("file"); is.read(dest);
  77. Java NetWorking: java.net, javax.net.ssl, URL class, support http://, ftp://, file://, https:// to be determined, download a particular URL:
    1. 1 URL url = new URL("http://www.jclarity.com/");
      2 try (InputStream in = url.openStream()) {
      3     Files.copy(in, Paths.get("output.txt"));
      4 } catch(IOException ex) {
      5     ex.printStackTrace();
      6 }
  78. request methods defined by HTTP: GET, POST, HEAD, PUT, DELETE, OPTIONS, TRACE
  79. search function to find news about java:
    1.  1 URL url = new URL("http://www.bbc.co.uk/search");
       2 String rawData = "q=java";
       3 String encodedData = URLEncoder.encode(rawData, "ASCII");
       4 String contentType = "application/x-www-form-urlencoded";
       5 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       6 conn.setInstanceFollowRedirects(false);
       7 conn.setRequestMethod("POST");
       8 conn.setRequestProperty("Content-Type", contentType );
       9 conn.setRequestProperty("Content-Length",
      10     String.valueOf(encodedData.length()));
      11 conn.setDoOutput(true);
      12 OutputStream os = conn.getOutputStream();
      13 os.write( encodedData.getBytes() );
      14 int response = conn.getResponseCode();
      15 if (response == HttpURLConnection.HTTP_MOVED_PERM
      16         || response == HttpURLConnection.HTTP_MOVED_TEMP) {
      17     System.out.println("Moved to: "+ conn.getHeaderField("Location"));
      18 } else {
      19     try (InputStream in = conn.getInputStream()) {
      20         Files.copy(in, Paths.get("bbc.txt"),
      21             StandardCopyOption.REPLACE_EXISTING);
      22 }
      23 }
  80. 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.
  81. 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
  82. Class<?> c = o.getClass(); return the object o's Class, because getClass() is public method, same as ClassName.class;
  83. use .class to find Deprecated methods from certain class:
    1. 1 Class<?> clz = getClassFromDisk();
      2 for (Method m : clz.getMethods()) {
      3     for (Annotation a : m.getAnnotations()) {
      4         if (a.annotationType() == Deprecated.class) {
      5             System.out.println(m.getName());
      6         }
      7     }
      8 }
  84. use .getSuperclass() to find common ancestor of 2 classes:
    1.  1 public static Class<?> commonAncestor(Class<?> cl1, Class<?> cl2) {
       2     if (cl1 == null || cl2 == null) return null;
       3     if (cl1.equals(cl2)) return cl1;
       4     if (cl1.isPrimitive() || cl2.isPrimitive()) return null;
       5     List<Class<?>> ancestors = new ArrayList<>();
       6     Class<?> c = cl1;
       7     while (!c.equals(Object.class)) {
       8         if (c.equals(cl2)) return c;
       9         ancestors.add(c);
      10         c = c.getSuperclass();
      11     }
      12     c = cl2;
      13     while (!c.equals(Object.class)) {
      14         for (Class<?> k : ancestors) {
      15             if (c.equals(k)) return c;
      16         }
      17         c = c.getSuperclass();
      18     }
      19     return Object.class;
      20 }
  85. .class file format if ack by JVM: (magic number: CafeBabe)
    1.  1 Magic number (all class files start with the four bytes  CA FE BA BE in hexadecimal)
       2 Version of class file standard in use
       3 Constant pool for this class
       4 Access flags ( abstract ,  public , etc.)
       5 Name of this class
       6 Inheritance info (e.g., name of superclass)
       7 Implemented Interfaces
       8 Fields
       9 Methods
      10 Attributes
  86. javap can be used to comprehend .class files
  87. Constant pool is designed so that the bytecode can refer to them by index
  88. phase of class loading: Loading-Verification-Prepare|Resolve-Initialization
  89. Only class can start a new process and execute
  90. 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
  91. .defineClass(), .loadClass()
  92. 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
  93. create reflective framework dealing only with the cases that are immediately applicable rather than to try to account for all the possible circumstances
  94. Java's Reflection API is often the only way to deal with dynamically loaded code, some setbacks:
    1. 1 Heavy use of  Object[] to represent call arguments and other instances.
      2 Also  Class[] when talking about types.
      3 Methods can be overloaded on name, so we need an array of types to distinguish between methods.
      4 Representing primitive types can be problematic—we have to manually box and unbox.
  95. non-public methods: instead of Method(), use getDeclaredMethod(), and then use setAccessible() to allow it to be executed
  96. last piece of Java Reflection is dynamically created proxies, classes extends from java.lang.reflect.Proxy, 
  97. 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);
  98. after getting handles by calling MethodHandles.lookup(), time to invoke it- (MethodType)l.invoke(args) & (MethodType)l.invokeExact(args)
  99. Nashorn-a new JS implementation that runs on JVM, comformance to JS ECMA spec.
  100. 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
  101. motivation? : 1. help JS developers to discover power of JVM; 2. help strengthen JS language
  102. Using Java classes in JS: 
    1.  1 jjs> var clz = Java.type("java.lang.Object");
       2 jjs> var obj = new clz;
       3 jjs> print(obj);
       4 java.lang.Object@73d4cc9e
       5 jjs> print(obj.hashCode());
       6 1943325854
       7 // Note that this syntax does not work
       8 jjs> var obj = clz.new;
       9 jjs> print(obj);
      10 undefined
  103. foreach in JS: for each (js in jsArgs){print(js);}
  104. Platform tools & profiles: 
    1.  javac java jar javadoc jdeps jps jstat jstatd jinfo jstack jmap javap 
  105. jar files are ZIP format files that contain Java classes, resources, and metadata usually, jar 5 operations - create, update, index, list, extract-cuitx
  106. javadoc produces documents from reading java source files
  107. jdeps- static analysis tool for analyzing the dependencies of packages or classes, by calling jdeps com.me.MyClass
  108. 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). 

  109. 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
  110. jinfo <pid>|<core file>: display systme properties and JVM options
  111. jstack <pid> produces a stack trace for each Java thread in the process
  112. jmap <process>: mem allocs of a certain Java process
  113. javap: disassembler
  114. 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
  115. Done.

转载于:https://www.cnblogs.com/sansna/p/5355610.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值