---
# System prepended metadata

title: Java Beginner Part-2
tags: [JAVA]

---

###### tags: `JAVA`
# Java Beginner Part-2

## If condition
**regular if condition**
```java=1
if(temp > 30)
    System.out.println("It's hot day");
else if(temp > 20)
    System.out.println("Beautiful day");
else
    System.out.println("Cold day");     
```
**simplify if condition**
```java=1
boolean hasHighIncome = (income > 100_000);
```
**ternary if condition(三元)**
>if score bigger than 80 then return "Excellent" or return "Good"
```java=1
String place = score > 80 ? "Excellent" : "Good";
```

**if convert to switch**
if the conditions are too many to be implement, we can use `switch` replace with `if`
```java=1
String role = "admin";
switch(role){
    case "admin":
        System.out.println("You are an admin");
        break;
    case "moderator":
        System.out.println("You are an moderator");
        break;
    default:
        System.out.println("You are a guest");
}
```


## Loop

### for loop
```java=1
for (int i = 0; i < 5; i++){
    System.out.println("Hello");
}
```
### while loop
**remember to add the condition to stop the loop, or ot will run infinite**
```java=1
int i = 5;
while (i > 0){
    System.out.println("Hello" + i);
    i--;
}
```
### Scanner loop(get value with loop)
If we want to quit, we need to add a condition to stop the loop
but `input !=  "quit"` won't work
Because String are reference type, comparison operator cannot compare reference type
We need to use equals() method
```java=1
String input = "";
while(true){
    System.out.print("Input: ");
    input = scanner.next().toLowerCase();
    if(input.equals("pass"))
        continue; // go to the next step of the loop
    if(input.equals("quit"))
        break;  // quit the loop
    System.out.println(input);
}
```


### do while
**at least execute one time**
```java=1
Scanner scanner = new Scanner(System.in);
do{
    System.out.print("Input: ");
    input = scanner.next().toLowerCase();
    System.out.println(input);
}while(!input.equals("quit"));
```
### forEach loop
```java=1
String[]  fruits = {"Apple","Mango","Orange"};
for(String fruit : fruits){  // variable : array
    System.out.println(fruit);
}
```
## Class
**class is object blueprint**
### regular class
In `Class` we can declare variable and function(method)
The important things is we need to create a **constructor**
And In Class we can use the private function(method) but out of this Class, it will never be seen
The Inheritance class can't see too
```java=1
public class Dog {
    public   String name;
    public   int age;

    // constructor
    public Dog(String dogName, int dogAge) {
        this.name = dogName;
        this.age = dogAge;
        System.out.println(add2()); // add2() private function can be use in this class

    }

    public void speak(){
        System.out.println("I am "+ this.name +" and I am "
                + this.age + " years old.");
    }

    public int getAge(){
        return this.age;
    }

    public void setAge(int age){
        this.age = age;
    }
    // private
    // this is not visible in MainDog
    // it only can be used in this class
    private int add2(){
        return this.age + 2;
    }

}
```
**create an Instance of Dog**
```java=1
Dog wall = new Dog("wall",10);
wall.speak();
```
### Inheritance
The following code is Cat class and it inheritance Dog class
We can override th parent's function, and add new function
And create many constructors, let class can instance  objects by many ways(different parameter's number)
```java=1
public class Cat extends Dog{

    private int food;
    
    // constructor
    // the below three constructors express that we can instance the class by three, two or one parameter
    public Cat(String name, int age, int food){
        super(name,age);
        this.food = food;
    }

    public Cat(String name, int age){
        super(name,age);
        this.food = 45; // default value
    }

    public Cat(String name){
        super(name,0);
        this.food = 50;
    }

    // override the dog's function
    public void speak(){
        System.out.println("Meow, My name is " + this.name + " and I get fed " + this.food);
    }

    // we can add the function what we want
    public void eat(int x){
        this.food -= x;
    }

}

```

### protected v.s private
**protected**
who can see(use) the variable?

    which in the same package can use it


**private**
who can see(use) the variable?
    
    which in the same class

## Set & List
* Set: the set which didn't have repeat elements 
    * 由 HashMap 實現的，不保證元素的順序
    * 允許使用 null 元素

```java=1
HashSet<Integer> s = new HashSet<Integer>();
s.add(2);
s.add(2); // will not add, because 2 is already in the set
s.add(9);
s.remove(9);
boolean e = s.isEmpty();
boolean c = s.contains(5); 
int t = s.size();
s.clear(); // clear all elements
```


* List: contain many element and can repeat the same value
```java=1
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(5);
a.add(4);
a.add(5);
a.get(2); // use the index to get the value 
a.set(0,1); // set the value (index,value)
System.out.println(a.subList(1,3)); // get sublist index 1 to 2
int size = a.size();
```
## Map & HashMap
* HashMap: doesn't have an order, so hashmap is extremely fast(search)
**the data type of key can different**
`.put(key,value)`
```java=1
HashMap m = new HashMap();
m.put("wall",2);
m.put("doncic","dallas");
m.put("kyrie",11);
m.put(99,190);
m.put(99,12); // override the same key

m.clear(); // make HashMap empty
m.isEmpty(); // detect HashMap isEmpty or not

System.out.println(m.containsKey("wall"));
System.out.println(m.containsValue(1));
System.out.println(m.get("doncic")); // get value by key
System.out.println(m.values()); // get all values
```
* TreeMap: has an order

```java=1
TreeMap t = new TreeMap();
t.put("sue",6);
t.put("bird","sue");
//t.put(99,11); treemap needs the key with the same type
```
* LinkedHashMap: the order of LinkedHashMap will adhere to when we add the elements

```java=1
LinkedHashMap l = new LinkedHashMap();
l.put("sue",6);
l.put("bird","sue");
l.put("bird","123"); // override the same key
l.put("a","aa");
```

### exercise
```java=1
HashMap map = new HashMap(); // record each character's appear number
String str = "Hello my favorite basketball player is John Wall.";
for(char s: str.toCharArray()){ // convert array to character
    if(map.containsKey(s)){
        int old = (int) map.get(s);
        map.put(s,old+1);
    }
    else{
        map.put(s,1);
    }
}
map.remove(' ');
```

## Interface
Interface is the blueprint of class
Class will implement the interface
You can declare the method, but not implements in Interface

**create interface**
```java=1
interface Vehicle{
    // only declare the method
    void changeGear(int a);
    void speedUp(int a);
    void slowDown(int a);
    default void out(){ // can be used directly
        System.out.println("Default output");
    }
    static int math(int b){  // can use class to call this method don't care about instance
       return b + 9;
    }
}
```
**implements the interface by class**
```java=1
public class InterfaceExercise implements Vehicle{
    ...
}
```


**override the method that we declare in interface**
```java=1
private  int gear = 0;
private  int speed = 0;

@Override
public void changeGear(int gear) {
    this.gear = gear;
}
```

**use the class which implements Vehicle to make an object**
```java=1
InterfaceExercise Toyota = new InterfaceExercise();
Toyota.changeGear(10);
Toyota.speedUp(100);
Toyota.slowDown(10);
Toyota.display();
int x = Vehicle.math(5); // static method (do not need an Instance to call the method)
```

## Inner Class
**create the Inner Class**
```java=1
class OutSide{
    int a = 0;
    class Inside{
        int b = 5;
    }
    static class Inner{
        int c = 100;
    }
}
```

**Regular Inner Class**
```java=1
OutSide o = new OutSide();
OutSide.Inside i = o.new Inside();
System.out.println(o.a);
System.out.println(i.b);
```
**Static Inner Class**
```java=1
//  can ignore to create an Instance
OutSide.Inner I = new OutSide.Inner();
System.out.println(I.c);
```

## Enum
**create an Enum**
The enum in Java can create variable and method
```java=1
enum Mobile{
    APPLE(100),SAMSUNG(89),HTC(78);
    private int Price;
    // constructor
    Mobile() {
        Price = 80;
    }
    // method
    Mobile(int price) {
        this.Price = price;
    }
    
    public int getPrice(){
        return this.Price;
    }

    public void setPrice(int price){
        this.Price = price;
    }

}
```
The real Enum created in Java
```java=1
class Mobile
{
    static final Mobile APPLE = new Mobile(100);
    static final Mobile SAMSUNG = new Mobile(89);
    static final Mobile HTC = new Mobile(78);
}
```

**use Enum in code**
```java=1
System.out.println(Mobile.HTC.getPrice());
Mobile phone = Mobile.HTC;
Mobile[] arr = Mobile.values();
for(Mobile a : arr){
    System.out.println(a);
}
System.out.println(Arrays.toString(Mobile.values()));
// [APPLE, SAMSUNG, HTC]
```


## ObjectComparisons
If you want to compare any value in the object, the class which is your object's blueprint need to implement
`Comparable<className>`
```java=1
static class Student implements Comparable<Student>{
        private String name;
        public Student(String name) {
            this.name = name;
        }
        public boolean equals(Student other){
            return this.name == other.name;
        }
        public int compareTo(Student other) {
            return this.name.compareTo(other.name);
        }
}
```
**implement the comparisons**
```java=1
Student wall = new Student("Wall");
Student doncic = new Student("Doncic");
System.out.println(doncic.equals(wall)); // return boolean type
System.out.println(doncic.compareTo(wall) > 0); // if true , means doncic is larger than wall.
```
