Study Notes for "Java Programming Masterclass"

读完入门书,算是打了个基础,于是开始跟Udemy上评价不错的一个”Java Programming MasterClass for Software Developers”, 预计20天左右学完,此文用意为学习笔记,毕业为止长期更新。
因为基础部分和之前读的”learn Java in one day”是几乎一致的,所以仅记录书中没提到过的一些小细节。
顺便非常想吐槽这讲师的口音,简直有种含着口球在上课的感觉,听着巨难受(笑cry
IntelliJ IEDA真的好用,感觉用起来比netbeans舒服多了。

Envrionment

  • The IDE used for this course is IntelliJIDEA Community Version 2019.1
  • This version has no direct entrance for “Project Defaults -> Project Structure”, need to use the shortcut Ctrl+Alt+Shift+S
  • Accidentally click the Inject language will give a error “‘class’ or ‘interface’ expected”.
    • goto “File-Settings-Editor-Language Injections” and deldete the injection
  • IntelliJ Idea will use a *.iml file to track a project
  • Code – Generate(Alt+Ins) can auto create constructors / getter and setter and some other methods
  • psvm->tab will auto give public static void main (String[] args){} declaration

Members of a class

  • Within a class definition, the members are:
    • Field declarations
    • Methods
    • Constructors
    • Initializers
  • Members can be defined as static or non-static (instance)

Variables

Primitive Data Types

  • Cannot directly use the power of a number, ^ is a bitwise operator, not math operator
  • Can use _ as ,
  • Java will auto convert byte and short to int for expression by default
    • The solution is type casting byte x = (byte) x/2;
  • For expression of long type data, every number shall have a suffix F to the end
    • long aLongNumber = 5000L + 10L * (aByte + aInt + aShort)
  • double / int = double
  • Type float and double has wider range than type int and long, but may lose significant digits
    • int 123456789 -> float 1.23456792E8 / double 1.23456789E8
  • Calculation with double is faster than float

Operator

  • Logical Operators

    • Binary Type &, |, non-short circuiting version of && and ||
    • Ternary Type ? :, short-form of if-else statement
      1
      2
      boolean wasCar = isCar ? true : false;
      //if isCar = true, wasCar = true, else all false
  • Bitwise Operators

    • &, |, ^, means and, or and Xor in bit pattern (1&0=0, 1|0=1, 1^0=1, 1^1=0)
      *~, turns 0 to 1 and 1 to 0

Keywords and Expressions

Methods

  • Math.round() can be used to round a number, will return long type number
  • Math.ceil() to return the smallest double that is larger than the number (123.3 -> 124.0)
  • int / int will alway give int, to avoid that
    • Use double = (double)int / int to get a double result, but cannot use (double)(int / int) as JAVA will cal the () first.
  • A way to compare first n decimal points of double/float is use narrow casting

    1
    2
    3
    double x = 3.1458; double y = 3.1452;
    int a = (int) (x * 1000); int b = (int) (y * 1000);
    // a = b = 3145, thus first 3 decimal points of x = y
  • Methods overloading doesn’t apply on same parameters with different return type

  • To conver a Integer to String
    • String str = Integer.toString(int)
    • Or can directly String str = int + “String”, JAVA will auto treat result as String
  • To apply a format in println instead of use printf
    • System.out.println(String.format("format_specifiers", data))
    • If newline is required in printf, it shall be within the format_specifiers,eg. "\n %.2f \n"
  • To check if a String is empty, can use .isEmpty() , return true for empty String

For and While Statement

  • For PrimeNumberChecker, as any number that can be treated as x * y shall have x or y <= sqrt(n)
    • the condition can be (i = 2; i <= Math.sqrt(n); i++)
  • In while-loop. keyword continue will by pass the rest part of code to continue loop
  • Logic to check digitals of number
    • Use n % 10 to get last digit, and n / 10 or n * 10 to move the pointer

If statement

  • If return type is boolean, can be simplified as return (condition)

Read Input

  • To avoid invalid type of input
    • try-catch method
    • reader.hasNextInt(), will return true if input is Int
  • To persent max / min of a data object (Integer / Double / …)
    • Object.MIN_VALUE and Object.MAX_VALUE

OOP

  • Reference vs Object vs Instance vs Class

    • Class is blueprint for a house, based on the blueprint can build as many houses as we like
    • instance is the object (house) we instantiated with new operator
    • reference is the address of the object (house), can be used as parameters for constructors and methods
    • There is no way to access an object directly without a reference
      1
      2
      3
      4
      5
      6
      7
      public static void main (String[] args){
      House house1 = new House("TypeA"); //instantiated a instance
      House house2 = house1; // create a reference to the same object
      house1.getType(); // A, use reference to access the object
      house2.setType("TypeB"); //change of house 2 applys to house 1
      house1 = getType(); // B
      }
  • Static Methods vs Instance (non-static) Methods

    • static methods can’t use instance variables
    • static methods do not belong to an object
    • static methods can be called directly
    • instance shall be created before call the instance method
    • If instance methods or any fields are used, shall use instance method
  • Static Variables vs Non-static (instance) Variables vs Local Varibales

    • static variables are shared between instances within the class
      • stored inside the class memory and are common to all obejects of a class
      • update static variable for current instance will also update the pervious instance
      • not destoried until the programe ends
    • instance variables are fields or member variables, belong to an instance of a class
      • instance variables are declared inside a class
      • not compulsory to initialization (contains default value 0 or null or false etc.)
      • have access modifiers (private/public/protected etc.)
      • stored inside the object memory and each object will have its own copy of instance valiables
      • destory when the object destoried
    • local variables are declared inside a method, static and instance are created outside of a method
      • declared inside a method/constructor/block
      • must be initialized before use, don’t have default values
      • have no access modifiers
  • For getter and setter methods, to avoid err with same name parameters, can use keyword this

    • public void setName(Sring name){ this.name = name; }
  • Constructors can be overloaded, to avoid empty fileds with empty constructor
    • Use this(args) inside the empty constructor to call the other constructor
  • To call another class object in a class method
    • Use the ClassName as data type

Combinations of access modifiers, abstract, final and static

↓method be abstract be static be final / private be protected/package-private/public be overridden (inheritance)
abstract - X X O O
static X - O O X
final / private X O - O X
  • private method is always final
  • abstract class can contain normal methods
  • concrete class cannot contain abstract method

Inheritance

  • keyword super point to the super class
    • super(parameters) calls constructor from super class
  • super(parameters) and this(parameters) have to be the first statement in a constructor
    • A constructor can not call both at same time
  • @Overriding has some limites
    • Only applicable for methods in child classes (inherited methods)
    • Must have same return type
    • Constructors, static methods, private methods and final methods cannot be overriden
    • Can’t have a lower access modifier (if parent method is protected, child cannot be private but can be public)
    • Can’t throw a new or broader checked exception

Composition

Creating objects within objects

  • Create classes without extend, treate other classes as object data type in fileds and constructors
  • To call methods in the related class, can use getter to access the class
  • private class cannot be called

Encapsulation

Use private fields + getter & setter to protect the data, known as data hiding.

Polymorphism

The ability of an object to take on many forms.

  • Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding).
  • Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism
  • Makes the code easy to maintain

References Type

  • The keyword new is very important when delcare an array, otherwise will be a pointer to the address only.
  • new will dereference the reference to another address.
  • Dereference parameter in a method will not modify the original reference.

ArrayList

  • A new arraylist can be created by ArrayList<type of data> nameOfArray = new ArrayList<>()
    • A shortcut is = new ArrayList<type of data>(an arraylist to copy data from)
  • To convert an ArrayList to a normal array
      1. Create an normal array with size of the arrayList
      1. arraylist.toArray(arrayname)
  • To declare and add custom object types
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class Main {
    public static void main (String[] args){
    ArrayList<CustomClass> customArrayList = new ArrayList<>();
    customArrayList.add(new CustomClass(arguments));
    }
    }
    Class CustomClass {
    private int myValue;
    public CustomClass(int number){
    this.myValue = number;
    }
    }

LinkedList

  • Declared by LinkedList<type of data> name = new LinkedList<>()
  • Can use Iterator and ListIterator Methods to play with the curser pointer
    • Iterator nameOfIterator = nameOfLinkedList.iterator() to traverse the list

Interface

keyword for Interface is implements

  • InterfaceDemo newObject = new ObjectClass(args) to declare a class with interface
  • Declare class as Interface is a kind of polymorphism and takes advantage of that
  • Interface can be tagging with no code, just to tag classes
  • To call the methods in the class, need to case the interface to class by (ObjectClass)newObject
  • Difference between Interface and superclass
    • A class can only extend one superClass but can implements many Interfaces
    • SuperClass can be what the class is, and interfaces can be what the class can do

Inner Classes

  • Local class is the class created inside the method
  • Anonymous inner class are no name class that can be used to declare an object and assgin it to another object

Abstract Class

Abstract class cannot be instantiated directly

Recursive Methods

  • A method that calls itself in the method, can be called up to 63 layers
  • Useful for binary search tree