This site is under construction. All dates and policies are tentative until this message goes away.

Homework 2: Java Intro

Lectures needed for this homework: Lecture 1 (Introduction) recommended.

The most basic Java syntax isn’t worth spending time on in lecture. We’ll cover such syntax in Homeworks 2 and 3. Starting with Homework 4, the exercises will be based more directly on lecture content.

Language Constructs

Many Python fundamentals have a Java equivalent, such as loops and if statements. This section shows a direct comparison of the syntax.

Variable Declaration

Python Java
i = 0
int i = 0;
  • Just like Python, Java variables have types. In Java, to declare a variable, we have to explicitly say what type it is. A variable’s declared type can never change. Refer to Lecture 1 for more on “static typing.”
  • We also have to put a semi-colon at the end of the statement.

Types

Python Java What?
bool boolean Python uses True and False; Java uses true and false.
int int While Python ints are unbounded, Java ints have a (large) max and min value.
float double Decimal values. Java doubles are again bounded.
str String Java Strings use double quotes ("), and can be any text.
no equivalent char Java char represents a single character, and uses single quotes (').

Comments

Python Java
# This is a single line comment.
// This is a single line comment.

Java also has multi-line comments that are started by /* and ended by */.

while Loop

Python Java
i = 0
while i < 10:
    print(i)
    i += 1

int i = 0;
while (i < 10) {
    System.out.println(i);
    i++;
}
  • The parentheses, ( and ) around the condition are required.
  • In Java, ++ is often used instead of += 1, though Josh prefers +=.
  • We really do use System.out.println to print in Java. Sorry.
  • Instead of indenting, we use curly braces, { and } to wrap the code that is part of the while loop. Java doesn’t require indenting, but it’s good style!

for Loop

Python Java
for i in range(10):
    print(i)

for (int i = 0; i < 10; i ++) {
    System.out.println(i);
}

In Java, the for loop has the syntax:

for (initialization; termination; increment) {
    // loop body
}

This is roughly equivalent to the while loops:

Python Java
initialization
while termination:
    # loop body
    increment

initialization
while (termination) {
    // loop body
    increment
}

The while loops and the for loop exit when the termination condition is false. The for loops in the comparison table go “until” i = 10.

Here’s a for loop that counts down from 9 to 0 (inclusive):

Python Java
for i in range(9, -1, -1):
  print(i)

for (int i = 9; i >= 0; i --) {
  System.out.println(i);
}
  • Note the different “initialization”, “termination”, and “increment” blocks in the Java for loop.
  • Similarly to ++, -- is often used instead of -= 1.
  • The for loops in the comparison table go “until” i < 0.

Conditionals

Python Java
if i % 3 == 0 and i % 5 == 0:
    print("FizzBuzz")
elif i % 3 == 0:
    print("Fizz")
elif i % 5 == 0:
    print("Buzz")
else:
    print(i)

if (i % 3 == 0 && i % 5 == 0) {
    System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
    System.out.println("Fizz");
} else if (i % 5 == 0) {
    System.out.println("Buzz");
} else {
    System.out.println(i);
}

The boolean operators are as follows:

Python Java
and &&
or ||
not !
== ==
  • Note the difference between elif and else if.
  • Note: In Java, == is used for identity, and .equals() is used for equality. For primitive types, this means the same thing, but for reference types, it may be different. For this assignment, you do not need to know the difference; we’ll learn more about this later.

Exponentiation

Python Java
x = 2**10
double x = Math.pow(2, 10);
  • Note that ^ in Java is the “XOR” operator, not the exponentiation operation. That is, 2 ^ 10 is valid code, but it will return 8, not 1024.

Functions

Python Java
def greet(name):
    return "Hello, " + name

# Elsewhere...
print(greet("Josh"))
public static String greet(String name) {
    return "Hello, " + name;
}
// Elsewhere...
System.out.println(greet("Josh"));
  • In Java, functions have a specific return type that comes before the function name. Functions also specify their arguments’ types.
  • When a function returns nothing, it has a return type of void.
  • For now, all our functions will have public static in front. We’ll learn what these mean later.
  • Calling a function looks the same as in Python.

Strings

Python Java
s = "hello"
s += " world"
s += str(5)
s_length = len(s)
substr = s[1:5]
c = s[2]
if "hello" in s:
    print("\"hello\" in s")

for letter in s:
    print(letter)

String s = "hello";
s += " world";
s += 5;
int sLength = s.length();
String substr = s.substring(1, 5);
char c = s.charAt(2);
if (s.indexOf("hello") != -1) {
    System.out.println("\"hello\" in s");
}
for (int i = 0; i < s.length(); i++) {
    char letter = s.charAt(i);
    System.out.println(letter);
}
  • In Java, Strings are not directly iterable. We either iterate over an index and use charAt, or we convert it to an array (coming soon).
  • In Java, you can add anything to a Strings, and it will be implicitly converted to a String without needing to explicitly cast.

Sample Programs

Python Java
print("Hello World")
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
def is_prime(number):
    if number <= 1:
        return False
    # Check for factors from 2 up to
    # the square root of the number
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            return False
    return True

# Main part of the script
if is_prime(1337):
    print("1337 is prime.")
else:
    print("1337 is not prime.")
public class PrimeChecker {
    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(number); i += 1) {
            if (number % i == 0) {
                return false; 
            }
        }
        return true; 
    }

    public static void main(String[] args) {
        if (is_prime(1337)) {
            System.out.println("1337 is prime.")
        }
        else {
            System.out.println("1337 is not prime.")
        }
    }
}
  • All Java code must be in a class. We’ll learn more about classes later.
  • When a Java program is executed, it runs the public static void main(String[] args) method. This is different from Python, where code can be executed outside of a function.

Programming Exercises

Setup

For this homework only, you can choose either of these setup options:

  • If you finished Homework 1, then you can follow the Assignment Workflow Guide to get started with this assignment. The starter code is in the hw02 folder, and you can edit the code directly in IntelliJ.
  • If you have not finished Homework 1, you can click on the visualizer links below to edit your code directly in your web browser.

For these exercises, you will fill in StarTriangle5.java, StarTriangleN.java, PrintIndexed.java, and DoubleUp.java.

Task 1: Star Triangle 5

Click on the visualizer here (or open StarTriangle5.java in IntelliJ) and write the function starTriangle5. This should print out a right aligned triangle of stars where the first row contains 1 star, the second row contains 2 stars, and so on. That is, your code should output the picture below:

    *
   **
  ***
 ****
*****
/**
 * Prints a right-aligned triangle of stars ('*') with 5 lines.
 * The first row contains 1 star, the second 2 stars, and so on. 
 */
public static void starTriangle5() {
    // TODO: Fill in this function
}

You may use either for loops or while loops.

After your code is working correctly, copy and paste the code into the text editor of your choice, and save the code as StarTriangle5.java on your computer.

Task 2: Star Triangle N

Let’s generalize. Click on the visualizer here (or open StarTriangleN.java in IntelliJ), and write a function starTriangle(int N) that takes an integer N and prints a right-aligned triangle of stars with N lines. That is, if the argument to starTriangle is 6, the code should output the picture below:

     *
    **
   ***
  ****
 *****
******
/**
 * Prints a right-aligned triangle of stars ('*') with N lines.
 * The first row contains 1 star, the second 2 stars, and so on.
 */
public static void starTriangle(int N) {
    // TODO: Fill in this function
}

After your code is working correctly, copy and paste the code into a file called StarTriangleN.java on your computer.

LLM Experiment

Let’s try using an LLM. Using the LLM of your choice, copy and paste in the instructions for Task 2. Compare your solution with the version that the LLM created. Which do you like better? What surprises you about the code the LLM generates?

You do not need to write down an answer, though we will discuss your opinions in next week’s discussion section.

Now ask an LLM again, but include “Please include a helper function to make the code cleaner.”

What do you think about the code that ChatGPT generated? Do you like it more or less than previous solutions (including your own)?

You do not need to write down an answer, though we will discuss your opinions in next week’s discussion section.

Task 3: Print Indexed

Click on the visualizer here (or open PrintIndexed.java in IntelliJ) and fill in the printIndexed method.

/**
 * Prints each character of a given string followed by the reverse of its index.
 * Example: printIndexed("hello") -> h4e3l2l1o0
 */
public static void printIndexed(String s) {
    // TODO: Fill in this function
}

By the “reverse of its index”, we mean that the last character of the string is indexed 0, the second to last character is indexed 1, and so on.

We recommend completely avoiding using an LLM for Tasks 3 and 4, especially if you’re new to Java. If you do use an LLM, consider asking specific and small questions rather than just asking for the entire solution. Keep in mind that Midterm 1 will require you to write a lot of Java code on paper without any computer assistance. Note that all of the syntax you need is available earlier on this page.

When your code works, save the code to your computer as a file called PrintIndexed.java.

If you’d like, after you’re done, you’re welcome to use an LLM to generate alternate solutions and then compare with your solution.

Task 4: Double Up

Click on the visualizer here (or open DoubleUp.java in IntelliJ) and fill in the doubleUp method. Keep in mind that doubleUp should return a value, not print.

As before, we recommend avoiding using an LLM (even for hints or debugging help) to complete your work for this problem. All of the syntax you need is available earlier on this page.

/**
 * Returns a new string where each character of the given string is repeated twice.
 * Example: doubleUp("hello") -> "hheelllloo"
 */
public static String doubleUp(String s) {
    // TODO: Fill in this function
    return null;
}

When your code works, save the code as DoubleUp.java on your computer.

Submission

For this homework only, you can choose either of these submission options:

  • If you wrote code in IntelliJ, follow the Assignment Workflow Guide to submit.

    Gradescope GitHub submission screenshot

  • If you wrote code in the Java Visualizer, upload StarTriangle5.java, StarTriangleN.java, PrintIndexed.java, and DoubleUp.java to the Homework 2 assignment on Gradescope.

    When you’re uploading your files, it should look like this on Gradescope:

    Gradescope upload submission screenshot

You can submit as many times as you want. The score you see on Gradescope is your final score for this homework.

Congratulations! You’re completed Homework 2, and you are now prepared for Lecture 2. After Lecture 2, you’ll be ready to work on Homework 3, but you can get a head start now if you’d like.