HW 0A: A Java Crash Course (Part 1)

Introduction #

In this assignment, we will go through basic Java syntax. Since roughly 98.5% of you have used Python, everything in this homework is similar to a Python concept. This homework does NOT require that you know Python. Even if you don’t know Python, you’ll see that Python code is almost like pseudocode and should therefore be readable.

If you’ve written code in C or C++, you’ll see that Java is very similar.

For the 0.3% of you who have never written code in Python, C, or C++, please feel free to contact the staff if you need extra assistance understanding basic Java syntax.

This homework is due on Friday, January 20th! Early lectures, labs, and projects will rely on being able to read and understand the basic structure of Java code.

Goals and Outcomes #

In this HW, you will complete a few Java exercises, and translate your existing programming knowledge to Java. By the end of this HW you will:

  • Understand how fundamental constructs translate to Java.
  • Be able to read short Java snippets.
  • Be able to implement novel programs in Java.

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.

Exponentiation #

Python Java
x = 2**10
int 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 #

UW has a large collection of introductory Java exercises that we will be borrowing. For HW 0, create an account on Practice-It, and complete the following:

Make sure to follow the directions on the exercise page, especially for printing versus returning!

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(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

Once you’ve completed the 6 exercises, go to your list of solved problems, take a screenshot of the table, and submit the screenshot to HW 0A on Gradescope.

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.

Last built: 2023-10-26 18:40 UTC