Homework 2: Java Intro

Lectures needed for this homework: Lecture 1 (Welcome to 61B, Intro to Java) 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) {
    IO.println(i);
    i++;
}
  • The parentheses, ( and ) around the condition are required.
  • In Java, ++ is often used instead of += 1, though Josh prefers +=.
  • As of Java 25, we print with IO.println. In older Java code (and most code on the internet), you’ll see the wordier System.out.println instead — more on that in Lecture 2.
  • 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 ++) {
    IO.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 --) {
  IO.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) {
    IO.println("FizzBuzz");
} else if (i % 3 == 0) {
    IO.println("Fizz");
} else if (i % 5 == 0) {
    IO.println("Buzz");
} else {
    IO.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...
IO.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) {
    IO.println("\"hello\" in s");
}
for (int i = 0; i < s.length(); i++) {
    char letter = s.charAt(i);
    IO.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.
  • If you see a yellow squiggly underline, this is IntelliJ providing you a “Quick-Fix” to potentially improve your code. In this case, it is most likely suggesting for you to “Convert variable output from String to StringBuilder” due to “String concatenation += in loop”. You can either accept this suggestion or ignore it, either works. We highly recommend understanding the suggestion before choosing to accept it, in this case using a StringBuilder is a more appropriate choice for string concatenation due to its mutability, which we’ll cover in a future lecture.

Sample Programs

Python Java
print("Hello World")
public class HelloWorld {
    void main() {
        IO.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;
    }

    void main() {
        if (isPrime(1337)) {
            IO.println("1337 is prime.");
        } else {
            IO.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 void main() method. This is different from Python, where code can be executed outside of a function.
  • Before Java 25, the main method had to be declared with the full incantation public static void main(String[] args) — you’ll see that form in older resources, and we’ll learn what it means in Lecture 2.

Programming Exercises

Provenance Setup

  • Before starting this homework, follow the Provenance Guide to set up Provenance for your computer.
  • Provenance is REQUIRED, and submissions where Provenance was not installed before starting on the assignment will receive no credit.

Setup

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.

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

Task 1: Star Triangle 5

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.

For all tasks in this homework, you can run the main method to check your work. In IntelliJ, click the green Play button, and the program output will appear at the bottom of the window.

Note: This homework uses Java 25 syntax, matching Lecture 1: the main method is declared void main(), and we print with IO.println. Older 61B resources (and most Java code on the internet) declare main as public static void main(String[] args) and print with System.out.println — we’ll cover those forms in Lecture 2.

Task 2: Star Triangle N

Let’s generalize. 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
}

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

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.

Note that all of the syntax you need is available earlier on this page.

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

Open DoubleUp.java in IntelliJ and fill in the doubleUp method. Keep in mind that doubleUp should return a value, not print.

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

Submission

Make sure your Provenance files are added by following the Provenance Guide, then follow the Assignment Workflow Guide to submit.

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

Congratulations on finishing the homework!