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 |
---|---|
|
|
- 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
. - 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 |
---|---|
|
|
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
.
for
Loop (counting down)
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 return 8
, not 1024
.
Function Declaration and Usage
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
.
- When a function returns nothing, it has a return type of
- 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.
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 |
---|---|
|
|
- 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:
- Self-Check 1.26: Confusing
- Exercise 2.5:
starTriangle
- Self-Check 2.25:
numberTotal
- Exercise 3.23:
printIndexed
or Exercise 4.17:stutter
- Self-Check 4.5:
ifElseMystery1
- Exercise 4.19:
quadrant
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
starTriangle
for i in range(5):
line = ""
for j in range(i + 1):
line += "*"
print(line)
printIndexed
printIndexed
def printIndexed(s):
output = ""
for i in range(len(s)):
output += s[i]
output += str(len(s) - 1 - i)
print(output)
stutter
stutter
def stutter(s):
output = ""
for i in range(len(s)):
output += s[i]
output += s[i]
return output
quadrant
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
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.
This assignment is worth 5 points and due 1/19, 11:59 PM.