Skip to content

Instantly share code, notes, and snippets.

@ettore26
Last active February 5, 2019 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ettore26/bb3e1a91e7a68bf912105e72633056c2 to your computer and use it in GitHub Desktop.
Save ettore26/bb3e1a91e7a68bf912105e72633056c2 to your computer and use it in GitHub Desktop.

TOPICS TO REMEMBER

Resources

Java Building Blocks

  • primitives:
    • primitives sizes (page 21)
    • primitives can not be assigned null
  • file and organization:
    • multiple classes in same file
    • required java elements order: package somepackage, import someclass, Class SomeClass. Comments anywhere
  • instance and static variables/initializer:
    • instance variables and instance inititalizers run before constructor
    • static variables and static initializers run before any instance member
    • instance and class variables have default values when declared
  • keywords:
    • strictfp and native keywords
  • garbage collection:
    • System.gc();
    • Objects are elegible for GC:
      1. No references pointing to them
      2. Refernces go out of scope.
    • finalize() could run zero or one time.
  • objects vs references

Operators and Statements

  • Operators and assigment:
    • unary, binary, ternary.
    • operators + and += do String concatenation. += take previews value, add new one and changes the reference to the new concatenated value.
    • compound operators (+=, -=, *=, /=) do cast date types implicitly
    • assigment (=) is an expression in and of itself, equal to the value of the assignment (long y = (x=3);)
    • logical operators:
      - &, |, ^ (not short-circuiting)
      - &&, || (short-circuiting)
      
  • Numbers, its wrapper classes, autoboxing and Numeric Promotion Rules (page 55):
    • number literals allowed:
      - hex:        0x1a
      - binary:     0b11010
      - scientific: 1.234e2
      
    • Unary Numeric Promotion (§5.6.1)
    • Binary Numeric Promotion (§5.6.2)
    • Boxing (§5.1.7) and Unboxing (§5.1.8)
    • Assignment Contexts (§5.2):
      • The type of the expression must be converted to the type of the variable.
      • The compile-time narrowing of constant expressions (§15.28) is allowed.
    • Widening (§5.1.2) and Narrowing (§5.1.3) Primitive Conversion:
      • A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.
    • primitive number sizes ():
      1. byte:   8-bit,  from -128                 to 127
      2. short:  16-bit, from -32768               to 32767
      5. char:   16-bit, from 0                    to 65535, that really is from '\u0000' to '\uffff'
      3. int:    32-bit, from -2147483648          to 2147483647
      4. long:   64-bit, from -9223372036854775808 to 9223372036854775807
      
      5. float:  32-bit, IEEE 754
      6. double: 32-bit, IEEE 754
      
      It Does really interfier in the Assignment Contexts (§5.2) 
      e.g. char has a bigger positive range than short even though have the same size. 
      
  • switch statement:
    • switch statement support values tha can be promoted by int (byte, short, char. No: float, double, long), they're wrapper classes (Byte, Short, ...) , string and Enums
    • in the switch statement the data type for the case statement value must be literal, enum constant or final constant varible.
  • labeled statemets:
    • labeled statemets can appear anywere inside a block and can have wthin break and continue statemts
    • labeled statements are usefull for breaking all nested loops from the innermost

Core Java APIs

  • String and StringBuilder:
    • String.concat() does exactly the same thing as the + sing
    • String litterals use String pool (are interned) by default (no: Object.toString(), nor: new String())
    • String literals conctenation are interned (e.g. "abc" + "def" == "abcdef")
    • Strings out of the string pool are garbage collected as any other Object
    • someString.intern() force someString to use the pool
    • when String is evaluated at runtime rather than at compiled time String is not interned (e.g. " something".trim() if in this case the method trim don't act on the String the String is interned e.g. "something".trim())
    • StringBuilder does the same as StringBuffer but the later is thread safe
    • Strings are inmutable and StringBuilders are not
    • String implemented method 'equals' but StringBuilder didn't
  • Array, varargs and List:
    • ways to create and Array:
      1. int[] nums = new int[3]
      2. int[] nums = new int[] {1, 2, 3}
      3. int[] nums = {1, 2, 3}
    • Arrays as instance and class variables have default values when decalred
    • java.util.Arrays.toString(someArray) prints Arrays nicely
    • someArray.length gives you allocated slots (not necessarily with data)
    • Arrays as any object inherit from Object class all it's methods plus a method clone and a final field lenght
    • the Arrays class provide some useful static methods:
      1. equals
      2. sort (changes the original array and returns void)
      3. binarySearch (needs to be sorted; when not found returns (-(insertion point index) - 1))
      4. copyOf (param1: array; param2: new length)
      5. ...
    • varargs (someObject ...) are used as normal arrays
    • ArraysList methods:
      1. add (E parameter returns boolean, (int, E) prameters return void)
      2. remove (E parameter return boolean, int parameter retruns E)
      3. set ((int, E) parameters returns E), 
      4. isEmpty
      5. size
      6. clear (no parameters retruns void)
      7. contains
      8. equals
    • array and List conversions:
      1. list.toArray() (returns Object)
      2. list.toArray(new someObject[0]) (returns someObject, the '[0]' doesn't affect the actual list size unless '[0]' is more than 0)
      3. Arrays.asList(array) (in this case the List and the array will hold the same reference and it will have a fixed size (could throw UnsupportedOperationException))
    • Collections.sort(List)
    • in classes that implement java.util.Iterator you can use values.iterator(); to iterate over Lists values (no need of: values.get(i))
  • wrapper classes:
    • WRAPPERCLASS.parsePRIMITIVE(someString) (.parseInt, .parseBoolean, ...) and WRAPPERCLASS.valueOf(someString) return int and Integer respectively (doesn't really matter do to autoboxing). Character wrapper clase doesn't have parseChar nor valueOf
  • java.time:
    • LocalDate, LocalTime, LocalDateTime: do not contain time zones (ZonedDateTime handles them)
    • LocalDate, LocalTime, LocalDateTime, Period, Duration and DateTimeFormatter: are immutable, have private constructors, have static methods.
    • date and time classes's static methods:
      LocalDateTime, LocalDate, LocalTime    -->    of(), now(), from(), parse() 
      Duration                               -->    of(), ofDays(), ofHours(), ofMinutes(), ...
      Period                                 -->    of(), ofYears(), ofMonths(), ofWeeks(), ...
      DateTimeFormatter                      -->    ofPattern(), ofLocalizedDateTime(), ofLocalizedDate(), ofLocalizedTime()
      
      DateTimeFormatter ofLocalizeDate(), ofLocalizedTime(), ofLocalizedDateTime() 
      could use FormatStyle.SHORT, FormatStyle.MEDIUM, ...
    • java.time.* has got a Month enum that starts at 1 with Month.JANUARY (Calendar does the same but starts at 0 instead)
    • date and time new vs old way:
      java.time.*                                     -->    java.util.*
      LocalDate.now()                                 -->    new Date()
      LocalDateTime.of(2018, Month.January, 1         -->    Calendar.getInstance().set(2015, Calendar.JANUARY, 1).getTime()
      DateTimeFormatter.ofPattern(...).format(...)    -->    new SimpleDateFormat(...).format(...)
    • Period and Duration methods chaining doesn't work as espected, they use the last method in the chain
    • both DateTimeFormatter and date/time objects have a .format(...) method for convenience
    • FIX NEEDED (.parse() available also in DateTimeFormatter): LocalDate, LocalTime and LocalDateTime have a .parse(date/time/dateTime, formatter) and .parse(date/time/dateTime) methods to get date/time/dateTime objects from String

Methods and Encapsulation

  • in a list of parameters a vararg must be the last element if included
  • when using vararg in a method you can omit the values when calling the method and a zero-sized array will be created
  • protected access modifier visivility is equals to default acces modifier plus child classes
  • instance and static variables/initializer
  • static imports import static members: import static package.Class.staticMember;
  • importing a static member from a class doesn't allow you to use its class to call the static member.
  • java is pass-by-value.
  • overloaded methods can havae different: access modifiers, specifiers (static, final, ..), return types and exception lists.
  • overloaded methods must have different parameters.
  • method that receive Object as a parameter could be sent a int litteral and it will be boxed to Integer wich is an Object child.
  • Constructor calls this() and super() must be the first statement.
  • final instance/class variables:
    - final instance variable can be assigne from constructor and instance initializer.
    - final static variable can be assigne from static initializer.
    - final variables can be assigne just one time.
    - final variables do not have default values.
    
  • Order of initialization:
    1. superclass static variables and static initializers.
    2. class static variables and static initializers.
    3. superclass instance variables and instance initilizers and then superclass constructor.
    4. class instance variables and instance initilizers and then constructor.
    
  • Inmutable classes are good.
  • Defensive copy (pag 208): to make a copy of the mutable object you receive and return.
  • Deferred execution: code is specified now but will run later.
  • Predicate

Class Design

  • each class constructor must call either other own class constructor or parent constructor, implicitly or explicitly.
  • no implicit call is made to parent cosntructor with parameters.
  • Methods signature (name and parameters), visible for a class (including subclass), can not be the same unless following overriding rules.
  • Overriding and hiding:
    • Overriding/Hiding rules:
      - Access modifie:                  same or broader.
      - static specifier (if presented): same.
      - Return type:                     same or subclass (covariant).
      - Signature (name and parameters): same.
      - Exception (if presented):        same, subclass or non.
      
    • For a child method to declare an exception the overridden method most declare one.
    • Hiding static methods is same as overriding but without polymorphism. Is done following overriding rules with both methods with static specifiers.
    • instance and class varibles are hidden, and they do so even with each other unlike methods.
    • final methods can not be overridden nor hidden.
    • final variables just mean their value can not change.
    • Hiding variables and static methods is bad practice.
  • Abstract classes and Interfaces:
    • abstract classes do have constructors.
    • abstract classes and abstract methods can not be final nor private.
    • abstract methods are just allowed inside abstract classes and interfaces.
    • interfaces just can use the keyword extends and is to inherit from other interfaces.
    • interfaces can have the keyword abstract in the class or methods declaration.
    • keyword implements goes before keyword extends.
    • An abstract class can implement abstract methods from another abstrac class.
    • interfaces are abstract classes that, implicitly or explicitly, only allow:
      - abstract methods: public abstract 
      - static methods:   public
      - default methods:  public
      - fields:           public static final
      - FIX: DO NOT HAVE CONSTRUCTOR
      
    • Interfaces that extend other interfaces can redefine parent abstract and concrete (default) methods to be the oposit.
    • concrete class inpmenting interfaces with same-signatured default method must override the method to lose the ambiguity.
    • interfaces's static methods are not inherited (no subject to overriding rules) so must be called using interfaces name reference.
    • a overriden method can be made final
  • Polymorphism: you get all visible superclass members but its subclass overridden methods implementation.
  • cast from subclass tu superclass is implicit where as the oposit is explicit.
  • when explicit cast is done it thorws a ClassCastExceptoin if the casting object is not instance of the type casted to.
  • in java all non-final, non-static and non-private methods are virtual methods.

Exceptions

  • Exceptions hierarchy:
                      +-----------------------------+
                      |                             |
                      |      java.lang.Object       |
                      |                             |
                      +-----------------------------+
                                     ^ 
                                     | 
                                     |   
                      +-----------------------------+
                      |                             |
                      |    java.lang.Throwable      |
                      |                             |
                      +-----------------------------+
                                     ^ 
                           __________|__________
                    ______/                     \______
                   /                                   \
    +-----------------------------+     +-----------------------------+
    |                             |     |                             |
    |    java.lang.Exception      |     |      java.lang.Error        |
    |                             |     |                             |
    +-----------------------------+     +-----------------------------+
                   ^
                   | 
                   | 
    +-----------------------------+
    |                             |
    | java.lang.RuntimeException  |
    |                             |
    +-----------------------------+
    
  • catch clouse is not required if finally clause is present
  • finally clause always run except when calling Syste.exit(0)
  • mutiple exceptions must be catch from specif to general
  • if exceptions are thrown on catch and finally clauses the one how gets thrown is the one from the finally clause

Noticeable things around the content

  • FIX NEDDED: when assigning number literals, which are intended to be int, a special casting is don to narrower types.
  • some wrapper classes need to be cast:
    - new Byte((byte) 1)
    - new Short((short) 1)
    - new Character((char) 1)
  • integral number literals (no floating-pointed or postfixed) could be operate and assigne to any numeric primitive always it is not larger than the data type assinged to. Even though are operated as integers.
  • wrapper class Float's got two costructors: Float(double value) and Float(float value)
  • floating-points cand be assigned long values.
  • floating-points could return: NaN and Infifnty
  • Method 'equals', in classes that haven't implemented it, does exactly the same as '=='
  • Exclusive OR (^) is only true if the operands are different
  • private methods are hidden and when using polymorphism inside a class with a hidden private method the implementation of the private method will be always choosen.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment