1 - Python To Java
1 - Python To Java
You have all the resources that you need to solve I reviewed slides 17-18 in the lecture, and I
the problems that have been given to you, but finished the practice activity. That all works fine.
sometimes you may not be able to find the
answers to the problems that you encounter. But when I try to use the values entered by the
user, I am getting an "input mismatch" error.
Does anyone have a suggestion?
Asking for help in this course is both expected and
encouraged.
Spending time trying to solve the problem yourself 1. Begin by reviewing the lecture slides
will be a more valuable learning experience in the related to the problem that you are
long run. trying to solve
2. Try to solve the related class activities
If you do ask for help, try to be as detailed as without looking at the answer
possible to make it easier for others to help you by 3. When asking for help, try to be as
specific as possible about the problem
providing as much detail as you can.
you are having
2
● In GCIS-123 we wrote software exclusively in
Python to Java the Python programming language.
○ For most of the course we used procedural
This unit will mostly focus on showing how to use Java programming, which is a term for programs
to do things that you already know how to do in Python. that use functions to implement most of the
This mostly involves learning Java syntax. program requirements.
○ Towards the end of the course, we introduced
object-oriented programming.
● In GCIS-124 we will be using the Java
Programming Language, a fully object-
oriented language.
○ Unlike Python, in Java all code must be inside of
a class.
● During this unit we will focus on learning how
to use Java to implement many of the
programs that you already know how to write
in Python.
○ Types & Variables
○ Methods, Parameters, Arguments & Return
As we move further into the semester, we will more Values
deeply explore object-oriented programming, and ○ Boolean Expressions, Conditionals & Loops
advanced topics such as threading and networking. ○ Unit Testing with JUnit
○ Exceptions & File I/O 3
Why Another
● Python is an incredibly powerful and flexible
language. Language?
I see that you know two languages. I'm
○ It is also one of the most popular languages sorry, but we only hire people who are
used today according to GitHub and irrationally attached to one language and
Stack Overflow. unwilling to learn anything new.
newlines. 4 }
○ 5 }
Statements are terminated by a semi-colon
(;) and may be written on multiple lines.
○ Curly braces ({}) are used to indicate a block A Java class is only executable if it includes
a main method with a very specific signature.
of statements, e.g. the body of a method or a
class.
● In Java, the static keyword marks a method The System.out.println() method is used to print to
standard output.
or field as belonging to the class. 8
○ The method or field can be accessed through
A Closer Look (or "Why we don't use Java in
123.")
In Java, using the public access modifier makes things A Java class is declared using the class keyword, just
(classes, methods, fields) accessible from anywhere like in Python. The name of the class must exactly match
outside of the class. In this unit we will make all classes the name of the file (including case), e.g. the Example
and methods public. class must be in a file named Example.java.
In Java, System.out refers to standard output. The Java strings must be enclosed in double-quotes ("").
print and println methods can be used to print You do not have the option of using single-quotes or triple-
virtually any type including strings, integers, and so on. quotes of any kind.
9
1.2 Hello, World!
"Hello, World!" is often the first program written when learning the syntax of a new
programming language. Let's start learning Java syntax by implementing it now.
● Create a new Java class in a file named
Hello, "HelloWorld.java" in the root folder of your project.
again. ○ Define a main method with the appropriate signature and
print "Hello, World!" to standard output.
● Open the terminal in VSCode (CTRL-`) and use the
Java Compiler to compile your new class.
1 public class Example { ○ e.g. javac HelloWorld.java
2 public static void main(String[] ○ If there are any syntax errors, correct them in the editor
args) { and try to compile your class again.
3 System.out.println("testing"); ○ List the files in the directory to verify that your .class
4 }
file has been created.
5 }
damian@batcomputer ~/SoftDevII/unit01 ● Once you have successfully compiled the class, run it
$ javac Example.java
damian@batcomputer ~/SoftDevII/unit01 using java.
$ java Example ○ e.g. java HelloWorld
testing ○ Do not include the .class extension. 10
● Java is a statically typed language, meaning
that the type of a variable must be specified
Variables & Assignment
when it is declared. Type Description Example
○ Once declared, only compatible values may be
assigned to the variable. byte 8-bit signed integer, -128 to 127. 123
● Unlike Python, a Java variable may be declared
short 16-bit signed integer. 12345
without immediately assigning a value.
○ e.g. int radius;
int 32-bit signed integer. 1234567
○ Variables may also be declared and initialized
at the same time, e.g. double pi = 3.14159; 64-bit signed integer.
long 1234567l
● Like Python, Java includes two basic kinds of
types. char 16-bit unsigned integer (Unicode). 'a'
○ Primitive types include integers, floating
float 32-bit signed floating point value. 3.14159f
point values, characters, and booleans.
■ Primitive types are very similar to
double 64-bit signed floating point value. -0.1234
Python's value types.
■ Java includes a character type, a single
boolea Boolean value; true or false. true
character enclosed in single-quotes,
n
e.g. char c = 'c';
○ Reference types are, well, everything else Java assumes that literal numbers are int or
including strings, arrays, and other objects. double, and so a suffix of l (lowercase L) is needed
■ Reference types work the same in Java as for a long literal (e.g. 3098765341l), and f for a
they do in Python. float literal (e.g. 1.3f).
11
Variables in Java
12
Variables in Java
Because Java is a statically typed language, variables Like any other statement in Java, a variable
must be declared with a valid type. Only values of a declaration must be terminated with a semicolon.
compatible type may be assigned to the variable.
1 public static void variables() {
2 double weight = 65.5;
3
4 be
Unlike Python a variable may int age;
declared without immediately
5 assigning
a value…
6 age = 10;
7
…but a value must be assigned
8 before System.out.println("weight = " +
the variable can be used. weight
9 + ", age = " + age);
10 } Unlike Python, the + operator can be used to
concatenate any type onto a string (not just other
strings).
13
1.6 Primitive Types
Primitive types in Java include integers (byte, short, int, long), floating point values
(float, double), characters (char), and boolean values. Practice declaring a few
variables using different primitive types and printing them to standard output.
20
● All Java methods must declare a return
type, even if no value is returned.
○ The return type is declared as part of the
method signature.
Return Values
● Unlike Python, there is no default return A method that declares a void return type does not
type in Java. The void return type indicates return a value of any type, though a return
that a method does not return a value of statement can be used without a value.
any type.
○ A void method cannot be assigned to a 1 public static void someVoidMethod() {
variable, and trying to do so will cause a 2 System.out.println("no return");
3 return;
compiler error, e.g. int x =
4 }
someVoidMethod(); 5
○ A void method cannot return a value, 6 public int intReturn() {
though it may use an empty return 7 return 5;
statement, e.g. return; 8 }
● If a method declares a return type of
anything other than void, then a value of A method that declares a return type of any other
that type must be returned by the method type must return a value of a compatible type. If
not, the method will not compile.
using a return statement, e.g. return 5;
○ This also means that, if there are multiple
branching paths through the method, each Assigning a method with a void return type to a
and every branch must terminate in a variable of any type will cause a compiler error.
return statement.
○ A method that does not return a value of the
21
declared type will not compile.
1.11 Calculon
In Python, all methods return a value (even if that value is None). In Java, a method
must declare its return type - if the return type is not void, the method must return a
value of the correct type or the program will not compile. Try writing a few methods
that return values.
● Create a new Java class in the "unit01" folder in a
file called "Calculon.java".
● Define a method for each of the four basic
arithmetic operations, each of which declares two
floating point parameters and returns a
floating point result.
○ add
○ subtract
○ multiply
○ divide
public int intReturn() ● Test your methods by calling them from main and
{ printing the results to standard output.
return 5; ● Run the class.
} 22
Conditionals ● Recall that a boolean expression is one
that, when evaluated, results in a boolean
Python Java Example value, i.e. true or false.
● Just like Python, logical and comparison
not ! !a, !(a || b) operators can be combined to create
complex boolean expressions in Java.
or || a || b
● Also like Python, Java supports conditional
and && a && b statements that work very much the same.
○ if(expression) {...} - executes the
^ ^ a ^ b statements in the body if the expression is
true.
is, is not ==, != a == b, a != b ○ else {...} - executes the statements in the
body if all of the preceding conditions are
== == x == 5 false.
(primitives) a.equals(b)
equals(Object ● The most notable difference is that Java does
) not include an elif statement.
1○ if(a && b)
Instead, { if(expression) {...} is used.
else
<, <= <, <= a < b, a <= b 2 System.out.println("foo");
3 } else if(b ^ c) {
4 System.out.println("bar");
>, >= >, >= a > b, a >= b
5 } else {
A side-by-side comparison of logical and comparison
6 System.out.println("foobar");
operators in Python and the equivalent operators in 7 }
Java.
23
1.12 Conditioning
By now you have lots of experience using conditionals
in Python. Conditionals in Java work exactly the same
way, but use a different syntax. Practice the Java
syntax by writing a method that prints a different
message depending on whether or not a number is
divisible by a2,new
● Create 3, Java
or 5.class in a file named
"Conditional.java" and define a method named
"evenlyDivisible" that declares a parameter for an
integer n.
○ Print exactly one of the following messages depending on
the value of n:
if(a && b) { ■ The number is even
System.out.println("foo"); ■ The number is divisible by 3
} else if(b ^ c) { ■ The number is divisible by 5
System.out.println("bar");
} else { ■ The number is odd but not divisible by 3 or 5
System.out.println("foobar"); ● Call your method from main with several values of n.
}
● Run the class.
24
while Loops
A while loop will execute zero or more iterations
● Java while loops work exactly the same depending on whether the boolean expression is true
way as while loops in Python with a few the very first time it is evaluated.
small syntactic differences.
○ The boolean expression that controls the loop 1 int i = 1048576;
must be enclosed in parentheses (()). 2 while(i != 2) {
○ If the body of the loop contains more than 3 System.out.println(i);
one statement, it must be enclosed in curly 4 i = i / 2;
braces ({}).
5 }
● Java also supports statements for more
finely grained control of a while loop.
○ The break statement will terminate a loop The loop will continue iterating until the boolean
immediately, regardless of the boolean expression evaluates to false.
expression.
○ The continue statement will stop the The break and continue statements work the same
current iteration. The boolean expression as they do in Python and can be used for more finely
will be evaluated to determine whether or grained control of the iteration. 25
not the next iteration should be executed.
1.13 Counting Up with while
The while loop in Java works just like Python's while loop, but uses a different syntax
(you may be sensing a theme here). Practice Java's while loop syntax by
implementing a method that uses a while loop to print a count up from 0 to n.
The initialization of the counting The boolean expression that stops The initialization of the counting The boolean expression that
variable, which happens before the loop. This is evaluated before variable, which happens before stops the loop. This is
the first iteration. each iteration. the first iteration. evaluated before each
iteration.
int count = 0;
while(count < 11) { for(int c=0; c<11; c++) {
System.out.println(count); System.out.println(c);
count++; }
} The statement that modifies the
counting variable. This is executed
at the end of an iteration.
The statement that modifies the
counting variable. This is usually
executed at the end of an iteration. 28
1.14 Counting up with for
Python does not have a loop like Java's "classic" or "C-Style" for loop. However, it
works just like a counting while loop with a more compact syntax. Practice the
syntax now by implementing a second method that counts from 0 to n using a for
loop.
Java's for loop is a syntactic shortcut for
a counting while loop. ● Open your CountUp class and define a
method called "countFor" that declares a
The counting variable is initialized in the parameter for an integer n.
loop header. The boolean expression is
evaluated before each iteration. ○ Use a for loop to print a count from 0 to n.
○ Return the sum of the numbers that are
for(int i=1024; i != 2; counted.
i=i/2) { ● Call your method from main and print the
System.out.println(i); sum.
} ● Run the class.
The modification statement is executed
after each iteration. 29
● Java is a fully object oriented language, and
so all code must be inside the body of a
Review: Java Basics
class.
○ The public access modifier indicates that the All code in Java must be within the body of a class. The
class, method, or field is visible to the entire public access modifier indicates global visibility.
program.
○ The static modifier means that the class, Curly braces ({}) enclose blocks of code.
method, or field is accessed through the class Whitespace is only used for readability.
and not an object.
● Whitespace in Java is insignificant. 1 public class MyClass {
○ Blocks of code are enclosed in curly braces 2 public static void main(String[] args) {
({}).
3 int x;
○ Statements are terminated with a semicolon
(;). 4 double pi = 3.14159;
● Primitive types in Java include integers 5 System.out.println("Hello, GCIS-
(byte, short, int, long), floating point values 124!");
(float, double), characters (char) and 6 }
Booleans (boolean). 7 }
● All other types in Java are reference types.
Being a statically typed language, Java variable
● Java variables must be declared with a type declarations must include the type. Only values of
and a valid identifier. The variable may or compatible types can be assigned.
may not be initialized with a value when it is
declared, e.g. In order to be executable, a Java class must include a
○ int x; main method with a very specific signature.
○ double pi = 3.14159;
30
● The System.out is a reference to standard
Review: Java Conditionals and Loops
Boolean expressions in Java combine logical Java's "classic" for loops use a C-like syntax and
operators (and (&&), or (||), not (!), and xor (^)) and are a more syntactically compact version of a counting
comparison operators (==, !=, <, <=, >, >=) and while loop.
evaluate to true or false.
import org.junit.jupiter.api.Test;
42
1.21 Writing Your First JUnit Test
Now that we have verified that we can run JUnit tests and have moved all of our code
into the right location in the project, let's write our own unit test. Tests in Java should
be set up the same as they are in Python (setup, invoke, analyze) and should be
small, fast, and repeatable.
● Create a new JUnit test named "CalculonTest" in the same folder
as "HelloWorldTest" and define a test method named "testAdd".
○ Make sure to add the @Test annotation to the method!
○ Call the static add method on your Calculon class and save the result
@Test
public void exampleTest() in a new variable, e.g. float actual = Calculon.add(5.1f, 7.2f);
{ ○ Use the JUnit assertEquals method to assert that the actual value
// setup matches the expected value.
int x = 5; ■ Hint: only type the first few characters of the name, e.g.
int y = 2;
"assertE", and then use VSCode's autocomplete feature to
int expected = 7;
import the assertEquals method from JUnit.
// invoke ● Click the flask icon in your VSCode sidebar to open the Java Test
int actual = x + 1;
Runner.
// analyze ○ Click the run all tests button at the top of the test runner.
assertEquals(expected, ○ You will see that VSCode runs each test method in each of your tests,
actual); usually from top to bottom.
} 43
○ If a test passes, it is marked with ✔ and if it fails, it is marked with 𝗫.
Test Output in VSCode
Filter to see all tests, only
failed tests, or only tests that
passed.
If a failing test is clicked in the
tree on the left, the editor will
When expanded, the tree on jump to that test…
the left shows tests that
passed with a ✔ and tests
that failed with an X.
…and show a detailed (if clunky)
dialog explaining which assertion
failed, and why.
44
○ Statements are terminated with a semicolon.
54
● The java.io.File class represents a file
or directory in the computer's file
system.
○ Importing the class will allow your Java Files
program to use it without specifying the
full class name. An instance of the java.io.File class can be
● A file object is created by calling the created with an absolute or relative path to a file in
File class constructor with the path to the the file system.
file.
○ An absolute path may be used.
A relative path is relative to the directory in which
○ A relative path may also be used; such
paths are relative to the directory from
the program was executed. For example,
which the program is executed. "data/file.txt" refers to a file named
○ e.g. File f = new File("a_file.txt"); "file.txt" in the "data" subdirectory.
● An instance of the File class cannot be
used to read from or write to the specified
1 File file = new File("a_file.txt");
file, but does provide many methods that
can be used to get information about the 2 String path =
file. file.getAbsolutePath();
○ exists() - returns true if a file with the 3 long size = file.length();
specified path exists in the file system, and
false otherwise. 4 boolean dir = file.isDirectory();
○ isDirectory() - returns true if the file is a Once created, a file object can be used to get
directory, and false otherwise. information about the file including its absolute
○ getAbsolutePath() - returns the absolute path, length, and whether or not it is a directory.
path to the file as a String.
○ length() - returns the number of bytes of
55 data in the file as a long.
1.30 Getting File Info
In Java, File objects can be used to get lots of different information about files and
directories. Try it out now by implementing a method that uses a File object to print
detailed information about any file.
A File object is created with string specifying a ● Create a new Java class named "Files" and
filename or a path to a file.
define a method named "info" that declares a
parameter for a filename.
File file = new ○ Create a File using the filename and print the
following:
File("some_file.txt");
■ The name of the file.
String name = file.getName(); ■ The absolute path to the file.
boolean exists = file.exists(); ■ Whether or not the file exists.
Once you have created a file object, you can call ■ If the file exists, print its length in bytes.
methods on it to get information about the file.
● Call your function from main with several
different filenames.
Try using VSCode's autocomplete feature to see ○ Hint: use the names of files in your repository.
which methods are available.
● Run the class.
56
● A java.io.FileReader can be used to read Reading Text Files
character data (text) from a file.
○ A FileReader can be created by passing an
A java.io.FileReader can be used to read
absolute or relative path into its
characters (one at a time or in chunks) from the file
constructor.
with the specified path.
○ e.g. new FileReader("a_file.txt")
● Once created, a FileReader provides several
1 FileReader fileReader =
methods for reading text.
○ 2 new FileReader("a_file.txt");
read() - returns the next character of data.
○ read(char[] buffer) - reads up to 3 BufferedReader reader =
buffer.length characters into the given 4 new BufferedReader(fileReader);
buffer. 5 String line = reader.readLine();
● A FileReader is a little hard to use because 6 reader.close();
7 fileReader.close();
it only supports reading characters (one at a
time or in chunks). A
java.io.BufferedReader can be A java.io.BufferedReader can be created with
a FileReader. Its readLine() method can be
constructed with a FileReader and provides
used to read one line of text at a time.
a readLine() method that reads up to the
next newline from the file and returns it as a Opened files should always be closed when no
String. longer needed to avoid locking the file (and
○ e.g. String s = reader.readLine(); preventing other processes from using it).
57 ○ The method returns null when the end of
the file has been reached.
1.31 Reading Text Files
Unfortunately, reading text files in Java is a lot more complicated than it is in Python.
There is a lot more setup and you can't just iterate through the lines in the file
exactly. Let's practice a little now.
● Open your Files class and define a method named
"printFile" that declares a parameter for a filename.
○ Create a FileReader using the filename.
○ Create a BufferedReader using the FileReader.
○ Use a loop to print the lines in the file one at a time.
■ Use the readLine() method on the BufferedReader.
■ If readLine() returns null, you have reached the end of
the file.
FileReader fileReader = ■ Don't forget to close the FileReader and
BufferedReader when you are done!
new FileReader("a_file.txt");
BufferedReader reader =
● Call your method from main using one of the provided files
new BufferedReader(fileReader); in the data directory in your repository.
○ e.g. "data/alice.txt"
String line = reader.readLine();
reader.close();
● What do you notice in VSCode?
fileReader.close();
● What happens when you try to run your code? 58
unchecked exceptions like
InputMismatchException.
60
● The java.io.FileWriter class provides
methods for writing character data to a file.
○
○
write(char c) - writes a single character.
write(char[] buffer) - writes an entire array
Writing Text Files
of characters all at once. A FileWriter can be created with a filename to
○ flush() - forces any data that has been write character data out to the file, but a
buffered in memory to be written to the file. If FileWriter can be a little clunky to use.
you do not flush before closing the file, your
data may not be written!
A PrintWriter can be created with a FileWriter.
● A FileWriter is a little hard to use because it
only supports writing characters. The
1 FileWriter fw = new
java.io.PrintWriter class can be
FileWriter("a_file.txt");
constructed with a FileWriter and provides 2 PrintWriter writer = new PrintWriter(fw);
methods that are easier to use. Anything 3 writer.print("Your age is: ");
printed to the PrintWriter is written out to 4 writer.print(18);
the FileWriter. 5 writer.println(" years old.");
○ print(String s) - writes the string to the 6 writer.flush();
FileWriter. 7 writer.close();
○ println(String s) - writes the string followed A PrintWriter provides many convenience
by a newline. methods for printing data. Anything printed using the
○ print(int i) - prints the integer as a string, PrintWriter is written to the FileWriter as
e.g. "123". There is a similar methods for each character data.
primitive type.
○ flush() - flushes any buffered data out to the Data should be flushed and the PrintWriter
61 file. Again, data that is not flushed may not be should be closed.
written!
1.33 Writing Text Files
Using Java to write to text files is just as complicated as reading files. It will take lots
of practice for you to get used to it. Using the code examples below and the code you
wrote for previous activities in this unit, write a command-line text editing tool that
saves text that the user types to a file.
U nit
● it
JUn ys
A rra O
/
●
F ile I tions
● p
E xce
● Please answer the questions above in your notes for
today. 65