1Z0-803 Java SE 7 Programmer I Passed

Today I've passed Java SE 7 Programmer I Exam with a score of 88%.
Unlike my preparation for MS 70-483: Programming in C#, I did not make any notes to the blog and Java projects to study every nuances necessary for this level of Java Certification Exams, especially taking into account the knowledge of C#. The only things I've done are: reading appropriate literature (see below), making drafts of a future set articles dedicated to comparison of C# and Java, and ofc some notes of major differences between tese languages within the scope of topics covered by the Java Programmer I Exam. Here they are:


----------------------------------------------------
docs.oracle.com/javase/tutorial/extra/certification/javase-7-programmer1.html
OCA/OCP Java® SE 7 Programmer I & II Study Guide
----------------------------------------------------
_________
MODIFIERS
    Good table for revising modifiers: http://bmanolov.free.fr/javamodifiers.php

_________
T Y P E S

 For an integer the JVM looks for matches in the following order: int, long, Integer....
 _ _ _ _ _ _
 PTIMITIVES
        0) Primitives are passed by value, for passing-by-reference purpose corresponding wrappers can be used.

        1) Completely legal:
            short sh = 0512;
            byte b = -0;

        2) Char value van be assigned to an int value, but this rule is inapplicable for arrays.
            * that is why char even can be passed to a method taking int as a param
            * integer cannot be passed instead of char because of narrowing conversion

        3) defaut values of primitive data types and objects:
            char                  ->            \u0000
            byte, short, int      ->            0
            long                  ->            0L
            float                 ->            0f
            double                ->            0d    
            boolean               ->            false
            Objects(inc. String)  ->            null        
 _ _ _ _ 
 ARRRAYS
        char[] chArr = new char[] {'1', '2', '3'};
    
        Frack this sh*t! Equals arrays shit declaration:
            int []arr[] = {{1,2,3},{1,2,3}};
            int arr[][] = {{1,2,3},{1,2,3}};
            int[][] arr = {{1,2,3},{1,2,3}};

        It's incorrect to specify the size of an array with a square brackets when declaring, instantiating and initializing an array in a single line

        Correct multidimensional array declaration in init:
            String[][] strArr = new String[][] {{},{}};

        Arrays have an ATTRIBUTE (NOT A METHOD) called length.

  _ _ _ _ _ _ 
  ArrayList<e>
            benefits:
                *reduces memory footprint
                *dynamically resizes based on the number of elements
      ___________________________________________
      ArrayList<string> ejg = new ArrayList<>() is legal object initialization
      ___________________________________________
      ArrayList<string>() ejg = new ArrayList<>()
          ejg.get(0)                     // throws an exception
          System.out.println(ejg);    // prints []
      ___________________________________________
      ArrayList<string>() ejg = new ArrayList<>();
      ejg.add(0, "first");               // OK
      ejg.add(10, "lol");                // Cannot add at index which is OutOfBounds

      .add(index, obj)   // inserts obj at specified index position
            
        Array
            void array.copy(Object src, int srcPos, Object dest, int destPos, int length2Copy)
 _ _ _ _
 STRINGS
        String content cannot be compared using == <= ... only using .equals(String str) method.
        Strings have only .length(), not an attribute. (Arrays have attribute .length, not a method)
        _ _ _ _
        String

            .charAt(int index)
            .concat(String str)
            .contains(CharSequence s)
            .isEmpty()
            .getChars(int srcBegin, int srcEnd,         // Characters are copied from this sequence 
                      char[] dst, int dstBegin)         // into the destination character array dst.
            .getBytes()
            .equals(Object obj)

            .equalsIgnoreCase(String anotherString)
             int compareTo(String anotherString) / compareToIgnoreCase(String anotherString)
             
            .regionMatches(int toffset, String other, int offset, int len)
            .matches(String regex)
            
            .startsWith(String prefix) / startsWith(String prefix, int toffset)
            .endsWith(String suffix)
            
            .indexOf(int ch) / indexOf((int ch, int fromIndex))
            .lastIndexOf(int ch, int fromIndex)
            
            .replace(char oldChar,char newChar)
            .replaceFirst(String regex, String replacement)
            .replaceAll(String regex, String replacement)
            .reverse()
            
            .substring(int beginIndex) / substring(int beginIndex, int endIndex)
            CharSequence subSequence(int beginIndex, int endIndex)
            .split(String regex, int limit)
            .trim()
            
            .length()
            .toLowerCase() / toLowerCase(Locale locale)
            .toUpperCase() / toUpperCase(Locale locale)

            .toCharArray()
            .valueOf(Object obj)
            .intern()
            
        _ _ _ _ _ _ _ 
        StringBuilder
        
            StringBuilder by default takes the initialize size as length+16 which is 0+16. so capacity would return 16 here.
            StringBuilder.insert() can be used to insert number, string, char or CharSequence
            
            StringBuilder   append(Object obj)
              
            int             capacity()
            int             charAt(char ch)

            StringBuilder   delete(int start, int end)
            StringBuilder   deleteCharAt(int index)

            void            ensureCapacity(int minimumCapacity)

            // Characters are copied from this sequence into the destination character array dst.
            void            getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

            StringBuilder   insert(int indexToInsert, char[] charArr, int charArrStart, int charArrLen)
            StringBuilder   insert(int offset, Object obj)
            int             indexOf(String str)
            int             indexOf(String str, int fromIndex)
            
            int             lastIndexOf(String str)
            int             lastIndexOf(String str, int fromIndex)
            int             length()

            StringBuilder   reverse()

            // replace only characters from start to end exclusively, 
            // the rest of original string is shifted by the rest elements of the replacement string
            StringBuilder   replace(int start, int end, String str)     
            
            String          toString()

            // if < than current length, characters with index > newLength will be cut off, 
            // if greater - '\u0000' will be inserted
            void            trimToSize() 
            void            setLength(int newLength)
                                                                        
            void            setCharAt(int index, char ch)
            String          substring(int start)
            String          substring(int start, end)
            CharSequence    subSequence(int start, int end)
 
  
  
__________
EXCEPTIONS
    - Exceptions are classes. If you try to catch an exception from its derived class afterwards, the code wont compile.
    - When overriding class method throws should be omitted or be of the same, derived type, however, an overriding method can throw RuntimeException and derived, not thrown by the overriden method.
                  Exception
                 /
        Throwable
                 \
                  Error
    - java.lang.Throwable is the base class of all exceptions
    - Error is not an exception coz it is not a sublacc of Exception
    - checked exceptions must be a part of methods signatur if not catched in the body

    SHould be never handled:
     StackOverflowError
     OutOfMemoryError
           
    Exception inheritance tree
        IOException
        BadStringOperationException
        CertificateException
        CloneNotSupportedException (class do not overrides clone method of Object)
        DataFormatException 
        NotBoundException (A NotBoundException is thrown if an attempt is made to lookup or unbind in the registry a name that has no associated binding.)
        ParseException (Signals that an error has been reached unexpectedly while parsing.) 
        TimeoutException (Exception thrown when a blocking operation times out. ) 
        
    RuntimeException inheritance tree
        NullPointerException
        IndexOutOfBoundsException
            ArrayIndexOutOfBoundsException
            StringIndexOutOfBoundsException
       IllegalArgumentException
            NumberFormatException
        SecurityException

    The rule that "if a base class' method doesn't throw an exception, an overriding method in the 
    derived class can't thow an exception" aolies only to checked exceptions. A base or overriden 
    method is free to throw any Error or runtime exception.

    ExceptionInInitializerError may be throw by JVM when a static initializer in your code throws
    a NullPointerException.

    NumberFormatException is thrown by multiple methods from Java API when invalid numbers are passed
    on a Strings to be converted to the specified number format. 
    NumberFormatException is a subclass of IllegalArgumentException
__________________________
INHERITANCE & POLYMORPHISM
    - polymorphism does not apply to static methods and depends only of type of a variable, not the object

    - polymorphic methods are also called overridden methods

    - interfaces can only extends other interfaces

    - class cannot implement two interfaces with the sme method having different return types, 
      even if types pass IS-A  test (compile-time error)

______
SCOPES
    1) If access modifier is not specified it considered to be default, 
       which means that member can be accessed by any class within the package.
    2) protected modifier extends package accessibility to child classes from other packages.

____________
CONTROL FLOW
 _ _ _ _
 SWITCH
        valid types:
            byte, int, Integer, String 
    
        0) SWITCH is based on labels, so when executed it jumps to the first matching label or default 
           and starts execute everything after it.
        
        1) Compile-time constants, including expressions and final variables, 
           are permissible in case labels:

           final int someNumber = 10;
           switch (num) {
               case 10*3 : ...
               case 10/3 : ...        // decimal part will be discarded and 3 will be compared with num
               someNumber: ...
           }

        * Java compiler does not consider a final variable which was not asigned value at initialization
          considered not to be a compile-time constant and thus cannot be applied to switch case statement.

        2) Default statement case executes only of no matching values are found.
        

______________
INITIALIZATION
 ______________________________________________________________________________________
 Java VM calls and  executes the main method
     - a class shouldn't define multiple main methods, which used to start an app;
     - more than one class in app can define main method;
     - the main method must accept String[] of varargs String...;
 ______________________________________________________________________________________

    STATIC AND INSTANCE INITIALIZERS
     This shit is legal :(
         class Ideone
         {
             static {
                 System.out.println("Static Initializer 1");
             }
             {
                 System.out.println("Non-Static Initializer 1");
             }
             public static void main (String[] args) throws java.lang.Exception
             {
                 ...
             }
             static {
                 System.out.println("Static Initializer 2");
             }
             {
                 System.out.println("Non-Static Initializer 2");
             }
         }
     * static constructors are invoked at first mention of a Class in any line of code.
     * if you do not assign explicit values to instance variables of class, they are initialized 
       to their default values, even if no-arg constructor is declared with empty body.
_______
CASTING
 When mathematical operations is perfomed on any primitives than smaller than int, the result is 
 automatically cast to an integer.

 Legal: int iNum = (int)123.456; // iNum = 123


_________
OPERATORS
 ^ - XOR (true if only one of operands is true, otherwise - false)
 


_____________
PAY ATTENTION
 - comments can appear at any position in a source files
 - a base class can user reference variables and objects of its derived classes
 - instanceof
 - on the methods name when overloading
    - "0123456".substring(0,5) // 0 inclusive and 5 exclusive, so the output is: 01234;
    - ClassCastExceptions are arisen at runtime;
    - you should not implement an interface if it is already implemented by a super class;
    - there is no difference how any times you will import a package;
    - the path of imported class used in an import statement isn't related to the class's physical location.

    When + operator encounters a String object, it trells all remaining operands as String objects.
    Concatenation runs from left2right, and if either operand is a String, the operands are concatenated.
    If both operands are numbers, they are added together.


 Interfaces and their methods are implicitly abstract and adding that modifier makes no difference. The method must be implemented by any (concrete) implementing class.

 Default no-args constructor generated by the compiler only if the class has no constructor defined explicitly.

_________________            
PACKAGES & IMPORT
    Automatically imported:
        Java.lang
        Pachage with no name 
        
    import static allowes to import static members
        import static java.lang.Math.PI;
        //или все целиком:
        import static java.lang.Math.*;

Comments