Intro to Java

Before we start

We will be using Eclipse as our IDE for this course.

It’s good practice to have a working environment folder and work within projects. (DEMO)

I’ll create a GettingStarted project, and then a new class called HelloWorld

Opt to create a public main method

System.out.println("Hello World!");

Typing

  • Python does dynamic typing
word = "car"
number = 3
new_list = []
names = ["Pedro", "Melissa", "Jessica"]
  • Static typing in Java
String word = "car";
int number = 3;
List<Integer> newList = new List<>();
List<String> names = new List<>();

Try it out

Modify your main method in your HelloWorld class to assign the string literal "Hello World!" to a String variable name, and then print out that variable instead.

Questions:

  • Can you use both double and single strings to create the variable?

  • Does concatenation with the + operator work?

  • Can we concatenate String, char and int (or a combination of these)?

Try it out – solution

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String message = "Hello World!";
        char space = ' ';
        int number = 210;
        System.out.println(message + space + number);

    }

}

Variable assignment

  • To declare and give initial values to variables use =, which means becomes or take on the value of (assignment)
int credits = 4;
double grade = 3.67;
String name = "Chris";
int hours = 10;
boolean ready = hours >= 8;

Question:

  • Can you change the type of a variable in Java?

  • Why are certain types all lower-cased, while others are title cased?

Types

All primitive types in Java and lower-cased.

A primitive cannot have a method attached to it and connat be subclasses (there is no Object)

Java types that start with a upper case are Objects.

Comments

  • Java requires a lot of code to express a simple concept.
  • You need to be much more explicit when writing Java than Python (more words to type in Java)
  • Comments are extra important
// one line comment

/*
  multi-line
  comment
 */
    
/**
 * JavaDoc comments for external documentation
 * @returns description of what returns   
 */

JavaDoc Comments

JavaDoc comments may be placed above any class or method

Two sections:

  • description
  • standalone block tags (marked with @)

Practice

Create a Java application that determines if an integer is odd or even

Solution 1

public class OddsOrEvens {

    public static void main(String[] args) {
        int number;
        number = 3;
        boolean result = number % 2 == 0;
        System.out.println(result);

    }

}

Solution 2

public class OddsOrEvens {
    
    public static boolean isOdd(int number) {
        return number % 2 == 1;
    }
    
    public static boolean isEven(int number) {
        return number % 2 == 0;
    }

    public static void main(String[] args) {
        System.out.println(isOdd(3));
        System.out.println(isEven(3));

    }

}

Solution 3

public class OddsOrEvens {
    
    public static boolean isOdd(int number) {
        // if integer is not divisible by 2, it's odd
          return number % 2 == 1;
    }
    
    public static void main(String[] args) {
          int number;
          number = 6;
          if (isOdd(number)) {
            System.out.println(number + " is odd.");
          } else {
            System.out.println(number + " is even.");
          }

    }

}

Gradescope Attendance

Submit a java class called OddEven to Gradescope that contains two public methods:

  • isOdd(int number) takes an integer as argument and returns a boolean
  • isEven(int number) takes an integer as argument and returns a boolean

Add package com.gradescope.oddeven; to the top of your .java file

Make sure you are spelling things correctly: to help you with that I created a checklist

Scanner

Let’s import the Scanner package from Java utils and use it to get user input.

import java.util.Scanner;

Here’s the call:

Scanner keyboardScanner = new Scanner(System.in);
int number = keyboardScanner.nextInt();
  • Add these to your solution.
  • Remember to tell the user what to enter.
  • What’s the difference between .println() and print()?

Solution

import java.util.Scanner;

/**
 * File: OddsOrEvens.java
 * Author: Adriana Picoral
 * Description: Asks for user to input an integer, and prints out
 * whether that number is odd or even
 */
public class OddsOrEvens {
    
    /**
     * Description: Determines if an integer is odd
     * @param number (integer)
     * @return boolean (true if param is odd, false otherwise)
     */
    public static boolean isOdd(int number) {
        return number % 2 == 1;
    }
    

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

          // calls isOdd to determine if number is odd or even
          if (isOdd(number)) {
            System.out.println(number + " is odd.");
          } else {
            System.out.println(number + " is even.");
          }

    }

}

Practice

Write an application (HoursMinutesSeconds.java) that prompts the user to enter an integer representing number os seconds.

Your application should print the equivalent hours, minutes, and seconds in this format: hours:minutes:seconds

Run examples:

Enter the number of seconds: 3661
1:1:1

Enter number of seconds: 8274
2:17:54

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

adapted from Rick Mercer’s slides

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.java file to the Programming Problem 01 on gradescope

Remember to add the package info at the top of your file:

package com.gradescope.hms;

Output needs to match exactly what is expected.

The message to the user (for input) should be "Enter number of seconds: " exactly (with the space after : and no line break)

Expand

Improve your code so that it prints out HH:MM:SS format

Enter number of seconds: 8274
02:17:54

Enter number of seconds: 233
00:03:53

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 a string representing number of hours
     */
    public static String getHours(int seconds) {
        int hours = seconds / 3600;
        String fullHour = "" + hours;
        
        if (hours < 10) {
            fullHour = "0" + hours;
        }
        
        return fullHour;
    }
    
    /**
     * Calculates number of full minutes left in many seconds
     * not considering the number of full hours
     * @param seconds (integer)
     * @return a string representing number of minutes
     */
    
    public static String getMinutes(int seconds) {
        int minutes = seconds  % 3600 / 60;
        String fullMinutes = "" + minutes;
        
        if (minutes < 10) {
            fullMinutes = "0" + minutes;
        }
        
        return fullMinutes;
    }
    
    /**
     * Calculates seconds left that are not in full minutes
     * @param seconds (integer)
     * @return an integer representing seconds
     */
    public static String getSeconds(int seconds) {
        int secondsLeft = seconds % 60;
        String fullSeconds = "" + secondsLeft;
        
        if (secondsLeft < 10) fullSeconds = "0" + secondsLeft; 
        
        return fullSeconds;
    }

    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);

    }

}

Java operators

Three boolean operators:

  • ! not
  • || or
  • && and

The other operators are the same as Python:

  • * multiplication, / division, % modulus
  • + addition/concatenation, - subtraction
  • < less, > greater,<= less or equal, >= greater or equal, == equal, != not equal

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 a class called LeapYear to gradescope with the following public static method:

  • isLeap(int year) returns either "Leap Year" or "Regular Year"

Package

package com.gradescope.leapyear;

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));

    }
}