Java Objects

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Classes

  • Collection of methods and attributes (information/values)
  • Template, blueprint of cookie cutter to construct many objects

Modularity: Classes allow us to split the problem to be solved into distinct tasks

You should be able to think about what a class does, not how it does it

Objects

Java Objects are titled case

  • String
    • Only object that gets special syntax (no need to call constructor with new)
    • Immutable
    • Use double quotes
  • Scanner
    • Represents specifically structured, text based input
    • Not necessarily “scanning” from the user

String

String is a class (title capitalization)

We can construct strings two ways:

String str = new String("with new");
String str2 = "Don't need new"

Some string methods:

.equals(String otherString)
.length() // len() function in python
.charAt(int index) // [] indexing in python
.substring(int beginIndex, int endIndex) // [:] indexing in python
.indexOf(String str) // .find() method in python

Objects

These work like pointers:

  • variable stores location, not object itself
  • variable defaults to null (meaning “not pointing to object”)

Comparison == not the same as .equals()

public static void main(String[] args) {
        String wordOne = new String("Hello");
        String wordTwo = new String("Hello");
        
        System.out.println(wordOne == wordTwo);
        System.out.println(wordOne.equals(wordTwo));

    }

Practice

Write an application (HoursMinutesSeconds.java) that, given number (integer) as seconds, it converts it to hours:minutes:seconds. Your application should print the equivalent hours, minutes, and seconds in this format: hours:minutes:seconds

Examples: 1 should be converted to the "0:0:1", 3661 should be converted to the "1:1:1", 8274 should be converted to the "2:17:54"

HINTS: There are 3600 seconds in one hour. Use % to calculate minutes and seconds left.

Solution

public class HoursMinutesSeconds {

    static int getHours(int seconds) {
        return seconds/3600;
    }

    static int getMinutes(int seconds) {
        return seconds/60;
    }

    static String getTime(int seconds) {
        // get full hours
        int hours = getHours(seconds);
        // update how many seconds are left
        int secondsLeft = seconds - (hours * 3600);
        // calculate full minutes
        int minutes = getMinutes(secondsLeft);
        // update how many seconds are left
        secondsLeft = secondsLeft - (minutes * 60);
        
        return hours + ":" + minutes + ":" + secondsLeft;
    }

    public static void main(String[] args) {
        int seconds = 119;
        String result = getTime(seconds);
        System.out.println(result);

    }
}

Scanner

The Scanner class (from java.util) is used to get different types of input

We use System.in to read keyboard input:

Scanner myObj = new Scanner(System.in);  // Scanner object
String userInputString = myObj.nextLine();  // method to read user input
int userInputInt = myObj.nextInt(); // another method to read user input

Solution

import java.util.Scanner;

/**
 * File: HoursMinutesSeconds.java
 * Author: Adriana Picoral
 * Description: Prompts the user to enter an integer representing seconds
 * and prints out time in h:m:s format
 */
public class HoursMinutesSeconds {
    
    /**
     * Calculates number of full hours in many seconds
     * @param seconds (integer)
     * @return an integer representing number of hours
     */
    public static int getHours(int seconds) {
        return seconds / 3600;
    }
    
    /**
     * Calculates number of full minutes left in many seconds
     * not considering the number of full hours
     * @param seconds (integer)
     * @return an integer representing number of minutes
     */
    
    public static int getMinutes(int seconds) {
        return seconds  % 3600 / 60;
    }
    
    /**
     * Calculates seconds left that are not in full minutes
     * @param seconds (integer)
     * @return an integer representing seconds
     */
    public static int getSeconds(int seconds) {
        return seconds % 60;
    }

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
          
        // prints out message to user
      System.out.print("Enter number of seconds: ");
      
        // get integer from keyboard entry
        int seconds = userInput.nextInt();
        userInput.close();
        
        // build up the message to print
        String message;
        message = getHours(seconds) + ":" + getMinutes(seconds);
        message += ":" + getSeconds(seconds);
        System.out.println(message);

    }

}

Submit solution to gradescope

Submit your HoursMinutesSeconds class file to gradescope.

Output needs to match exactly what is expected. "Enter number of seconds: " is the prompt to the user.

Practice

Write a Java application to check if a year is leap or regular

Leap years are those that are either:

  • divisible by 4 and not 100
  • divisible by 400

Submit your LeapYear class to gradescope. It should have a public static String isLeap(int year) method that returns "Leap Year" or "Regular Year".

Solution 1

import java.util.Scanner;

public class LeapYear {
    
    public static String isLeap(int year) {
        if ((year % 100 != 0) && (year % 4 == 0)) return "Leap Year";
        else if ((year % 400 == 0)) return "Leap Year";
        else return "Regular Year";

    }

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        
        // prints out message to user
        System.out.print("Enter a year: ");
      
        // get integer from keyboard entry
        int year = userInput.nextInt();
        userInput.close();
        
        System.out.println(isLeap(year));
    }
}

Solution 2

import java.util.Scanner;

public class LeapYear {
    
    public static String isLeap(int year) {
        boolean isLeapYear;
        
        isLeapYear = ((year % 100 != 0) && (year % 4 == 0));
        isLeapYear = isLeapYear || ((year % 400 == 0));
        
        if (isLeapYear) return "Leap Year";
        else return "Regular Year";

    }

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        
        // prints out message to user
        System.out.print("Enter a year: ");
      
        // get integer from keyboard entry
        int year = userInput.nextInt();
        userInput.close();
        
        System.out.println(isLeap(year));

    }
}

Other useful classes

Both Double and Integer classes have methods to cast a string into a double or int

Double.valueOf("10");
Integer.valueOf("10");
Integer.parseInt("10");