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 |
|---|---|
|
|
- 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 |
|---|---|
|
|
Java also has multi-line comments that are started by /* and ended by */.
while Loop
| Python | Java |
|---|---|
|
|
- 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 wordierSystem.out.printlninstead — 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 |
|---|---|
|
|
In Java, the for loop has the syntax:
for (initialization; termination; increment) {
// loop body
}
This is roughly equivalent to the while loops:
| Python | Java |
|---|---|
|
|
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 |
|---|---|
|
|
- Note the different “initialization”, “termination”, and “increment” blocks in the Java
forloop. - Similarly to
++,--is often used instead of-= 1. - The
forloops in the comparison table go “until”i < 0.
Conditionals
| Python | Java |
|---|---|
|
|
The boolean operators are as follows:
| Python | Java |
|---|---|
and |
&& |
or |
|| |
not |
! |
== |
== |
- Note the difference between
elifandelse 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 |
|---|---|
|
|
- Note that
^in Java is the “XOR” operator, not the exponentiation operation. That is,2 ^ 10is valid code, but it will return8, not1024.
Functions
| Python | Java |
|---|---|
|
|
- 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 staticin front. We’ll learn what these mean later. - Calling a function looks the same as in Python.
Strings
| Python | Java |
|---|---|
|
|
- In Java,
Strings are not directly iterable. We either iterate over an index and usecharAt, 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 aStringwithout 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
outputfromStringtoStringBuilder” due to “Stringconcatenation+=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 aStringBuilderis a more appropriate choice for string concatenation due to its mutability, which we’ll cover in a future lecture.
Sample Programs
| Python | Java |
|---|---|
|
|
|
|
- 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!