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 |
---|---|
|
|
- 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 int s are unbounded, Java int s have a (large) max and min value. |
float |
double |
Decimal values. Java doubles are again bounded. |
str |
String |
Java String s 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+=
. - 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 |
---|---|
|
|
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
for
loop. - Similarly to
++
,--
is often used instead of-= 1
. - The
for
loops 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
elif
andelse 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 ^ 10
is 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 static
in front. We’ll learn what these mean later. - Calling a function looks the same as in Python.
Strings
Python | Java |
---|---|
|
|
- In Java,
String
s 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
String
s, and it will be implicitly converted to aString
without needing to explicitly cast.
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
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.
-
If you wrote code in the Java Visualizer, upload
StarTriangle5.java
,StarTriangleN.java
,PrintIndexed.java
, andDoubleUp.java
to the Homework 2 assignment on Gradescope.When you’re uploading your files, it should look like this on Gradescope:
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.