# Week 2
## Main Lecturer: Kanjonavo Sabud
Classes, String methods, Math Class, and If/Else condition
---
## Class
Think of a `class` as a "blueprint" and an `object` as the blueprint actually physically created.
For example, let's create a `Student` Class. This class will have a `String` name and an `int` ID as its data fields Data fields are basically attributes that differ in the `Objects` of the `Class`.
```java=
class Student {
private String name;
private int id;
// ...
```
Now if you want to create specific students using the `Student` class as a template, the class needs a **constructor**.
A constructor is called when a new `Object` is **instantiated** and must intialize all uninitialized data fields.
```java=
public Student(String s, int i){
name = s;
id = i;
}
// ...
```
Now before we go into the methods of the Class let's first understand what a method is.
**Methods** are basically commands to do a job. They are made of a header and a block of code, which comes after the header and is wrapped in curly braces.

These are the parts of a method.
Different Examples of these parts are:
* Access Specifiers : `private`, `public`
* Return type: `int`, `double`, `String`, `void`, etc.
* Can be any data type
* Can be `void`, meaning no return type
* Parameters in the parameter list must be specified with the data type of the parameter. Think of a parameter as a "variable" that is passed in when a method is run (like passing in x to a function f(x) in math).
Then we have the getter and setter methods of a class.
These methods are responsible for returning and editing, respectively, the private fields of the class.
We can use the `return` keyword to send data back to the method that called the method.
``` java=
//getters and setters
public String getName(){
return name;
}
public void setName(String str){
name = str;
}
public int getID(){
return id;
}
public void setID(int i){
id = i;
}
...
```
There are also 3 essential methods that all objects should have: `.toString()`,`.equals()`, and `.compareTo()`
```java=
//essential methods for every class!!
public String toString(){
return "Name: " + name + ", ID: " + id;
}
public boolean equals(Student s){
return name.equals(s.getName());
}
public int compareTo(Student s){
return id - s.getID();
}
```
So in total, the `Student` class is:
```java=
class Student {
private String name;
private int id;
public Student(String s, int i){
name = s;
id = i;
}
//getters and setters
public String getName(){
return name;
}
public void setName(String str){
name = str;
}
public int getID(){
return id;
}
public void setID(int i){
id = i;
}
//essential methods for every class!!
public String toString(){
return "Name: " + name + ", ID: " + id;
}
public boolean equals(Student s){
return name.equals(s.getName());
}
public int compareTo(Student s){
return id - s.getID();
}
}
```
And now you can instantiate different students in your main method like this:
```java=
Student johny = new Student("Johny", 1);
Student martinez = new Student("Susan Martinez", 2);
```
## Strings
A `String` is a sequence of chars or characters. They can be instantiated in two different ways, though most people will instantiate them in the shorter, first way.
``` java=
String s = "Hello World";
String s = new String("Hello World");
```
As Strings are objects, they have methods of their own!
#### String Methods
| Method | Parameter(s) | Returns | Description |
| --------------------- |:--------------:| ---------- | --------------------------------------------------------------------------------------------------------------------------- |
| `.charAt()` | `int` | `char` | returns the char at the index |
| `.length()` | - | `int` | returns the length of the String |
| `.indexOf()` | `char` | `int` | returns the index of the first occurence of char |
| `.lastIndexOf()` | `char` | `int` | returns the index of the last occurence of char |
| `.indexOf()` | `char`, `int` | `int` | returns the index of the first occurence of char from int |
| `.lastIndexOf()` | `char`, `int` | `int` | returns the index of the last occurence of char from int |
| `.trim()` | - | `String` | returns the String without leading and trailing spaces |
| `.replace()` | `char`, `char` | `String` | returns the String with all occurences of char 1 replaced with char 2 |
| `.toLowerCase()` | - | `String` | returns the String with all lower case |
| `.toUpperCase()` | - | `String` | returns the String with all upper case |
| `.split()`* | `String` | `String[]` | returns the String divided around the parameter in an Array version |
| `.substring()` | `int` | `String` | returns the part of the String starting from but not including the int index up to the end |
| `.substring()` | `int` , `int` | `String` | returns the part of the String starting from but not including the first int index up to and including the second int index |
| `.equals()` | `String` | `boolean` | returns true if the parameter String has the same value as the String object and false otherwise |
| `.equalsIgnoreCase()` | `String` | `boolean` | returns true if the parameter String has the same value as the String object irrespective of the case and false otherwise|
| `.contains()` | `String` | `boolean` | returns true if the Object String containsthe parameter String and false otherwise |
Be sure to remember these methods and understand their applications.
Strings are also immutable, meaning they cannot be changed after instantiation.
```java=
String s = "Hello World!";
// s --> "Hello World!"
s.toUpperCase();
//changes s to upper case and returns a new String
//However, this new String is not stored
String s2 = s.toUpperCase(); // this stores the new returned String in s2
// s2 --> "HELLO WORLD!"
// s --> "Hello World!" // s remains unchanged
s = s.substring(5); // stores the new String in s itself
// However, this means that "Hello World!" previously stored in s is lost
// s -->"World!"
```
That is why methods like `.trim()`, `.substring()`, `.upperCase()`, `.lowerCase()` all return a `String` even though they work with the given String itself.
## The Math Class
The `Math` Class is a Class containing methods for performing basic numeric operations.
Because all these methods are **class methods** (i.e. they belong to the class, not each object), no object needs to be initialized in order to access the methods of the Math Class.
In the String class you had to initialize an object.
```java=
String s = "Hello World!";
```
And then you could access the String Methods using the dot notation.
```java=
s.methodName();
```
With the `Math` Class, you dont need to intialize an object! You can directly access the methods using the class name`Math` like this:
```java=
Math.max(2,5); //returns the greater of the two
Math.min(2,5); //returns the lesser of the two
```
Math class also has a huge amount of methods but for our purposes, we will only look at a few of the most commonly used.
| Method | Parameter(s) | Returns | Description |
|:-----------:|:------------:|:--------:|:-------------------------------------------------------------- |
| `.max(a, b)` | `int`,`int` | `int` | returns the greater of the two |
| `.min(a, b)` | `int`,`int` | `int` | returns the lesser of the two |
| `.sqrt(a)` | `double` | `double` | returns the square root of the input |
| `.abs(a)` | `double` | `double` | returns the absolute value of the input |
| `.pow(a, b)` |`double, double` | `double` | returns a raised to the power of b
| `.random()` | - | `double` | returns a random value from 0.0 (inclusive) to 1.0 (exclusive) |
> Visit this site to look at all the methods in the Math Class
> [Math Class Oracle Center](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html)
## If/Else Condition
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.
Here is the basic skeleton of an if/else condition statement.
```java=
if(condition){ //if the condition is true
execute this block of code
} else { // if condition is false
execute this block of code
}
```
There is also a variation of the if/else condition statement with an additional condition called else-if condition.
``` java=
if(condition 1){ //if condition 1 is true
execute this block of code
} else if (condition 2){ //if condition 2 is true
execute this block of code
} else { // if both the conditions are false
execute this block of code
}
```
Now let's take a look at some example code involving an if/else statement:
```java=
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Remember the scanner class from last week!!
String s1 = input.nextLine();
if (s1.equals("Strings are immutable")) {
System.out.println("Correct");
} else if (s1.equals("Strings cannot be changed after initialization")) {
System.out.println("Correct but there is a better word for that");
} else {
System.out.println("Incorrect");
System.out.println("Please try again!");
}
}
}
```
That's it for conditional statements!
When if/else statements are combined with loops (more on this in the upcoming weeks), they can create quite tricky and complicated algorithms.
How FUN!!!
## Week 2 Assignment
Make a program to demonstrate what we learned in week 2. Feel free to be creative and try new things out!
However, if you are want to tackle something challenging, complete the assignment described below.
### #1
> Create a class called `Employee` which stores an `Employee`'s:
>
> * `String` first name
> * `String` last name (middle initials part of last name)
> * `int` age
> These will be your private fields.
>
> Create a constructor which takes in all these values as arguments/parameters and initializes the private fields.
>
> Create appropriate getter and setter methods.
>
> Create a `toString` method which prints the private fields in the following format:
> ```
> firstName ,lastName: age
> ```
>
> Create an `equals` method which compares the last names first, and if they are the same, compares the first name.
### #2
> In your file's main method, ask the user for the `Employee`'s first name, last name, and age.
>
> Use this information to create an `Employee` object and print out that object's information (try implementing a `toString()` method!).
>
> Next, ask the user for another first name, last name, and phone number.
>
> Create another `Employee` object using this new information and return if the two `Employee` objects created are the same or not.
## That's it for Week 2! Happy Coding!