Java Grammar for Automation Testing

工作需要最近开始要捡起Java并且搭建Selenium为其基础的自动化测试框架,后续有一系列相关笔记,笔记都是英文也是为世所迫(工作需要也得捡起英语),拙劣英文的请见谅
Please excuse my English since I picked them up just a very short period of time.

Java Grammar

First Java Grammar

public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello World");
    }
}

Basic Grammar

  • Sensible for Uppercase and Lowercase
  • Class name must be capitalized the first letter
  • Method name must be all lowercases
  • Source file name must be the same as Class name
  • All Java program start from main method(refer public static void main(String[] args) in particular)

add package declaration on the top of the code to indicate where the class lives

package com.example.java;

public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello World");
    }
}

which means: the HelloWorld.java is in the com\example\java\


Java SE 8 API Documentation

  • https://docs.oracle.com/javase/8/docs/api/
  • https://blog.csdn.net/weixin_44034328/article/details/103645460

Primitive data type

primitive data type names are all lowercase

  • Number(In order to save memory, Number was divided into different types)

    image-20210909174412325
    • Java class library includes helper classes (java.lang.Double) for each primitive

    • Helper classes support conversion and formatting tools

      image-20210909175829688
      double a = 123.4d;
      Double b = new Double(a);
      int c = b.byteValue();
      float f = b.floatValue();
      
    • Primitive numeric variables default to 0

    • How to get the maximum number of each type?

      System.out.println("maximum:Byte.MAX_VALUE=" + Byte.MAX_VALUE);  
      
    • for float and double, what you've store aren't exactly what you've store. So BigDecimal is specifically designed to take care of this precision problems.

    double finalBill = (this.taxRate * 0.01 +1)*this.initialBill;
    BigDecimal fb = BigDecimal.valueOf(finalBill).setScale(2, RoundingMode.HALF_UP);
    
    • You have to add 'L' at the end of a long type value or otherwise, it would consider as an integer.

      long ll = 2147483648L;
      
    • You have to add 'F' or 'f' right after a float type value or otherwise, it would consider as an integer or double

      float ff = 2.0f;
      
  • Character

    • Single quotation mark contains one character(2 bit)
  • booleans (true/false)

java is a statically typed language, so all variables must have their types declared

int myVar 5;
  • when type was declared, you can't change the type

  • use camel case to define the identifier(myVar)

Conversion

  • automatic convert: from low to high

    byte,short,char—> int —> long—> float —> double 
    
  • force to convert

    public static int[] printArray(double[] args){
        int[] result = new int[args.length];
        for (int i=0; i< args.length;i++) {
        	// convert double to int by using (int) 
        	result[i] = (int)args[i];
        }
        return result;
    }
    
  • use helper classes to convert

    for (int i=0; i< args.length;i++) {
        Double doubleHelp = new Double(args[i]);
        result[i] = doubleHelp.intValue();
    }
    

Reference data type

  • String

    • Commonly Used Method

      • equals() : compares this string to the specified object, return true or false.

        public boolean equals(Object)
        
      • equalsIgnoreCase(): similar to equals(), but this one will ignore its upper case or lower case.

        public boolean equalsIgnoreCase(String anotherString)
        
      • replace(): replace substring of this string with replacement sequence

        public String replace(CharSequence target,
                              CharSequence replacement)
        
      • contains() : return true if and only if this string contains the sub-string

        public boolean contains(CharSequence s)
        
      • endsWith(): tests if this string ends with the specified string

        public boolean endsWith(String suffix)
        
      • indexOf(): returns the index with this string of the first occurence of the specified string.

        public int indexOf(String str)
        
      • split(): splits this string around matches of the given regular expression

        public String[] split(String regex)
        
      • substring(): returns a string that is a substring of this string. the substring begins at the specified beginIndex and extends to the character at endIndex(but not including the endIndex).

        public String substring(int beginIndex,
                                int endIndex)
        
    • StringBuffer

      • hundreds of good to use method that you can check it in API docs

        StringBuffer ab1 = new StringBuffer();
        StringBuffer ab2 = ab1.append("hello");
        
  • Class

  • Array

    • Array create a continuous memory space

    • Characteristic: Fixed Length + Fixed Type

      • Initialized by fixed value

      • Dynamic initialization : all elements default value are 0\0.0\false\ ' ' \ null (it depends on the data type)

        double[] dd = new double[5];
        System.out.println(dd.length);
        System.out.println(dd[2]);
        // 5
        // 0
        
    • How to obtain elements in this array? How to change elements in this array? : Bracket + Index(index number can not be a negative number)

      int[] d = {1,2,3,4,5};
      System.out.println(d[1]);
      System.out.println(d[4]);
      // 2 
      // 5
      d[3] = 100;
      System.out.println(d[3]);
      // 100
      
    • How to get the length of the array?: array.length

      System.out.println(d.length);
      // 5
      
    • Common Exception to Array:

      • java.lang.ArrayIndexOutOfBoundsException
      • java.lang.NullPointerException, which is often caused by null
    • Pass as parameter:

      public static void printArray(double[] args){
          for (double arg : args) {
              System.out.println(arg);
          }
      }
      public static void main(String[] args) {
          // the 1st way
          double[] myList = {1.9, 2.9, 3.4, 3.5};
          printArray(myList);
          // the 2nd way
          printArray(new double[]{2,3,4,5,6});
      }
      
    • Multidimensional Array

      type[][] typeName = new type[typeLength1][typeLength2];
      
  • enum

  • Interface

Two-Dimensional Array

  • Create Statically
    • DataType[][] varName = {{..},{..},{..},..};
  • Create Dynamically
    • The sub-array in this array is uncertain(if initialize, you have to initialize every sub-array): DataType[][] varName = new DataType[size][]
    • The sub-array is certain: DataType[][] varName = new DataType [size] [size]
// In this case [0]=null
String[][] ss = new String[3][]
// Initialize
ss[0] = new String[3]
// sub-array is certain
String[][] tt = new String[3][2]

Precaution to reference data type

  • they all store address value(location info) in memory
int[] d = {1,2,3,4,5};
System.out.println(d);
// [I@1b6d3586
  • null can be assigned to any reference type: you can output the variable, but you can not use this variable

Java Provide Reference data type to almost every primitive data type

primitive type reference type
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double

Process Control

Control

  • Switch

    • Data types that can be accepted by case are limited
      • int / byte / char / short / String / enum
    String dd = "Chloe";
    switch (dd){
        case "chloe":
            System.out.println("111");
            break;
        case "Chloe":
            System.out.println("3233");
            break;
        default:
            System.out.println("0000");
            break;
    }
    
    • pros: good performance
  • if..else if..else

    • multiple branches
    • branches are mutually exclusive

Loop

  • for

    • enhanced loop

    • normal loop

      • multiple arguments

        for(int i=A.lenth()-1,j=0;i>=0;i--,j++){
                    if(mm.charAt(i)!=mm.charAt(j)){
                        System.out.println("dddd");
                }
        
    • Nested loops

    • We used to loop array by the old method, but JDK 1.5 introduced a new loop method(what we call "For-Each Loop"). In this situation, intelliJ is deprecating the old loop method

    double[] myList = {1.9, 2.9, 3.4, 3.5};
    	// old loop method
        for(int i=0;i<myList.length;i++){
        System.out.println(myList[i]);
        }
        // new loop method
        for(double myElement:myList){
        System.out.println(myElement+" eee");
        }
    
  • while

    • while(condition statement){statement1;}
    • do{}while(condition)

Function(Method)

  • There's no run order between each Function in the same Class

Common Type

  • common method

    • format: Modifier ReturnType MethodName(parameter list){Method Body}
    public static int age(int birthday){...}
    
  • overload method

    • Definition: In the same class, you can create a method with the same method name that already hava but with different parameter types as an over load method. (ps: There's nothing to do with return type)
    public static void main(String[] args) {
        System.out.println(add(2));
        System.out.println(add(2,3));
        System.out.println(add(2.3d,2));
    }
    public static int add(int a, int b){
        return a+b;
    }
    public static double add(double a, double b){
        return a+b;
    }
    public static int add(int a){
        return 1+a;
    }
    // output: 3\5\4.3
    
    • Uses: Reduce the memory of different method, it's convenient for caller
  • Override method

    • Condition of use: Inheritance or Polymorphism
    • Pros: upgrade old method
    • Optional(for calibration): you can add "@Overrideat the top of the method, which is to check if it is a override method(if it isn't, then IDE will throw an exception)
    • How can I call the method with the same name of parent class? : by using key word super (but you can't find grandparent's class)
    public class IPhone4S extends IPhone{
        public void Siri(){
            System.out.println("111");
        }
    }
    
    public class IPhone5 extends IPhone4{
        @Override
        public void Siri(){
            super.Siri();
            System.out.println("222");
        }
    }
    
  • Construct method

    • Used for constructing a new object
    • format:public void ClassName(){}
      • you can omit return data type, because construct method must return null
    • constuct method can be a overload method
    • One thing to note is that when passing parameters into construct method, and your parameter name is the same with the variable name in class, you should use "this" to distinguish them(local variables and member variables).
    public class Calculator {
    String name;
    int age;
    public Calculator(String name,int age){
        this.name = name;
        this.age = age;
    }
    public void PrintOut(){
        System.out.println(this.name);
        System.out.println(this.age);
    }
    }
    
    
    public static void main(String[] args) {
          Calculator cc = new Calculator("aaa",3);
          cc.PrintOut();
    }
    // output:aaa 3      
    
  • Abstract method

    • abstract method define a prototype of a method, it doesn't implement any specific rules
    • shows in Interface

Object(Object-Oriented)

  • Diffrence between Object and Class

    • Class is just like a template, describe something or some action with common.(Abstract)
      • a mobile phone, which be able to take a call and message. Define phone's brand, price and tag.
    • Object describes something or some actions from class more specific
      • apple mobile phone, which has specific price tag, phone size, os characteristic and so on.
  • Instantiate Object(Create an object)

    • ClassName ObjectName = new ClassName()
    Calculator cc = new Calculator();
    
  • Three Characteristic in Object: Encapsulation, Polymorphism, Inheritance

    • Encapsulation: which enhance the readability and maintainability of code

      • limit the modification of object's variable
      Public Class Calculator{
          private String name; // You won't have any access unless you visit it by method in the same class.
          
          public void setName(String name){
              this.name = name
          }
          
          public String getName(){
              return this.name
          }
          
      }
      
    • Inheritance: if A class inherit B class, then A class owns all public method of B class.

      • use "extends" to inherit
      public class People {
          private String name;
          private int age;
      
          public int getAge(){
              return this.age;
          }
          public String getName(){
              return this.name;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      }
      
      public class Engineer extends People{
      }
      
      public class InheritDemo {
          public static void main(String[] args) {
              Engineer ee = new Engineer();
              ee.setAge(23);
              System.out.println(ee.getAge());
          }
      }
      // 23
      
      • if a class do not inherit from other class, then it will automatically inherit Object class by default(ancestor class)
      • class can inherit only one class, but class can be inherited by multiple classes.(Single Inheritance)
      • could not inherit any private members of parent class
      • when create object from a child class, java will call the construct method of its parent class at the beginning.
    • Polymorphism

      • Receive objects of subclasses with the type of the parent class

      • the same method that can be perform in different action accroding to their different morphology(example:Human and Monkey, they're all inherit Creature).

      • in the condition of inheritance

      • It reflects scalability

        ParentClass variableName = new ChildClassName();
        
        • Pros: able to accept all sub-classes object by only one parent class variable.

        • However, in this situation, you can not call the unique method of Child Class. So, you can only call the method shared by both parent class and child class, which should be an override method that overridden by child class.

          • How can I call the unique method of child class? : Forced Conversion

            Card card = new ACard();
            ACard aCard = (ACard)card;
            

Modifier

Access Modifier

  • public : you can access in any case
  • protected: you can access when you inherit the class(wherever the package is)
  • default : you can access in the same package(it means in the same folder).
  • private : you can access in the same class.

Non-Access Modifier

  • static : you can call it without instantiate an object
  • final : you can not overwrite this method/class (Format is as follows)

public static final String ECOMMERCE_URL = "http://automationpractice.com/index.php";


- abstract : use for setting a initial mehtod, then refine the method by rewriting it.

---

## Collection

*Container is use for storing data*

- **ArrayList** : Resizable-array, the actual realization is to create a new array for the sake of expansion

  - When instantiate, it constructs an empty list with an initial capacity of 10.

  - You have to regulate the data type of this collection(That's what we call **Generics<>**), and this data type must be **reference data type**. Java do not recommend you to ignore the specific data type in this collection.

  - **Collection Polymorphism** : use Interface as a datatype(No difference, but to remember that you can not instantiate that Interface)

    ```java
    List<String> list1 = new ArrayList<>();
    ```
    
  - Usage example:

    ```java
    public static void main(String[] args) {
            // not recommend you to do so
            // ArrayList al = new ArrayList(); // it turns out you add multiple object in al
    
            // this is the preferable one
            ArrayList<String> al = new ArrayList<>();
            // or ArrayList<String> al = new ArrayList<String>();
    
            al.add("ccc");
            al.add("ddd");
            al.add("ooo");
    
            System.out.println(al); // ToString() has been overwritten by ArrayList
            // output:[ccc, ddd, ooo]
        }
    ```
    
  - Commonly used method:

    - **add()** : append specified element to the end of the list
    - addAll() : append all the element in the specified collection to the end of the list
    - **get()**: Returns the element at the specified position in this list.
    - **size()**: Returns the number of elements in this list.
    - isEmpty(): Returns `true`if this list contains no elements.
    - remove() : Removes the element at the specified position in this list. or Removes the first occurrence of the specified element from this list, if it is present.(Overload method)
    - set() : Replaces the element at the specified position in this list with the specified element.

  - 3 types of loop

    - by index

      ```java
      for(int i=0;i<al.size();i++){
                  System.out.println(al.get(i));
              }
      ```

    - by enhanced loop

      ```java
      for(String a:al){
                  System.out.println(a);
              }
      ```

    - by iterator (not every container has index, then iterator appeared) --- less important

      ```java
      Iterator<String> ial = al.iterator();
              while(ial.hasNext()){
                  System.out.println(ial.next());
              }
      ```

- HashSet: Unordered(just not in order of the addition, they calculate the order by their own algorithm), no index, **non-repeatable**. 

  - Usage example:

    ```java
    HashSet<String> al = new HashSet<>();
    
    al.add("ccc");
    al.add("ddd");
    al.add("ooo");
    al.add("22");
    al.add("ddd");
    
    System.out.println(al); // Output:[22, ccc, ddd, ooo]
    ```

  - **Collection Polymorphism** : use Interface as a datatype(No difference, but to remember that you can not instantiate that Interface)

    ```java
    Set<String> set1 = new HashSet<>();
    ```

  - Commonly used method  (HashSet and ArrayList are all inheriting from Collection, so most of their methods are similar to each other.)

    - add() : Adds the specified element to this set if it is not already present.(**if it is already present, then return false**)
    - remove() : Removes the **specified element** from this set if it is present.
    - size() : Returns the number of elements in this set (its cardinality).

  - Loop (no index in HashSet)

    - enhanced loop
    - iterator

- HashMap : store data in form of key-value pairs, but key shouldn't be the same. 

  - `HashMap<k,v> varName = new HashMap<k,v>();`

  - key is unordered,no-index and non-repeatable

  - **Collection Polymorphism** : use Interface as a datatype(No difference, but to remember that you can not instantiate that Interface)

    ```java
    Map<String,String> map = new HashMap<>();

  - Commonly use method

    - get() : Returns the value to which the specified key is mapped, or `null` if this map contains no mapping for the key.  

      ```java
      HashMap<String,Integer> aa = new HashMap<>();
      aa.put("eee",22);
      aa.put("eer",34);
      System.out.println(aa); // {eer=34, eee=22}
      System.out.println(aa.get("eee")); //22
      ```

    - put() : Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

      ```java
      public V put(K key,V value)
      ```

    - **containsKey()** : Returns `true` if this map contains a mapping for the specified key.(*Given the fact that key is non-repeatable*)

      ````
      public boolean containsKey(Object key)
      ````

    - getOrDefault() : Returns the value to which the specified key is mapped, or default Value if this map contains no mapping for the key.

      ```
      public V getOrDefault(Object key, V defaultValue)
      ```

    - **keySet()** : Set is implemented by HashSet, so Set is just like parent, and keySet() is child that implement Set.(You can not instantiate interface) 

      ```
      public Set<K> keySet()
      ```

      - Usage :  pair with get(key)

        ```
        Set<String> ss = aa.keySet();
        for(String s :ss){
        	System.out.println(s + "=" + aa.get(s));
        }
        ```

    - **entrySet()**: similar to dict.items() in Python

      - `public Set<Map.Entry<K,V>> entrySet()`

      - Implementation logic

        ```java
        class Entry{
        	K key;
        	V value;
        }
        ```

      - Usage

        ```java
        Set<Map.Entry<String, Integer>> entries = aa.entrySet();
                // or Set<Entry<String, Integer>> entries = aa.entrySet(); ( but you should import java.util.Map.Entry )
                for(Map.Entry<String, Integer> en:entries){
                    System.out.println(en.getKey() + " == " + en.getValue());
                }
            }
        ```

    - foreach() : loop method that similar to entrySet(), but is more convenient

      - `public void forEach(BiConsumer<? super K,? super V> action)`

      - Usage

        ```java
        aa.forEach((k,v)->{
                    System.out.println(k + "==" + v);
                });
        ```





---

## Interface

- Interface is a collection of abstract methods, you should overwrite every abstract method later on class which implemented the interface.

  ```java
  public interface BaBa{
      int size();
  }
  public class ArraryCheck implements BaBa{
      // overwrite size
      public int size(){
          return 1;
      }
  } 
  • Similar with class, but somehow they're quite different:

    • Interface can not be instantiated
    • There's no construct method in Interface
    • Interface is born to be impletemented
    • but unlike inheritance, multiple interfaces can be implemented.
  • What's the similarities and differences between abstract class and interface?

    • Similarities:
      • Both can not create an object.
      • Both contains abstract methods.
    • differences:
      • abstract class embody commonality
      • interface embody characteristic
  • Characteristic:

    • Every method is a hidden abstract, which means they hide the modifier public abstract
    • Every variable can be hidden, but the modifier of each variable should only be public static final
    • You can not implement method in interface, but you can do it in class by implemented the interface.

Memory Mechanism

  • Java put memory into two type:
    • Stack Memory
      • Stack characteristic: First In Last Out(FILO)
      • pressing method or variable into the bottom of stack
      • Stack store the access address for heap memory space
    • Heap Memory
      • use for storing array and object create by "new"(every time you create an object, java allocates memory space from heap, which is pointed by stack memory)

Keyboard Shortcut

  • check files : double Shift
  • check the inherit relation: Ctrl + H
  • import: alt+Enter
  • input println : sout
  • input println with Class name.Method name : soutm
  • file formatting: Crtl+Alt+L