Homework 0A: Java Syntax

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.
  • 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 (counting up)

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.

for Loop (counting down)

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.

Function Declaration and Usage

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.

Programs

Now that we’ve covered individual language constructs, let’s look at some Java programs that use them. Here are some simple ones that you might find yourself referring to if you forget how to do something.

Hello World

Python Java
print("Hello World")
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
  • 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.

Exercises

Make sure you have completed Lab 1 before continuing on.

UW has a large collection of introductory Java exercises on a site called Practice-It that we will be borrowing. For HW 0A, we’ve picked a few of these exercises for you to complete!

Note: the University of Washington has limited access to Practice-It and is planning on discontinuing the service. You are not required (or expected) to log in to Practice-It to complete this assignment. See the Deliverables section for explicit instructions on how to complete HW 0A.

  • Self-Check 1.26: Confusing
  • Exercise 2.5: starTriangle
  • Self-Check 2.25: numberTotal
  • Exercise 3.23: printIndexed
  • Exercise 4.17: stutter
  • Self-Check 4.5: ifElseMystery1
  • Exercise 4.19: quadrant

We have provided some skeleton code to get you started. To obtain the skeleton code, follow the normal assignment workflow.

Once you have the skeleton code, open it in IntelliJ. You will find problem descriptions for each of the tasks in the comment above the corresponding method signature. You are required to complete starTriangle, printIndexed, stutter, and quadrant for full credit. We encourage you to complete Confusing, numberTotal, and ifElseMystery1 as well, but we won’t be grading these.

If you run into trouble with the exercises, one strategy could be solving in Python first, then translating that to Java. If you’re having trouble with solving in Python, that’s fine, and not the point of this exercise. If you’d like to reference Python solutions, see the dropdowns below.

starTriangle

for i in range(5):
    line = ""
    for j in range(5 - i - 1):
        line += " "
    for k in range(i + 1):
        line += "*"
    print(line)

printIndexed

def printIndexed(s):
    output = ""
    for i in range(len(s)):
        output += s[i]
        output += str(len(s) - 1 - i)
    print(output)

stutter

def stutter(s):
    output = ""
    for i in range(len(s)):
        output += s[i]
        output += s[i]
    return output

quadrant

def quadrant(x, y):
    if x == 0 or y == 0:
        return 0
    elif y > 0 and x > 0:
        return 1
    elif y > 0 and x < 0:
        return 2
    elif y < 0 and x < 0:
        return 3
    else:
        return 4

Deliverables

You have two options for receiving credit on this assignment.

  • Submit a working implementation to Homework 0A: Code
  • Submit a screenshot to Homework 0A: Screenshots

If you are completing HW 0A for the first time, you must complete the exercises in the skeleton files. Once you have commited and pushed your work to your remote repository, you can submit your code to Homework 0A: Code on Gradescope. If you pass all of the autograder tests, you have finished the assignment!

If you’ve already done HW 0A previously before (e.g. you enrolled in 61B in an earlier semester but dropped it), you can submit the screenshot you used previously showing earlier completion dates for the Practice-It exercises. You don’t need to do anything else, but we highly encourage to redo any exercises that you are unfamiliar with to brush up.

Note: If you are having trouble getting your screenshot into the PDF format required by Gradescope, try using this converter.

Congratulations! You’re prepared for the next few lectures, and have completed HW 0. After Lecture 2, you’ll be ready to read HW0B, but you can get a head start now if you’d like.

A programming language is not too different from a spoken language – in particular, you will get better the more code you write. The PracticeIt site has many problems available, and you should feel free to attempt more. (Their progression doesn’t exactly match ours, though – if you see a Scanner or need to generate a random number, you can skip that problem.)

We also recommend https://codingbat.com/java/AP-1, which has more advanced Java problems.