HSSP CS
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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. ![](https://i.imgur.com/RuNZjlD.png) 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!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully