• Introduction
  • Important Wrapper Classes
  • Autoboxing and Unboxing
  • Introduction
  • Useful Methods
  • PRACTICE Strings, Integers, and Math
  • Objects

    What are objects?

    Brief note: The text here is useful for following along and reviewing after the lesson. However, for the best experience, I’d recommend you simply pay attention to the presentation and run the code as you go.

    Let’s say we have a book. This book has several properties, such as a title, author, and publisher. We can represent this with a few variables in our code.

    class Main {
        public static void main(String[] args) {
            String title = "The Guide to Failure";
            String author = "Aadit Mathur";
            String publisher = "The Crusaders of FreeBSD";
            String content = "...";
    
            System.out.println("The title of the book is " + title);
            System.out.println("The author of the book is " + author);
            System.out.println("The publisher of the book is " + publisher);
        }
    }
    
    Main.main(new String[]{});
    

    That’s all well and dandy, until we want to add another book.

    class Main {
        public static void main(String[] args) {
            String book1_title = "The Guide to Failure";
            String book1_author = "Aadit Mathur";
            String book1_publisher = "The Crusaders of FreeBSD";
            String book1_content = "..."; // placeholder
    
            System.out.println("The title of the book is " + book1_title);
            System.out.println("The author of " + book1_title + " is " + book1_author);
            System.out.println("The publisher of " + book1_title + " is " + book1_publisher);
    
            String book2_title = "The Tragedy of Mr. Mortensen, Teacher of A101";
            String book2_author = "Shuban Pal";
            String book2_publisher = "The Crusaders of FreeBSD";
            String book2_content = "...";
    
            System.out.println("The title of the book is " + book2_title);
            System.out.println("The author of " + book2_title + " is " + book2_author);
            System.out.println("The publisher of " + book2_title + " is " + book2_publisher);
        }
    }
    
    Main.main(new String[]{});
    
    Failed to start the Kernel 'java (IJava/j!)'. 
    
    
    View Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details. spawn EINVAL
    

    Within a second, our simple program has turned into a mess. Also, although we named our variables in a wway that allows us to see that theyre related, it would be nice if we could group these attributes together.

    Introducing… classes!

    Classes are a way for us to logically group these attributes and behaviors together.

    class Book {
        public String title;
        public String author;
        public String publisher;
        public String content;
        public int pages;
    
        public Book(String title, String author, String publisher, String content, int pages) {
            this.title = title;
            this.author = author;
            this.publisher = publisher;
            this.content = content;
            this.pages = pages;
        }
    
        public Book(String title, String author, String publisher, String content) {
            this.title = title;
            this.author = author;
            this.publisher = publisher;
            this.content = content;
            this.pages = 0;
        }
    }
    
    class Main {
        public static void main(String[] args) {
            Book book1 = new Book("The Guide to Failure", "Aadit Mathur", "Crusaders of FreeBSD", "...", 50);
            
            System.out.println("The title of the book is " + book1.title);
            System.out.println("The author of " + book1.title + " is " + book1.author);
            System.out.println("The publisher of " + book1.title + " is " + book1.publisher);
            
            Book book2 = new Book(
                "The Tragedy of Mr. Mortensen, Teacher of A101",
                "Shuban Pal",
                "Crusaders of FreeBSD",
                "..."
            );
    
            System.out.println("The title of the book is " + book2.title);
            System.out.println("The author of " + book2.title + " is " + book2.author);
            System.out.println("The publisher of " + book2.title + " is " + book2.publisher);
        }
    }
    
    Main.main(new String[]{});
    

    There are a few things to note here:

    • Classes as Blueprints: The class, Book, acts as a blueprint for creating objects, such as our book, “The Guide to Failure”
    • Objects: These are different Books made using our “blueprint”
      • Each of these books (i.e. the things made using our class) are usually called “instances” of the class
    • Types: The Book class is a type that can be used like something such as a String
    • The new Keyword: This allows us to create an object of type Book
    • Constructors: When we make a new Book(), the arguments passed in are matched to the correct constructor, a special function which creates a new instance
    • Class-wide variables: These variables can be accessed with the dot operator
    • Dot operator: Allows us to access class variables
    • The this Keyword: Allows us to access class variables from inside the class

    PRACTICE: Objects

    Now, we’ll see if you understand the concept of classes and objects.

    Try and create a class in the following code space to represent a dog.

    class Dog {
        ...
    }
    
    public class Main {
        public static void main(String[] args) {
            Dog myDog = new Dog("Shelby", "Golden Retriever", 5); // name, breed, age
            myDog.bark(); // should print "Woof!"
        }
    }
    

    Non-Void Methods

    Objects can group attributes together, but they can also group together behaviors. Let’s see an example.

    class Book {
        public String title;
        public String author;
        public String publisher;
        public String content;
        public int pages;
    
        public Book(String title, String author, String publisher, String content, int pages) {
            this.title = title;
            this.author = author;
            this.publisher = publisher;
            this.content = content;
            this.pages = pages;
        }
    
        public Book(String title, String author, String publisher, String content) {
            this.title = title;
            this.author = author;
            this.publisher = publisher;
            this.content = content;
            this.pages = 0;
        }
    
        public void printInformation() {
            System.out.println("The book \"" + this.title + "\", written by " + this.author + " and published by " + this.publisher + " has " + Integer.toString(this.pages) + " pages.");
        }
        
        public void printPage(int page, int charactersPerPage) {
            page -= 1;
            String pageContent = this.content.substring(charactersPerPage * page, charactersPerPage * (page+1));
            System.out.println(pageContent);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Book myFaveBook = new Book(
                "The Tragedy of Mr. Mortensen, Teacher of A101",
                "Shuban Pal",
                "Crusaders of FreeBSD",
                "A child is a monkey in its mother's eye. Yet that child dreams of going on a wild journey, far beyond her reach."
                5
            );
            
            myFaveBook.printPage(1, 18);
            myFaveBook.printInformation();
        }
    }
    

    Here, we were able to make our code much more readable. In addition, if we have more books in the future, it’s likely that we’ll reuse these functions.

    Void Methods are functions in classes which have no return value.

    ❓ What is a return value? That’s a surprise tool we’ll save for later!

    BREAK TIME!!!

    Take a quick stretch, complain about the lesson being boring to your friends, and laugh and sob uncontrollably from no longer having to force your skibidi ohio selves to be locked in and focusing.

    Section 2.4: Calling a Void Method with Parameters

    Small Recap: Methods in Python vs Java

    image-2.png

    image.png

    • Python 🐍: Here, the method is getInfo() and it is provided by the Animal class. Whenever a new Animal class is declared, the getInfo() method can be used upon itself to get the info of the new class based on its group.
    • Java ☕: Here, the method is also getInfo() which is also provided by the animal class. This time, the Animal class can be initialized via constructors

    Method Signatures

    A method signature is basically the piece of code which lists how the method should act before specific code is given to the method. For example, for the main function the signature states that the method is a public method, the method is a static method, the method returns a void type, and it takes in the argument args[] as a String type.

    public class Main {
        public static void main(String args[]) {
            System.out.println("📝 Main method is executed, method has nothing to return.");
        }
    }
    
    Main.main(new String[]{});
    

    In the code above, the method signature is public static void main(String args[]) which is the standard way to write main methods in java. Here is an anatomy of each piece:

    • public ➡️ Make sure the method can be used outside of the Main class
    • static ➡️ Make sure the method is a feature packaged into the class and does not work based off of an instance of that class
    • void ➡️ The return type. If the method is set to return nothing, void must be the return type.
    • name(type arg1, type argn) ➡️ The name of the method. Methods can be named! The elements listed inside the parentheses next to the name of the method are parameters. They are the values which the method takes in. If the method is set to take no parameters, the parenthesis can be left empty (e.g. name()).

    image.png

    • 👁️ Visibility Modifiers: public or `private
    • 🔀 Optional: static or blank
    • 📩 Return Type: void, int, char, double, String, or any other datatype
    • 🔤 Name: Anything!
    • 📃 Parameter(s): A list of values that will be passed into the method in type name format

    Method Parameters

    The Methodical Methods of the Java Method Parameter:

    • 1️⃣ RULE 1 - Parameters MUST be passed in order
    • 2️⃣ RULE 2 - Parameters MUST be seperated by comma
    • 3️⃣ RULE 3 - Parameters MUST include a datatype specification and a name
    • 3️⃣ RULE 4 - Parameters MUST be referenced by their names inside the method

    🤮🤢🗑️😭1️⃣ BAD 1️⃣😭🗑️🤢🤮

    public static void funny_method(int funny_number, String funny_string) {
        System.out.println(funny_number);
        System.out.println(funny_string);
    }
    
    funny_method("cat", 1);
    



    🤑💸🪙😎5️⃣ GOOD 5️⃣😎🪙💸🤑

    // Initiate method
    public static void funny_method(int funny_number, String funny_string) {
        System.out.println(funny_number);
        System.out.println(funny_string);
    }
    
    // Call method
    funny_method(1, "cat");
    

    Method Overload

    Method overload occurs when a method of the same name but different parameters. The signature of a method does NOT include the return value though for overloading purposes. Imagine you have a method called printTwoNumbers() and you had 3 implementations of it as shown below.

    public void printTwoNumbers() {
        System.out.println(1);
        System.out.println(1);
    }
    
    public void printTwoNumbers(int number) {
        System.out.println(number);
        System.out.println(number);
    }
    
    public void printTwoNumbers(int number1, number2) {
        System.out.println(number1);
        System.out.println(number2);
    }
    

    For each of the 3 method calls below, what would happen?

    • Method call 1: printTwoNumbers(2);
    • Method call 2: printTwoNumbers();
    • Method call 3: printTwoNumbers(5, 6);
    printTwoNumbers(2);
    printTwoNumbers();`
    printTwoNumbers(5, 6);
    

    When printTwoNumbers(2) was called, compiler started looking for a signature which had the name printTwoNumbers which took 1 parameter and as an int. When printTwoNumbers() was called, compiler started looking for a signature which had the name printTwoNumbers which took no parameters at all. When printTwoNumbers(2) was called, compiler started looking for a signature which had the name printTwoNumbers which took 2 parameter and both as an ints.

    Section 2.5: Calling a Non-Void (Shuban)

    What is a Non-Void Method?

    A non-void method is a method which has a defined return type. This return type is stated in the function’s signature. As a recap from earlier, we made a bullet list of every component inside of a method’s signature. Here is a recap of the return type segment of a method’s signature.

    📩 Return Type: void, int, char, double, String, or any other datatype

    Here is a list of signatures. For each signature, you must be able to tell whether the method corresponding to that signature will be a non-void method or not.

    1. public static int function_1(String string)
    2. private static void function_2(int number)
    3. public double function_3(int number)
    4. private void function_4(double funnyDouble)
    5. private int function_5(double notFunnyDouble)
    6. public void function_6(char funnyChar)
    public class MathMachine {
        private static boolean isEven(int num) {
            if (num%2 == 0) {
                return true;
            } else {
                return false;
            }
        }
    
        public static void getEvenOrOdd(int num) {
            if (isEven(num) == true) {
                System.out.println("Number is even");
            } else {
                System.out.println("Number is odd");
            }
        }
    }
    
    MathMachine.getEvenOrOdd(2);
    MathMachine.getEvenOrOdd(3);
    

    In the example above, the class isEven is a Non-Void method while getEvenOrOdd is not. In a Non-Void method, there is always a type to be returned. This value is essentually what calling the method will equal to based on the parameter it is called upon.

    In the case of isEven, the return type was a boolean or a datatype which stores either true or false. Accordingly, whenever isEven was called as a method, its assignment would be to whatever value was returned based on its parameter.

    Calling Non-Void Methods

    Calling a Non-Void method is the same as calling a void method, except a return value is produced and assigned to the call. Due to this sort of structure, non-void methods are classically used when comparing return values. For example, in the case of isEven:

    private static boolean isEven(int num) {
        if (num%2 == 0) {
            return true;
        } else {
            return false;
        }
    }
    

    The return type is a boolean. So whenever isEven(n) is referenced, where n is an integer, the value of isEven(n) gets assigned to either true or false based on the value of n or any underlying logic inside the method. That is why in the code below, isEven(n) can be compared directly to a tangiable boolean value.

    public static void getEvenOrOdd(int num) {
        if (isEven(num) == true) {
            System.out.println("Number is even");
        } else {
            System.out.println("Number is odd");
        }
    }
    

    PRACTICE Calling Methods: Method Golf 😋

    ⛳ Link to Method Golf: https://shuban-789.github.io/Shuban-CSA/2024/09/18/method-golf.html

    String Objects - Concatenation, Literals, and More

    Creating Strings:

    public class stringobjects
    {
        public static void main(String[] args)
        {
            String name1 = "Skibidi";
            String name2 = new String("Sigma");
            String name3 = new String(name1);
    
            System.out.println(name1);
            System.out.println(name2);
            System.out.println(name3);
        }
    }
    
    stringobjects.main(null);
    
    Skibidi
    

    📝 Three Ways to Create a String: Let’s Break it Down!


    First Option:

    This method of creating a string consists of the following three parts:

    Class Name: Defines the type of variable (String, Integer, Array, etc.)

    Variable Name: The name assigned to the variable. This is how the variable will be referenced in the rest of the program.

    String Value: The actual value you’d like to assign to the variable


    Second Option:

    This method is similar to option one but consists of a few extra components (indicated in pink coloring below):

    Class: Again, defines the type of the variable (String, Integers, Arrays, etc.)

    Variable Name: How the variable will be referenced in the rest of the program

    new: A Java keyword which is used to explicitly instantiate a new object.

    Class Name (Part 2): The ‘new’ key word must be followed with the class name of the object being created (in this case, String)

    String Value: The actual value you’d like to assign to this variable


    Third Option:

    Finally, a string can be created using the value of another, existing string object. The components needed for this declaration are as follows:

    Class Name: Again, type of variable will it be? (String, Integers, Arrays, etc.)

    Variable Name: The name of the variable

    Java Keyword ‘new’: The new keyword in Java is used to explicitly create a new object.

    Class Name (Part 2): As indicated before, the new keyword has to be followed with the class name of the object being created.

    Variable Name (Part 2) The name of the variable whose value you want the new variable to take on.

    Importantly, regardless of which creation method you choose, String objects are immutable. This means that every time you attempt to change the value of some string variable, under the hood, a new string object is created with the updated value, and your variable name is used to reference this new object.

    📝 What are Concatentations?

    Concatentations are the joining of strings using operators such as “+=” and “+”.

    There are two primary ways to combine strings. Assume a, b, and c are previously created string variables.

    • a += b : Appends the string value stored in b to the string value stored in a. In the processs, a is redefined to equal this newly appended string.
    • c = a + b : Joins the string values of a and b together, but doesn’t redefine either a or b. Instead, the resultant value is assigned to c.
    public class concatentations
    {
        public static void main(String[] args)
        {
            String name1 = "Skibidi";
            String name2 = new String("Sigma");
            String name3 = new String(name1);
    
            int number1 = 1;
            int number2 = 2;
            String combine = name1 + "" + number1;
            name1 += number2; 
    
            System.out.println(name1); 
            System.out.println(combine);
        }
    }
    
    concatentations.main(null);
    
    Skibidi2
    Skibidi1
    

    Let’s do an exercise for practice! What will the following code segment print?

    public class concatentations
    {
        public static void main(String[] args)
        {
            String name1 = "Skibidi";
            String name2 = new String("Sigma");
            String name3 = new String(name1);
    
            name1 += "!!"
            String mystery = name1 + name2 + name3
    
            System.out.println(mystery);
        }
    }
    
    // Uncomment the following method call to run the code and check your answer!
    // concatentations.main(null);
    

    📝 Backwards and Forwards Slashes

    In Java, there are a few characters with pre-assigned purposes. Backwards and forwards slashes are such characters, and they can be easy to mix up, so it’s important to pay close attention to them!

    \: A backward slash is used to start escape sequences. In other words, it can allow you to add special characters to your string as well as specify certain ‘actions.’ We’ll see more on this later, in the form of a few examples.
    /: A forward slash is traditionally used as a division operator. Two forward slashes indicate the beginning of a comment.

    Backslashes

    \" = Indicates that the double quote character isn’t delimiting a new string, but is rather part of the string being written/printed

    \\ = Similarly, indicates that the double quote character isn’t delimiting a new string, but is rather part of the string being written/printed

    \n = Prints on a new line

    public class SlashDemo {
        public static void main(String[] args) {
            // Using backslashes for escape sequences:
            System.out.println("This is a double quote: \"");  // Prints a double quote
            System.out.println("This is a backslash: \\");     // Prints a backslash
            System.out.println("This prints on a new line:\nSecond line starts here");
    
            // Using forward slashes for division and comments:
            int a = 10;
            int b = 2;
            int result = a / b; // Division operation
    
            System.out.println("Result of 10 / 2 is: " + result); // Prints the result of the division
        }
    }
    
    SlashDemo.main(null)
    
    This is a double quote: "
    This is a backslash: \
    This prints on a new line:
    Second line starts here
    Result of 10 / 2 is: 5
    

    📝 String methods

    The following are some important methods that can be used on String objects.

    Method Description
    String(String str) Constructs a new String object that represents the same sequence of characters as str
    int length() Returns the number of characters in a String object
    String substring(int from, int to) Returns the substring beginning at index from and ending at index to - 1
    String substring(int from) Returns substring(from, length())
    int indexOf(String str) Returns the index of the first occurrence of str; returns -1 if not found
    boolean equals(String other) Returns true if the calling string is equal to other; returns false otherwise
    int compareTo(String other) Returns a value < 0 if the calling string is less than other in alphanumeric order; returns zero if it is equal to other; returns a value > 0 if it is greater than other
    public class intDemo {
        public static void main(String[] args) {
            String wordOfDay = new String("Skibidi");
    
    
            System.out.println("This should return the length of the word 'Skibidi'");
            System.out.println(wordOfDay.length());
    
        }
    }
    
    intDemo.main(null)
    
    This should return the length of the word 'Skibidi'
    7
    
    public class indexOfDemo {
        public static void main(String[] args) {
            String wordOfDay = new String("Skibidi");
    
            System.out.println("\nThis should return -1, since there is no n in the string");
            System.out.println(wordOfDay.lastIndexOf("n"));
    
            System.out.println("\nThis should display the index of d (5)");
            System.out.println(wordOfDay.lastIndexOf("d"));
        }
    }
    
    indexOfDemo.main(null)
    
    This should return -1, since there is no n in the string
    -1
    
    This should display the index of d (5)
    5
    
    public class substringOfDemo {
        public static void main(String[] args) {
            String word = new String("skibidi");
    
            System.out.println("\nThis should display the letters between the 2nd and 6th");
            System.out.println(word.substring(2,6));
        }
    }
    
    substringOfDemo.main(null)
    
    This should display the letters between the 2nd and 6th
    ibid
    

    Quick, let’s do an exercise for practice! What will the following code segment return?

    public class substringOfDemo {
        public static void main(String[] args) {
            String word = new String("skibidi");
    
            System.out.println("\nWhat is printed if we only pass one parameter into the substring method?");
            System.out.println(word.substring(2));
        }
    }
    
    // Uncomment the following method call to run the code and check your answer!
    // substringOfDemo.main(null)
    
    public class compareToDemo {
        public static void main(String[] args) {
            String word = new String("skibidi");
            String word2 = new String("skibidi1");
            String word3 = new String("skibidi");
    
            System.out.println("\nIf word is < word2, a negative value will be printed. If they are equal, 0 will be printed, and if word > word2, a positive value is printed");
            System.out.println(word.compareTo(word2));
    
            System.out.println("\nComparison between word and word3");
            System.out.println(word.compareTo(word3));
        }
    }
    
    compareToDemo.main(null)
    
    This displays if word1 = word2, if false it returns -1, if true it returns 0
    -1
    
    This displays if word1 = word2, if false it returns -1, if true it returns 0
    0
    
    public class equalToDemo {
        public static void main(String[] args) {
            String word = new String("skibidi");
            String word2 = new String("skibidi1");
            String word3 = new String("skibidi");
    
            System.out.println("\nThis displays if word1 = word2, if false it returns false, if true it returns true");
            System.out.println(word.equals((word2)));
    
            System.out.println("\nThis displays if word1 = word3, if false it returns false, if true it returns true");
            System.out.println(word.equals((word3)));
        }
    }
    
    equalToDemo.main(null)
    
    This displays if word1 = word2, if false it returns false, if true it returns true
    false
    
    This displays if word1 = word3, if false it returns false, if true it returns true
    true
    

    Lesson 2.8: Wrapper Classes!

    Introduction

    By now, you should be used to working with different variables and data types in Java. Some of you may have asked a question regarding why the data type String has a capital S, while int is not capitalized.

    The answer is: String is a reference type, while int is a primitive type.

    Primitive types are the mosic basic data types in Java, and they always represent single values. On the other hand, Reference types are used to store objects and can have a variety of things stored.

    Important Wrapper Classes

    • Integer for int
    • Double for double

    These classes are part of the java.lang package, so you don’t need to import them explicitly. Additionally, there are more wrapper classes, but these are the two that are required by College Board.

    But let’s back off real quick. What is a Wrapper class?

    Answer: A wrapper class allows you to use primitive data types.

    Integer Wrapper Class

    The Integer class wraps a value of the primitive type int in an object.

    Methods & Constants

    1. Constructor: Integer (int value): Constructs a new Integer object representing the specified int value.
    2. Integer.MIN_VALUE and Integer.MAX_VALUE returns the minimum/maximum value that an int can hold. Going beyound these borders will lead to overflow.
    3. int intValue(): Returns the value of the Integer as an int

    Let’s take a look at an example:

    public class Main {
        public static void main(String[] args){
            Integer num1 = new Integer(5);  // Constructor usage 
    
            System.out.println("num1 = " + num1);
            System.out.println("num2 = " + num2);
            System.out.println("Maximum value of Integer: " + Integer.MAX_VALUE);
            System.out.println("Minimum value of Integer: " + Integer.MIN_VALUE);
            System.out.println("num1 as int: " + num1.intValue());
        }
    }
    

    Double Wrapper Class

    The Double class wraps a value of the primitive type double in an object.

    Important Methods

    1. Constructor: Double(double value): Constructs a new Double object representing the specified double value.
    2. double doubleValue(): Returns the value of the Double as a double

    Let’s take a look at another example.

    public class Main {
        public static void main(String[] args){
            Double pi = new Double(3.14159); 
            Double e = Double.valueOf(2.71828);
    
            System.out.println("pi = " + pi);
            System.out.println("e = " + e);
            System.out.println("pi as double: " + pi.doubleValue());
        }
    }
    

    Autoboxing and Unboxing

    Java gives you automatic conversion between primitive types and their respective wrapper classes

    • Autoboxing: Primitive Value -> Wrapper Object
    • Unboxing: Wrapper object -> Primitive Value

    Let’s take a look at a short example.

    public class Main {
        public static void main(String[] args){
            Integer wrapped = 100;  // Autoboxing
            int unwrapped = wrapped;  // Unboxing
    
            System.out.println("wrapped = " + wrapped);
            System.out.println("unwrapped = " + unwrapped);
        }
    }
    

    Practice Exercises

    Fix the code below!

    public class Main {
        public static void main(String[] args) {
            integer num1 = 50;
            Integer num2 = new Integer(75);
            
            Double d1 = 3.14;
            double d2 = new Double(2.718);
            
            System.out.println("Sum of integers: " + (num1 + num2));
            System.out.println("Product of doubles: " + (d1 * d2));
        }
    }
    

    Now, complete the exercise below without any extra help.

    public class Main {
        public static void main(String[] args) {
            // TODO: Create an Integer object using autoboxing
            
            // TODO: Create a double primitive from a Double object (unboxing)
            
            // TODO: Print both values
        }
    }
    

    2.9: Using the Math Module

    Have you ever been stuck in your Calculus or Physics class because your calculator died? You can use the Java math module to help you!

    Introduction

    The Java math module is a package that comes with java.lang.Math. All it’s methods are static.

    This is more straightforward than wrapper classes, but still important to know.

    Useful Methods

    1. static int abs(int x): Returns the absolute value of an int
    2. static double abs(double x): Returns the absolute value of a double
    3. static double pow(double base, double exponent): Returns the value of the first value raised to the power of the second value
    4. static double sqrt(double x): Returns the (positive) square root of a double value
    5. static double random(): Returns a double greater than or equal to 0.0 and less than 1.0

    Let’s take a look at a code example using all of these!

    public class Main {
        public static void main(String[] args) {
            // abs() method for int and double
            int intNumber = -5;
            double doubleNumber = -10.5;
            System.out.println("Absolute value of " + intNumber + " is: " + Math.abs(intNumber));
            System.out.println("Absolute value of " + doubleNumber + " is: " + Math.abs(doubleNumber));
    
            // pow() method
            double base = 2.0;
            double exponent = 3.0;
            System.out.println(base + " raised to the power of " + exponent + " is: " + Math.pow(base, exponent));
    
            // sqrt() method
            double number = 16.0;
            System.out.println("Square root of " + number + " is: " + Math.sqrt(number));
    
            // random() method
            System.out.println("A random number between 0.0 and 1.0: " + Math.random());
        }
    }
    

    PRACTICE Strings, Integers, and Math

    Let’s try a practice! Fill in the function below, randomize, following the steps below:

    1. Take the absolute value of both numbers
    2. Return a random number in between those two numbers, inclusive
    import java.util.*;
    public class Main {
        public double randomize(double a, double b){
            // TODO: Enter code here! Don't forget a return statement
        }
        public static void main(String[] args) {
           Scanner scan = new Scanner(System.in);
           double a = scan.nextDouble();
           double b = scan.nextDouble();
    
           System.out.println(randomize(a, b));
        }
    }
    

    Homework

    Now, it’s time to practice! The following problem will incorporate the following concepts:

    • Classes
      • Constructors
    • Methods
      • Void methods
      • Non-void methods
    • Math class
    • Integer and Double wrapper classes
    • String methods
    public class Circle {
        // 1. Class variable: radius (double)
    
        // 2. Make a constructor that takes in the radius as a parameter, and sets the radius property
    
        // 3. cirumference() method: Calculate and return the circumference
    
        // 4. area() method: Calculate and return the area, use Math.pow()
    }
    
    public class Student {
        // 1. Class variables: name (String) and grade (Integer)
    
        // 2. Constructor to initialize name and grade
    
        // 3. nameLength() method: Return the length of the student's name
    
        // 4. getGradeAsDouble() method: Return the grade as the Double wrapper type
    
        // 5. getScaledGrade() method: Return grade divided by 2
    }
    
    public class Main {
        public static void main(String[] args) {
            // Testing the Circle class
            Circle circle1 = new Circle(5.0);
            Circle circle2 = new Circle(7.0);
    
            System.out.println("Circle 1:");
            System.out.println("Radius: " + circle1.radius);
            System.out.println("Circumference: " + circle1.circumference());
            System.out.println("Area: " + circle1.area());
    
            System.out.println("\nCircle 2:");
            System.out.println("Radius: " + circle2.radius);
            System.out.println("Circumference: " + circle2.circumference());
            System.out.println("Area: " + circle2.area());
    
            // Testing the Student class
            Student student1 = new Student("Aadit", 75);
            Student student2 = new Student("Emily", 45);
    
            System.out.println("\nStudent 1:");
            System.out.println("Name: " + student1.name);
            System.out.println("Name Length: " + student1.nameLength());
            System.out.println("Grade: " + student1.getGradeAsDouble());
            System.out.println("Scaled Grade: " + student1.getScaledGrade());
    
            System.out.println("\nStudent 2:");
            System.out.println("Name: " + student2.name);
            System.out.println("Name Length: " + student2.nameLength());
            System.out.println("Grade: " + student2.getGradeAsDouble());
            System.out.println("Scaled Grade: " + student2.getScaledGrade());
        }
    }