2. Java vs. Python
Python |
Java |
---|---|
1print("Hello, world!")
|
1public class SomeClass {
2 public static void main(String[] args){
3 System.out.println("Hello, world!");
4 }
5}
|
2.1. Variables and Types
Python |
Java |
---|---|
an_int = 5
a_float = 5.5
a_string = "5"
|
public class SomeClass {
public static void main(String[] args){
int anInt = 5;
double aFloat = 5.5; // doubles now for float
String aString = "5"; // Mind the double quotes
char aCharacter = '5'; // Single quote for character
}
}
|
Notice a few main differences:
We must declare the variables with their types
We will use the word
double
to be floating point numbersTechnically we could still use
float
, butdouble
is very commonA
float
takes up 4 bytes and adouble
takes up 8 — double the amount
We use
"double quotes"
for strings — single quotes are used for a single character:'a'
That does mean that we have a new type: a character (
char
)char theLetterB = 'B';
We use
// for comments
instead of# like in Python
We end our statements in Java with a semicolon (
;
)
Note
For the sake of brevity, from now on the class
stuff and public static void main(String[] args)
boilerplate
code will not be included in the code examples unless necessary.
Warning
In Python one could change the value stored in a variable to something of a different type. In Java, this is not possible since we need to be explicit about what the type of the value is to be stored in a variable.
If one writes code that would put a value of a type into a variable of another type, Java will not even compile the code; the code will not even run. At first this may seem frustrating, but this ends up being very helpful as it protects against certain bugs before the code even starts running.
Python |
Java |
---|---|
other_int = 5
other_int = 'totally not 5'
|
int otherInt = 5;
otherInt = "totally not 5"; // Compiler error
|
2.1.1. Declaring & Assigning Variables
There is a difference between declaring and assigning a variable
In Python, one did not need to explicitly declare variables
They got created and automatically declared once they are assigned a value
In Java, one must explicitly declare variables
This tells the computer that you need to set aside enough memory for something of the specified type
Python |
Java |
---|---|
1another_int = 11
2print(another_int)
|
1int anotherInt; // Declaration
2anotherInt = 11; // Assignment
3System.out.println(anotherInt);
|
However, in Java, one could declare and assign a variable in a single line of code, like in the above examples
int anotherInt = 11;
— variable is declared and assigned in a single line
2.1.2. Reusing Variables
Python |
Java |
---|---|
1a = 5
2print(a + 2)
3
4b = a + 7
5print(b)
6
7b = b + 1
8print(b)
9
10b += 1
11print(b)
|
1int a = 5;
2System.out.println(a + 2);
3
4int b = a + 7;
5System.out.println(b);
6
7b = b + 1;
8System.out.println(b);
9
10b += 1;
11System.out.println(b);
|
The Python and Java code is nearly the same
The difference with Java is the need to explicitly declare the variable the first time they are used
Note
Although it is fine to reuse variables, it is often not overly helpful. The above example really only makes sense given that they are arbitrary values stored in variables with nondescript names.
Consider a variable for storing a temperature in Celsius — temperatureInCelsius
. The circumstances where it
would make sense to assign a brand new value to this variable would be very limited.
2.1.3. Constants
Recall constants
Variables that are set by the programmer but are not changed throughout the execution of the program
Python, the language, does not enforce the rule that constants should not be altered
The idea of constants are maintained and respected among programmers
The convention is to use all upper case letters and separate words with underscores
THIS_IS_A_CONSTANT
Although one could change the values during execution, it would break the convention
Java will, however, ensure that the value of the constant is set once and not changed during execution
The special keyword
final
is used to declare a constantForces the variable to be set exactly once
If somehow no value was assigned, there will be a compiler error
Python |
Java |
---|---|
1SALES_TAX = 1.15 # Leave me alone
|
1final double SALES_TAX = 1.15;
|
Remember, it is possible to change a constant’s value before runtime
The point is that they will not change at runtime
2.2. Arrays
Java does not come with lists ready to go like Python does
They are not provided as a language primitive
Java does however have arrays, which are similar-ish to lists
They store data in a sequential linear collection
They have a fixed size
They have fewer built in functions
Python |
Java |
---|---|
1a_list = [10, 11, 12, 13]
2
3# Access the list at index 1
4print(a_list[1])
5
6# Modify the list at index 1
7a_list[1] = 21
8print(a_list[1])
|
1int[] anArray = {10, 11, 12, 13};
2
3// Access the array at index 1
4System.out.println(anArray[1]);
5
6// Modify the array at index 1
7anArray[1] = 21;
8System.out.println(anArray[1]);
|
With the exception of the type and syntax, these look the same
We have to specify the type for Java
int[]
Note that
int
is an int andint[]
is an array of ints
Squiggly braces (
{ ... }
) are used instead of brackets ([ ... ]
)
One difference is that Java arrays can’t contain mixed types like a Python list
There is an asterisk added to this statement that will be discussed later
One major difference is that the Java array used in the above example will always be size 4
One cannot simply list append to an array like with lists in Python
a_list.append(34)
In Java, arrays have fixed sizes
This means that one cannot start with an empty array and have it grow and grow
Python |
Java |
---|---|
1# List will start with 0
2a_list = []
3
4# List will grow to size 1,000
5for i in range(1000):
6 a_list.append(i)
|
1// Create a new array of size 1,000
2int[] anArray = new int[1000];
3
4// Put a number in each index in the array
5for(int i = 0; i < anArray.length; i++){
6 anArray[i] = i;
7}
|
Mind line 2, showing how to make an empty array of a specific size
They will be filled with some default value (0 in this case)
Mind line 5, showing:
A
for
loop (more on this later)Arrays have an attribute
length
that returns the array’s capacity
Mind line 6 indexing the array in order to assign it a value
One could make the size of the array based on some runtime determined value — for example:
Reading data from a file to be stored in an array — how big should the array be?
Perhaps the first line of the file contains how long the file is
String[] fileContents = new String[someValueReadIn]
Warning
In Java, it is not possible to index arrays backwards with negative values like in Python.
2.3. Input & Output
Several of the above examples included the use of Java’s standard output
System.out.print("print");
System.out.println("print a line");
Standard input with Java is more verbose than Python’s
This is because Java is not designed for console applications
Fortunately, the only place this is used in this course is for the Kattis problems
Python |
Java |
---|---|
1the_input = input()
2print(the_input)
|
1// Outside class definition
2import java.io.BufferedReader;
3import java.io.InputStreamReader;
4import java.io.IOException;
5
6...
7
8// Create a Stream Reader with the standard input
9InputStreamReader stream = new InputStreamReader(System.in);
10
11// Give the Stream Reader to a Buffered Reader
12BufferedReader reader = new BufferedReader(stream);
13
14// We use the Buffered Reader to read the actual stream
15// We use a try & catch because readLine may throw an
16// exception that we must deal with
17try {
18 String theLine = reader.readLine();
19 System.out.println(theLine);
20} catch (IOException e){
21 System.out.println("Something bad happened.");
22}
|
Mind the
import
statements for JavaIn Java, one reads from a stream
Here the stream is the standard input (
System.in
)
An
InputStreamReader
object is createdThe thing that reads the input from the stream
With this, it only reads one thing at a time
A
BufferedReader
is used to buffer the stream readerTo make it easier to read in more than one at a time
Also note the use of
try
andcatch
around thereader.readLine()
This is done because
readLine()
has an exception that may be thrown that you must deal withAlthough discussed last semester, exceptions will be covered in more detail later in the course
Like Python’s
input()
,readLine()
returns aString
Alternatively, one could modify the above code to, arguably, clean it up
1import java.io.BufferedReader;
2import java.io.InputStreamReader;
3import java.io.IOException;
4
5public class SomeClass {
6 public static void main(String[] args) throws IOException {
7
8 // Create a Stream Reader with the standard input
9 InputStreamReader stream = new InputStreamReader(System.in);
10
11 // Give the Stream Reader to a Buffered Reader
12 BufferedReader reader = new BufferedReader(stream);
13
14 // We use the Buffered Reader to read the actual stream
15 String theLine = reader.readLine();
16 System.out.println(theLine);
17 }
18}
This just passes the buck of dealing with the exception to the caller of the function/method
In this example, it’s the
main
method, so this will throw the exception at the person who ran the programThis would cause the program to crash
2.4. Functions/Methods
Python |
Java |
---|---|
1# Declaring a function
2def some_function(a, b):
3 c = a + b
4 return c
5
6# Call the function
7result = some_function(1, 2)
8print(result)
|
1public class SomeClass {
2 public static void main(String[] args) {
3 // Call the function
4 int result = someFunction(1, 2);
5 System.out.println(result);
6 }
7
8 // Declare the Function
9 static int someFunction(int a, int b) {
10 int c = a + b;
11 return c;
12 }
13}
|
In Java, functions/methods must be explicitly told what their return type is
int
in this example, because the value being returned is anint
In the case where the method returns no value, the return type is set to
void
static void someOtherMethod( ... ) {
Parameters have their types included
int a
andint b
in the parameter list
In the above example, the function is
static
, which means it is a function and not a methodThis is a function that belongs to the class, not an instance of the class
If the function is not written with
static
, it is then an instance methodIn other words, it’s not a method we will call on an instance of some object
As seen in the above example, the function is defined after it is called
The function
someFunction
is called withinmain
, but it is written belowmain
This is not required in Java, but is something one could do
In Python, the interpreter needed to know the function existed before it could be referenced
2.4.1. Instance Methods
For instance methods in Java, there is no need to include
self
in the parameter listAlthough, Java has a similar keyword —
this
Python |
Java |
---|---|
1def some_method(self, add_me):
2 self.some_instance_variable += add_me
|
1public void someMethod(int addMe) {
2 someInstanceVariable += addMe;
3}
|
2.4.2. Visibility Modifiers
In Python, there is a convention of adding an underscore (
_
) to the beginning of an attribute or method nameThis is done to indicate that the attribute or method is not to be accessed directly from outside the class
In Java, the keywords
public
andprivate
are used instead to specify attribute and method visibilityFurther, Java will produce a compiler error if one tries to access something declared to be private
Python |
Java |
---|---|
1def you_can_touch_me(self):
2 # ...
3
4def _do_not_touch_me(self):
5 # ...
|
1public void youCanTouchMe() {
2 // ...
3}
4
5private void doNotTouchMe() {
6 // ...
7}
|
2.4.3. Temperature Converter
Python |
Java |
---|---|
1def fahrenheit_to_celsius(fahrenheit):
2 celsius = (fahrenheit - 32) * 5/9
3 return celsius
|
1static double fahrenheitToCelsius(double fahrenheit) {
2 double celsius = (fahrenheit - 32) * 5.0/9.0;
3 return celsius;
4}
|
Pay special attention to the division taking place on like 2
If one wrote
5/9
, since both5
and9
are integers, it will do integer divisionSince integers do not have decimal values, it truncates the decimal off —
5/9 = 0
In reality, although it is 0.55555555555, everything after the decimal point is truncated
This integer division functionality is more typical
In fact, Python used to work this way too, and they made people mad when they changed
If one truly wants floating point division, then be sure to divide floating point values
2.6. Booleans
Java has Boolean values, except they start with lower case letters
Python —
some_boolean = True
Java —
boolean someBoolean = true;
2.6.1. Conditionals
Python |
Java |
---|---|
1if some_boolean:
2 print("it was true")
3else:
4 print("it was false")
|
1if (someBoolean) {
2 System.out.println("it was true");
3} else {
4 System.out.println("it was false");
5}
|
Both examples above assume the variable
someBoolean
exists and is a booleanNotice how, unlike Python, the condition is in parentheses in the Java example
( ... )
2.6.2. Boolean Operators
Just like Python, Java has comparison operators that return booleans
less than —
a < b
sameness —
c == d
not sameness —
e != f
Logical operators also exist, but their syntax is a little different
and —
v and w
vsv && w
or —
x or y
vsx || y
not —
not z
vs!z
2.7. Loops
Just as one would expect, Java has loops too
2.7.1. While Loops
Python |
Java |
---|---|
1c = 0
2
3# While some condition is true
4while c < 10:
5 print("c is now: " + str(c))
6 c+=1
|
1int c = 0;
2
3// While some condition is true
4while (c < 10) {
5 System.out.println("c is now: " + c);
6 c++;
7}
|
Just like the
if
statements, the condition is in parenthesesNote the
c++
— this is the same thing asc+=1
, but even shorterOne could still use
c+=1
in Java though
Python |
Java |
---|---|
1stop = False
2c = 0
3
4while not stop:
5 print("c is now: " + str(c))
6 c+=1
7 if c == 5:
8 stop = True
|
1boolean stop = false;
2int c = 0;
3
4while (!stop) {
5 System.out.println("c is now: " + c);
6 c++;
7 if (c == 5) {
8 stop = true;
9 }
10}
|
2.7.2. For Each Loop
For loops in Python are effectively for each loops
Python |
Java |
---|---|
1a_list = ['a', 'b', 'c', 'd']
2
3# For each thing 'c' in aList
4for c in a_list:
5 print(c)
|
1char[] anArray = {'a', 'b', 'c', 'd'};
2
3// For each character 'c' in anArray
4for (char c : anArray) {
5 System.out.println(c);
6}
|
It’s very similar, except
The type of
c
is specifiedA colon (
:
) is used instead ofin
2.7.3. For Loop
Looping a specific number of times
Python |
Java |
---|---|
1# Run loop 10 times (0 -- 9)
2for i in range(10):
3 print(i)
|
1// Run loop 10 times (0 -- 9)
2for (int i = 0; i < 10; i++) {
3 System.out.println(i);
4}
|
In Java, the first statement within the parentheses is run once before anything loops
int i = 0
Create an integer
i
and assign it to0
The second statement in the parentheses is the condition checked every time the loop runs
i < 10
Check if
i
is less than10
This could be a more general conditionals if needed
The third statement in the parentheses runs after each time the code block in the loop finishes
i++
After the body of the loop finishes a single iteration, add
1
toi
Overall, this says:
Create an
int i
and set it to0
If
i
is less than10
, run the loopAdd
1
toi
every time the loop runs
In other words, this loop will run 10 times
0
–9
2.7.3.1. Comparison of For Loop to While Loop
It may be useful to show the comparison of a for loop to a while loop in Java
1// For loop
2for (initializer; condition; step) {
3 loop stuff;
4}
5
6// The same functionality as a while loop
7// although, scope does come into play
8initializer;
9while (condition) {
10 loop stuff;
11 step;
12}
In the above example, both loops are doing the same thing and have the same functionality
The only functional difference is scope
In the for loop example, the initialized stuff only exists within the loop
The
i
inint = i
cannot be accessed outside the loopThe initialized stuff in the while loop example will exist outside the loop
2.8. Java Conventions
The following is not exhaustive, but here are some important Java conventions to follow
Have one public class per file
Not a convention; this is required
Class names start with capital letters
SomeClass
File names are the same as the class
SomeClass.java
Not a convention; this is required
Functions/methods should be camel case, starting with a lower case
someFunction( ... )
someOtherFunction( ... )
Variables should be camelcase, starting with a lower case
int someVariable = 5;
int someOtherVariable = 55;
Constants are all uppercase with underscores separating words (snake case)
static final int THIS_IS_A_CONSTANT = 555;
2.9. For Next Time
Note
If at any point you are thinking “Uh oh, how on earth am I going to remember all these differences?”, you’re doing programming wrong.
Practice
Use Kattis and solve problems you have already solved in Python, but use Java
Read Chapter 1 of your text
15 pages
2.5. Comments
In the above Java example you will see