Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
28 views

1 - Python To Java

hi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

1 - Python To Java

hi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

GCIS-124

Software Development & Problem Solving


1: Python to Java
Asking for Help
Could be MUCH
Improved Better
I don't understand
part 4.c. on the Part 4.c. on homework 2.2 asks us to write a
homework. function that prompts the user to enter two
floating point values and to print the product.

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.

● It is also a great learning language for


inexperienced programmers because, while
it is very powerful, it is also relatively quick
and easy to pick up the basics.
○ "Hello, World!" is just print("Hello,
World!")
● However, while Python supports classes and
objects, it is not a great object-oriented
language.
○ OO concepts like encapsulation, inheritance,
overriding, and overloading are all very oddly
implemented in Python when compared to Said no one, ever.
other languages.
● There are also significant benefits to It's great to have a favorite language that is your
learning a new programming language. "go to" for personal projects, but be careful not to
○ Not only is it great for your resume, but the get stuck in a professional rut.
4
more languages that you learn, the more
Java ● Java is a fully object-oriented programming
Python is implicitly compiled and executed in a
language.
○ This means that all code must be inside the
single step. Both syntax and runtime errors are
reported at the same time. body of a class.
● Python is an interpreted language, meaning
Python Java source that code written in a Python program is
source code code interpreted at the time of execution.
○ This means that any syntax or runtime errors
Syntax Errors
are reported at the same time.
Reported
● Java, on the other hand, is a compiled
Java
bytecode language.
○ Java programs are text files saved with a .java
Runtime
Errors extension, e.g. HelloWorld.java.
Reported ○ Each must be explicitly compiled into
bytecode using javac before it can be
computer computer
executed.
○ Any syntax errors are reported at this time.
Java is explicitly compiled into bytecode first, at ○ The bytecode is saved in a .class file with the
which time syntax errors are reported. same name, e.g. HelloWorld.class.
● Once a Java program is compiled, it can be
Once compiled, a Java program is executed as a executed using java.
separate step, at which time runtime errors are ○ The program must include a main method
reported. 5
with a specific signature to be executed.
● High-level languages like Python and Java Java Bytecode
are meant for humans to understand.
○ A higher-level language has syntax that is
closer to written or spoken language. Java Source Java Compiler
○ Python is a (slightly) higher-level language (.java) (javac)
than Java.
○ On the other hand, assembly is a very low-
level language.
● Machine code is very low-level code that
can be executed directly on a computer.
○ Different computers understand different Java Bytecode
dialects of machine code. (.class)
● Bytecode is somewhere in the middle.
○ Lower-level than Python or Java source code.
○ Higher-level than machine code.
● Bytecode is much faster/easier to interpret Mac PC
(translate) into machine instructions than
Mac JVM Windows JVM
source code is. (java) (java.exe)
● A virtual machine (VM) interprets bytecode
into machine code at runtime.
○ In this way, bytecode is like machine code for
the virtual machine. macOS Windows
○ The compiled bytecode never needs to Specific Specific
Instructions Instructions
change, but a different VM is needed for each
operating system and/or processor to
6
translate it properly.
1.1 Verify Your Java Version
Before we can do anything else, you will need to make sure that the correct version of
Java has been installed on your computer. Take a moment to verify that both Java and
the Java Compiler have been installed and configured correctly.

● Open the terminal in VSCode (CTRL-`) and run javac -


version to verify the version of the Java Compiler that you
have installed.
○ This is the executable that you will use to compile your Java
programs.
● Next, run the java -version command to display the version
of the Java Development Kit (JDK) that you have installed.
○ This is the executable that you will use to run your Java programs.
● Both executables
dick@batcomputer should have the same version
MINGW64 ~/SoftDevII/unit01-nightw (main) number.
$ javac -version
javac 19.0.1
dick@batcomputer MINGW64 ~/SoftDevII/unit01-nightw (main)
$ java -version
java version "19.0.1" 2020-10-20
Java(TM) SE Runtime Environment (build 15.0.1+9-18)
Java HotSpot(TM) 64-Bit Server VM (build 15.0.1+9-18, mixed mode, sharing)
7
Scaffolding
● Unlike Python, Java requires quite a bit of All Java code must be inside the body of a class, meaning
that every program starts with a class declaration. The
scaffolding to write even the most basic class name must match the filename, e.g. Example.java
programs.
○ Part of the reason for this is that all code in Curly braces ({}) are used to indicate scope.
Java must be in the body of a class, and so at Whitespace is not significant.
a minimum a class must be declared.
● Java has a C-like syntax meaning: 1 public class Example {
○ Whitespace is not significant beyond 2 public static void main(String[] args) {

improving readability for humans. This includes 3 System.out.println("testing");

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.

1 public class Example {


2 public static void main(String[]
Whitespace is insignificant in
The static keyword indicates args) { Java. Instead, curly braces
that the method belongs to the
3 System.out.println("testing"); ({}) define blocks of code.
class and can be called without
Indents are used for readability
creating an object. 4 } only.
5 }

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

1 public static void variables() {


2 double weight = 65.5;
3
4 int age;
5
6 age = 10;
7
8 System.out.println("weight = " +
weight
9 + ", age = " + age);
10 }

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.

● Create a new Java class in a file named


"Primitives.java" in the "src/main/java/unit01"
folder.
● Define a main method with the appropriate
signature.
○ Declare variables of at least four different primitive
types and print the name, type, and value to
public static void variables() {
String name = "Buttercup";
standard output.
int age; ○ e.g. int x = 5;
age = 10; ○ Hint: unlike Python, you can concatenate a value of
System.out.println("name = " + name
any Java type onto a string using the + operator, e.g.
+ ", age = " + age);
}
System.out.println("four = " + 4);
14
● Use the "play" button in VSCode to run your class.
● Java supports most of the same basic
arithmetic operators that Python does with
Arithmetic Operators
a couple of notable exceptions.
○ There is no power (**) operator in Java, but the Operator Description Example
Math.pow() method may be used instead, e.g.
Math.pow(2, 7) will return 27 = 128. + Addition double x = 5.1 + 3;
○ There is no integer division operator (//) in Java,
but using standard division with two integer - Subtraction double z = 5.1 - 3;
values has the same result.
* Multiplication int x = 3 * 4;
● The other basic operators all work the same
with some possible caveats. / Division double x = 5.1 / 3;
● Applying an operator to two values of the
same type will produce a value of that / (integers) Integer Division int x = 5 / 2;

type. Math.pow(x, double z;


Power: XY
○ For example, 10 / 3 will perform integer y) z = Math.pow(x, y);
division. In this case, the expression would
evaluate to an int (3). % Modulo m = 10 % 3

● If values of different types are mixed in the


same expression, the result is "promoted" to The + operator also works for string concatenation,
the most complex type. just as it does in Python. A notable difference is that
○ For example 2.5 * 3 would evaluate to a double any type can be concatenated onto a string without
(7.5). using a function like str(), so "abc" + 123 is valid.
15
1.8 Arithmetic
Arithmetic operators in Java work very similarly to those in Python, including the
order of operations and the way that they behave when combining integer and
floating point values. Practice using the Java operators now.
● Create a new Java class in the
"src/main/java/unit01" folder in a file called
"Arithmetic.java" and define a main method with the
appropriate signature.
○ Use System.out.println to print the results of using
arithmetic operators with combinations of different types,
e.g.:
■ int and int
■ int and double
■ double and double
○ For example: System.out.println("12 * 3.6 = " + (12
* 3.6));
○ There is no need to declare variables, but remember that
Java will consider a literal integer to be an int (32-bit)
and a literal floating point value to be a double (64-bit).
16
● Use the VSCode run button to run the class.
Strings & ● Java strings have a lot in common with
Python strings.
Characters
String is the type used for Java strings. String


They comprise characters.
Literal strings are enclosed in double-
quotes ("").
literals must be enclosed in double-quotes (""). ○ Strings are immutable.
○ The + operator can be used to create a new
string by concatenating two strings
1 String aString = "Jason"; together.
2 char first = ○ Strings are reference types.
aString.charAt(0); ● There are some key differences as well.
○ Literal strings cannot use single-quotes ('')
3 char last = aString.charAt(4);
or triple-quotes of either type.
4 ○ Java includes a char type that represents a
5 System.out.println(first); single character. Single quotes are used for
6 System.out.println(last); char literals, e.g. 'a', '1', '&'.
○ The + operator can concatenate strings
Java strings do not support the use of square together with any other Java type.
brackets ([]), but the charAt(int index) ○ Java strings do not work with square
method will return the char at a specific index. brackets ([]). Instead the charAt(int
index) method is called on the string to get
the char at a specific index.
As with Python, valid indexes range from 0 to ○ Strings are not iterable.
length-1. Java does not support negative indexes. ● Also like Python, Java makes use of a string
literal pool.
○ If the same string literal is used in more than 17
one place, a single copy of the string is stored
1.9 Java Strings
Making the transition from Python strings to Java strings can take some getting used
to, especially because you can't access individual characters in a Java string using [].
Start getting used to using the s.charAt(index) to access the individual characters
in Java strings.
String aString = "Jason"; ● Create a new Java class in the "unit01" folder
char first =
aString.charAt(0); in a file called "Strings.java" and declare a
char last =
aString.charAt(4); main method with the appropriate signature.
○ Create a String variable containing at least
System.out.println(first);
System.out.println(last);
5 characters using the literal of your choice.
'J' 'a' 's' 'o' 'n' ○ Use the charAt(int index) method to print
the first and last characters in the string.
0 1 2 3 4
○ Print at least 3 of the remaining characters.
Java strings are built on top of an ● Use the VSCode run button to run the class.
array of characters, each of which is
accessible via its index using
charAt(int index). 18
● You should recall that a function that belongs to
Methods & Parameters a class is called a method. All code in Java
must be within the body of a class, therefore all
All of the methods that we write in this unit will be
functions in Java are methods.
○ Java methods must be declared between the
public (visible to all parts of the program) and
static (called on the class, not an object). curly braces ({...}) that define the body of a
class.
● There are some key differences between Python
All Java methods must declare a return type. A
void return type indicates that the method does and Java.
not return a value. ○ There is no self parameter.
○ Like any other Java variable, parameters must be
declared with a type as well as a name.
1 public static void example(int x, double y)
○ All methods must declare a return type. A
{
method that does not return anything declares a
2 System.out.println(x + " * " + y
void return type.
3 + " = " + (x * y)); ○ An access modifier may be used to set the
4 } visibility of the method outside of the class. In
this unit, all of the methods that we write will be
Parameters must declare a type as well as a public.
name. When the method is invoked, a compatible
● In Python, a method that does not explicitly
argument must be provided for each parameter.
return a value returns None by default. In Java, a
method with a void return type does not 19
return anything at all.
1.10 Hello, Methods!
Java methods must declare types for any parameters and the type that will be
returned by the method (or void if nothing is returned). Practice now by writing a Java
method and calling it from main.
● Open the HelloWorld class that you wrote previously
Hi. and define a method called "helloName" that declares
String parameters for a first and last name.
Again, again. ○ Don't forget to make the method public and static.
○ Print a message in the format "Hello, <first> <last>!"
to standard output.
● Call your method from main.
● Run the class.

public static void example(int x, double y) {


System.out.println(x + " * " + y
+ " = " + (x * y));
}

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.

In Java, the boolean expression used


by a while loop must be enclosed in ● Create a new Java class in a file named
parentheses...
"CountUp.java" and define a method named
1 int i = 128; "countWhile" that declares a parameter for
2 while(i != 2) {
3 an integer n.
System.out.println(i); ○ Use a while loop to print a count from 0 to n.
4 i = i / 2; ○ Return the sum of the numbers that are
5 }
counted.
...and the statements in the body of the ● Call your method from main and print the
loop must be enclosed in curly braces
({}). sum.
● Run the class.
26
"Classic" for Loops
● Java's "classic" for loop is a more
syntactically compact version of the
counting while loop. The "classic" for loop uses a C-like syntax to make
a more syntactically compact version of a counting
● The loop declaration includes three while loop.
statements separated by semicolons (;).
○ The initialization statement initializes the
counting variable and is executed exactly 1 for(int i=1048576; i != 2; i=i/2) {
once before the first iteration, e.g. int 2 System.out.println(i);
i=1048576; 3 }
○ The boolean expression that controls the
loop. It is evaluated before each iteration of 1 int i = 1048576;
the loop, e.g. i!=2; 2 while(i != 2) {
○ The modification statement that is 3 System.out.println(i);
executed after each iteration of the loop, 4 i = i / 2;
e.g. i=i/2; 5 }
● All three statements are optional.
○ If omitted, the boolean expression is always The initialization statement, boolean expression, and
true. modification statement are all included in the loop
● Java also includes a for each loop similar declaration. 27
to Python's that works with iterable types.
A Closer Look at "Classic" for Loops
A counting while loop has a few A for loop is a more compact syntax
basic parts… for all of the same parts.

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.

1 for(int i=1048576; i != 2; i=i/2) {


1 if(a && b || !c ^ d) { 2 System.out.println(i);
2 System.out.println("foo"); 3 }
3 } else if(x <= y) {
4 System.out.println("bar");
1 int i = 1048576;
5 } else {
2 while(i != 2) {
6 System.out.println("foobar"); 3 System.out.println(i);
7 } 4 i = i / 2;
5 }
Java conditionals combine if(expression) {...}
and else {...} statements that work the same as Java while loops work the same as Python while loops,
they do in Python. There is no explicit elif in Java; with only a few syntactic differences: the boolean expression
instead else if(expression) {...} is used. is in parentheses (()) and the body is in curly braces ({}). 31
1.15 Java Basics
Up to this point you have only written a small amount of Java code, so let's do a quick
practice exercise so that you can continue to reinforce Java syntax. Write a new class
that includes a main method that uses a loop to print the integers between 1 and 100
that are multiples of 3 or 7.
● Create a new Java class in a file called "Basics.java"
and define a main method with the appropriate
signature.
○ Use a loop to print all of the integers that are multiples of 3
or 7 between 1 and 100.
○ Challenge: Do not print numbers that are multiples of
both 3 and 7.
●1 Run
public class MyClass {
the class.
2 public static void main(String[] args) {
3 int x;
4 double pi = 3.14159;
5 System.out.println("Hello, GCIS-
Java programs require a lot of 124!");
scaffolding, even for something as
6 }
simple as "Hello, World!"
7 } 32
● You should recall that a function that belongs
Review: Java Methods to a class is a method.
● Because all Java code must be part of a class,
A Java method signature must include a return type, all functions in Java are methods.
a name, and zero or more parameters. ● The signature of a Java method includes
several parts:
○ An optional access modifier that determines
1 public static int factorial(int n) { the visibility of the method outside of the class.
2 int result = 1; In this unit, all of our methods will have public
3 while(n > 1) { access.
○ The static modifier is used if the method
4 result = result * n;
belongs to the class. In this unit, all of our
5 n = n - 1; methods will be static.
6 } ○ A return type.
7 return result; ■ A method that does not return a value
8 } declares the void return type. Such
methods must not return a value.
■ Otherwise, the method must return a
Declaring a method public and/or static is value of the declared return type.
optional (but we will do both throughout this unit). ○ A valid name.
○ A list of zero or more parameters, each of
which must specify a type and a name. When
If a return type other than void is declared, the
the method is called, and argument must be
method must return a value of a compatible type.
provided for each parameter.
33
1.16 Calculon++
In the last class, you wrote a four-function calculator in a class named Calculon. Let's
practice writing methods by adding a fifth function; a raise method that uses a loop
to compute and return an exponent.

● Open your Calculon class and define a


new method named "raise" that declares
parameters for a floating point base and
an integer exponent.
○ Use a loop to compute the result of raising
the base to the power of the exponent.
public static int factorial(int n) { ● Call your new method from main.
int result = 1;
while(n > 1) { ● Run the class.
result = result * n;
n = n - 1;
}
return result;
} 34
● In Python, type conversions are handled using
the constructor of the desired type, e.g.

Casting Numbers
a_string = str(123)
○ a_list = list("abcdef")
● In Java, converting a less complex type to a Safe Type Conversions
Example
more complex type is considered safe (automatic)
because there is no risk of data loss. Such
int x = 1234;
conversions may happen automatically, e.g. smaller integer -> larger integer
long y = x;
○ long x = 123; // int to long
○ double y = 12.34f; // float to double
int x = 1234;
● However, converting from a more complex integer -> floating point
double y = x;
type to a less complex type risks data loss
and is considered to be unsafe. Attempting to
do so will cause a compiler error Unsafe Type Conversions
Example
(incompatible types), e.g. (requires casting)
○ int x = 3246123456l; // long to int
○ long y = 1234.567; // double to float long x = 1234l;
larger integer -> smaller integer
● You may force the conversion by casting, int y = (int)x;
wherein the desired type is specified in
parentheses on the right side of the float x = 12.34f;
floating point -> integer
int y = x;
assignment statement, e.g.
○ int x = (int)3246123456l;
○ long y = (long)1234.567; Conversions between incompatible types, e.g. boolean
● This is a signal to the compiler that it is OK if and int, will result in a compilation error under any
35 there will be some data loss, e.g. the fractional circumstances (even with a cast).
part of a decimal.
1.17 Casting
Casting is only necessary when assigning a value of a more complex type to a
variable of a less complex type, e.g. a double value to an int variable. Try it out now
to see what happens when you cast values of different types.
Sometimes casting can have…
unintended consequences.
● Create a new Java class in a file called
"Casting.java" and define a main method with the
appropriate signature.
○ Experiment with casting by creating variables different
types and trying to cast them into variables of another
type. Print the values before and after casting. Try at
least two of the suggestions below:
■ int to long
double x = 47.2; ■ long >3 Billion to int
int y = (int)x; // cast
■ char to int
needed
■ int in the range 33 ≤ i ≤ 126 to char
When casting, the type to cast into is
specified in parentheses next to the
■ boolean to int
value being cast. ● Run the class. 36
Standard Input ● System.out is a reference to standard
output and the println and print functions
The Scanner class is in the java.util package, can be used to direct output to the terminal.
and so must be imported. Imports are done at the ● Similarly, System.in is a reference to
top of the class file. standard input, and it can be used to read
user input from the terminal, but it's a little
import java.util.Scanner; unwieldy to use.
● As an alternative to System.in, Java provides
The new keyword will create a new Scanner by the java.util.Scanner class, which can be
calling its constructor. The Scanner needs to be
used to read data from any input source, e.g.
configured to read from a specific data source, e.g.
standard input (System.in). standard input, files, etc.
○ A Scanner needs to be told from where to read
by passing the input source into its
1 Scanner scanner = new Scanner(System.in); constructor, e.g. Scanner s = new
2 System.out.print("Enter age: ");
3 int age = scanner.nextInt(); Scanner(System.in);
4 int months = age * 12; ● Scanner provides lots of useful methods:
5 System.out.println("Age in months: " + ○ next() returns the next word typed by the user
months);
(up to the next whitespace).
6 scanner.close();
○ nextLine() return everything up to the point
where the user pressed the enter key.
Methods like next(), nextLine(), and
○ nextInt(), nextLong(), nextFloat(), etc.
nextInt() will return input typed by the user into
returns the next word as the corresponding
the terminal. The Scanner should be closed when
type.
it is no longer needed. 37
● It is considered good programming practice to
1.18 Hello, You!
You may remember that "Hello, You!" is a modified version of the classic "Hello,
World!" program that prompts the user to enter their name and prints a customized
"Hello!" message to standard output. Practice using Scanner to implement it now.

● Create a new Java class in a file named


"Hello.java" and define a new method named
"helloYou".
○ Prompt the user to enter their name.
■ Hint: the System.out.print() method will
not terminate with a newline, so the user can
type on the same line as the prompt.
import java.util.Scanner; // import! ○ Use a Scanner to read the user's input and store it
in a variable.
Scanner scanner = new Scanner(System.in); ■ Remember, Scanner is in the java.util
System.out.print("Enter age: ");
int age = scanner.nextInt();
package. Don't forget to import it!
int months = age * 12; ○ Print a message in the format "Hello, <name>!"
System.out.println("Age in months: " + ● Call your method from main.
months);
scanner.close(); ● Run the class. 38
1.19 Calculon+++
We'll be using the Scanner a lot to read user input from standard input. Let's practice
a little more by making an improvement to the five function calculator by prompting
the user to enter the values to add, subtract, multiply, divide, and raise.

● Open your Calculon class and update


your main method.
○ Prompt the user to enter two floating
point operands.
○ Print the results of calling all five
methods on your calculator.
import java.util.Scanner; // import! ● Run the class.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();
int months = age * 12;
System.out.println("Age in months: " +
months);
scanner.close(); 39
● JUnit is a unit testing framework that
is similar to pytest in Python.
○ You will write a separate JUnit test for
each Java class in your program.
JUnit Unit Tests
○ The unit test is a Java class. By
convention, the unit test is named the
same as the class under test with "Test" Each test method is marked with the @Test annotation
suffix, e.g. "MyClassTest". so that JUnit knows which methods to execute.
○ You will write one or more test methods
for each non-trivial method in your Java
class. 1 public class EuclidGCDTest {
● 2 @Test
JUnit uses Java annotations to find test 3 public void gcd100() {
methods inside of your unit test. 4 // setup
○ @Test annotates each test method. 5 int a = 100;
○ JUnit and/or VSCode will not be able to find 6 int b = 60;
the tests if they are not annotated properly. 7 int expected = 20;
● JUnit also includes many built in 8
9 // invoke
assertions, e.g. 10 int actual = EuclidGCD.gcd(a, b);
○ assertEquals(expected, actual) 11
○ assertEquals(float1, float2, delta) 12 // analyze
○ assertTrue(actual) 13 assertEquals(expected, actual);
○ assertNotNull(actual) 14 }
○ etc. 15 }
● Using JUnit with VSCode requires
configuring your project to include the A good JUnit tests follow the same pattern as pytest:
JUnit library. setup, invoke, and analyze using assertions.
○ You should have downloaded and
40 configured this as part of the pre-semester
assignment.
1.20 Running Your First JUnit Test
The project that you have been given should already be configured to run JUnit tests,
including a "HelloWorldTest" that has been provided for you. Make sure that
everything is configured properly by using VSCode's Test Runner ( ) to run the
provided unit test now.
If everything is working as
Open the provided HelloWorldTest.
expected, you should see
You can find it under "test" in your root
green check marks indicating
project folder.
that the test passed!

import org.junit.jupiter.api.Test;

public class HelloWorldTest {


@Test
public void helloWorld() {
assertEquals("Hello, World!",
"Hello, World!"); Open the VSCode Test Runner ( ) and
} use "Run Test" ( ) to run the provided
} test.
41
If VSCode has identified any
problems, try to fix them. If you're
not sure how, raise your hand
and ask for help!
Whenever you see this
image, it's a reminder to
check your PROBLEMS And remember: it's not about
tab. avoiding making mistakes. It's
about learning how to fix them as
we make them.

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.

The output from the tests is


displayed in the Debug Console.
But it's not very useful.

44
○ Statements are terminated with a semicolon.

Review: All the Java


○ Curly braces ({}) are used to define blocks
of code.
● Java is statically typed, meaning that all
1 public class Summer { variables must be declared with a type and a
2 name.
3 public static int natSum(int n) { ○ Java includes 8 primitive types including
4 if(n <= 0) { integers, floating point values, characters,
5 return 0; and booleans. All other types are reference
6 } else { types, including strings.
7 int sum = 0; ○ Only values of a compatible type can be
8 while(n > 0) {
9 sum += n;
assigned to a variable, e.g. int x = 5;
10 n = n - 1; ● Java Strings must be enclosed in double-
11 } quotes (""), and the + operator can be used
12 return sum; to concatenate any type onto a string, e.g.
13 }
○ String s = "abc" + 123 + false;
14 }
15 ● Java method signatures have several parts:
16 public static void main(String[] args) { ○ An optional access modifier like public
17 int total = natSum(100); determines visibility of the methout outside of
18 System.out.println("Sum 1-100: " the class.
19 + total); ○ A static modifier indicates that the method
20 } belongs to the class and can be called without
12 }
an object.
○ A method must return a value of its declared
Not every Java class needs to be executable, but an return type unless it is void.
executable Java class must have a main method with a ○ A valid method name.
specific signature. ○ Zero or more parameters including types
and names. 45
● Java supports while loops and "classic" for
1.24 Reverse a String
Let's practice some of the Java basics that we've learned earlier in this unit, including
writing methods, returning values, and looping over strings; write a method that
returns a reversed copy of a string.

int length = string.length(); ● Create a new Java class named "Miscellany"


char c = string.charAt(3); and define a method named "reverseChars" that
String cat = "abc" + "def"; declares a String parameter.
○ Use a loop to create a copy of the string with
for(int i=5; i<11; i++) {
the characters reversed.
System.out.println(i);
○ Remember you can use concatenation (the +
}
operator) to concatenate anything onto a
Remember: you can access individual string.
characters in a string using the
charAt(index) method inside of a for
○ Return the reversed copy.
loop. ● Run the class.
46
● A data structure is a grouping of related
elements.
Java Arrays ○ In the previous course, we worked with lots of
different data structures including lists, sets,
dictionaries, stacks, and queues.
● You should recall that an array is the most
Arrays are allocated as a contiguous block of
memory that can be efficiently accessed using an basic kind of data structure, and it has the
index that ranges from 0 to length-1. following properties.
○ Arrays are fixed length; arrays are created to
be a non-negative size, and the size never
An array can be visualized as a table with a single changes.
row. The number of columns is determined by the ○ Arrays can store elements of any type.
length of the array. ○ Individual elements are accessed using an
index that ranges from 0 to length-1.
● A Java array is declared using any type with
0 0 0 0 0 0 0 0 0 0 square brackets, e.g.
○ String[] strings;
0 1 2 3 4 5 6 7 8 9 ○ int[] integers;
● An array is initialized using the new keyword
and the size of the array in square brackets,
Arrays are created to be a specific size using the new
keyword, which tells Java to allocate memory and e.g.
○ integers = new int[10];
store something there.
○ The length field can be used to get the length
of the array, e.g. integers.length
In the case of an array, the memory allocated is a ● Java fills each array with default values
contiguous block large enough to hold the number of appropriate for the type.
elements specified when the array is created. ○ 0 for numeric types (including char).
47
○ false for booleans.

1.26 Array of Squares
Like so many other things we have talked about in this unit, arrays in Java are very
similar to those that you used in Python. The only real difference is the syntax for
creating and using them. Practice now by implementing a method that returns an
array of squares.
int[] numbers = new int[5]; ● Open your Miscellany class and define a method
numbers[0] = 2;
numbers[1] = 3; named "squares" that declares a parameter for an
numbers[2] = 5; integer n.
numbers[3] = 7; ○ Create an integer array large enough to hold n
numbers[4] = 11;
elements.
for(int i=0; i<numbers.length; i+ ○ Use a loop to set the value at each index to the square
+) { of the index
System.out.println(numbers[i]); ■ i.e. 02, 12, 22, …, n-12.
} ○ Return the array.
● Call your squares method from main and print the
String s =
results.
Arrays.toString(numbers);
Creating an array works a little differently in
Java, but using one is very similar to the
○ Use the Arrays.toString() method to print your array
arrays module in Python. to standard output (see the example to the left).
48
● Run the class.
● In Python we experimented with two-
2-Dimensional Arrays dimensional lists. In Java, it is possible to
create two-dimensional arrays.
○ A 2D array is an array of arrays.
You can depict a two-dimensional array with 4
○ Like any other array, a two-dimensional array
rows and 6 columns as a table...
must be declared with a type, and can only be
used to store values of that type.
0 1 2 3 4 5 ○ Two-dimensional arrays are declared using two
sets of square brackets, e.g. int[][] table;
0 5 3 7 0 0 0 ○ 2D arrays are initialized with two sizes, which
you can think of as the number of rows and
1 13 16 0 3 4 17 columns in the array, e.g. table = new
int[4][6];
2 2 10 5 6 5 14 ● The values in a two dimensional array are
accessed using two indexes.
3 1 18 11 4 3 12 ○ You can think of these as the index of the row
and column of the data that you are looking for.
○ For example: int value = table[4][5] will
The table is really an array of arrays. Each row is retrieve the value from row 4, column 5 in the
an array of values, e.g. row 0 is the array 2D array.
containing the values [5, 3, 7, 0, 0, 0]. ● You can also fetch the array for an entire row
all at once by using only one index.
Let’s take a closer look... ○ For example: int[] row = table[3] will grab
the array that contains the values in the row 3.49
A Closer Look at Two-Dimensional Arrays
The first “dimension” is really just And each “row” is really an array
an array. Each value in the array is that contains elements of the
the address of another array. 0 1 2 3 4 5 specified type, e.g. integers.

5 3 7 0 0 0 While it can be handy to imagine


such arrays as a table, it is possible
for different rows to be different
0 1 2 3 4 5 lengths...
0
13 16 0 3 4 17
1
0 1 2 3 4 5 6 7 8
2
2 10 5 6 5 14 2 31 7
3
0 1 2 3
These kinds of two-dimensional
arrays are referred to as “ragged”
17 19 23 4 because the uneven lengths create
a ragged edge. 50
1.27 Multiplication Tables
You may remember using 2D-lists in Python to create multiplication tables. Let's try
the same thing in Java using a two dimensional array instead.

// 5 rows, 4 columns ● Open your Miscellany class and define a


int[][] table = new int[5][4];
new method named
// row 1 "multiplicationTable" that declares a
int[] entireRow = table[1]; parameter for rows and columns.
// the value at row 3 column 2 ○ Create a two-dimensional array of the
int individualValue = table[3][2]; specified size.
○ Use loops to set the value at each index to
for(int row=0; row<table.length; row++) {
the product of its row and column,
for(int col=0; col < table[row].length; col++)
starting at 1. Do not include 0s!
{
System.out.println(table[row][col]); ● Call your method from main.
} ○ Use a loop to print each row in the table using
} the static Arrays.toString() method, e.g.
In a 2D array a single index is used to get an entire row, and Arrays.toString(table[0]) will print the
two indexes are needed to retrieve an individual value from a
row.
first row.
51
● Run the class.
1.28 Invalid Input
We wrote many Python programs that expected the user to use standard input to
enter numeric values into a prompt. If they entered non-numeric values, the program
would crash with a ValueError. What happens if the user enters non-numeric data
into your Calculon program?
● Run the Calculon program.
○ Use standard input to enter non-numeric
data for one of the two values.
○ What happens?

In Python, trying to convert an invalid string


into an integer or float will cause an error.

If the error is not handled using


try/except then the program will crash.
52
● In Python, we saw lots of different kinds of
errors, e.g.
Java Exceptions ○ Trying to convert a non-numeric string into an
integer raises a ValueError.
○ Trying to index into an integer raises a
Code that may throw an exception will crash your TypeError.
program if the exception is not handled. ○ Trying to access an invalid index in a list raises
an IndexError.
○ Trying to open a file that doesn't exist raises a
The code may be enclosed in the body of a try FileNotFoundError.
block. The try must be followed by a catch that ● In Java these types of errors are called
specifies the type of exception it handles. exceptions.
○ Specifically, trying to read non-numeric input
from the user as an integer causes an
1 Scanner scanner = new Scanner(System.in); InputMismatchException.
2 try { ○ You may have seen other exceptions before,
3 System.out.print("Enter a number: "); including IndexOutOfBoundsException and
NullPointerException.
4 int x = scanner.nextInt();
● Java code that causes an exception is said to
5 } catch(InputMismatchException e) {
throw the exception.
6 System.out.println("Invalid integer!"); ● As with Python, if nothing is done to handle
7 } the error, your program will crash.
○ In Python, we used try/except to handle
The code in the catch block is executed iff an errors that were raised.
exception of a matching type is thrown in the try ○ In Java, try/catch works almost exactly the
block. same way. One notable difference is that the
catch must specify the type of exception that
it handles. 53
1.29 Using try/catch in Java Programs
Handling errors in Java works a lot like it does in Python. Instead of using try/except,
we will use try/catch to handle exceptions that may occur. Try it out by modifying
your Calculon class so that it displays an error if the user enters invalid input to
Scanner scanner = new
either prompt.
Scanner(System.in);
try { ● Open the Calculon class and navigate to
System.out.print("Enter a number:
"); the main method.
int x = scanner.nextInt();
} catch(InputMismatchException e) {
○ Use a try/catch to handle the exception
System.out.println("Invalid that occurs if the user types invalid input.
integer!");
}
○ Print an error message and exit gracefully.
● Run your updated class and enter non-
numeric data.
○ What happens?

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.

Checked ○ You are not explicitly required to handle an


unchecked exception in any way.
○ Of course, in the event that an unchecked
Exceptions
Because IOException is a checked exception, it
must be explicitly handled using a try/catch or by
exception is thrown, it will crash your program if it
is not handled.
rethrowing the exception.
● Java also includes checked exceptions.
○ If a program calls a method that throws a
Many of the methods on the various I/O classes
checked exception, the programmer must handle
throw IOException (including the constructors).
the exception in some way.
○ Failure to handle a checked exception will cause a
1 public static String readOneLine() compiler error.
2 throws IOException {
○ In a way, this can be very good - checked
3 FileReader file =
4 new FileReader("a_file.txt"); exceptions do not "sneak through" and crash your
5 BufferedReader reader = program like unchecked exceptions can
6 new BufferedReader(file); sometimes do.
7 String line = reader.readLine();
● A checked exception can be handled in two
8 reader.close();
9 return line; ways.
10 } ○ Using a try/catch in the same way as we did
previously with unchecked exceptions.
○ Rethrowing the exception by adding a throws
A throws declaration is added to the method declaration to the method, e.g.
signature. In the event that the specified type of ■ void method() throws IOException
exception occurs, it is automatically rethrown.
● Nearly every method used to read data from 59
files can throw a java.io.IOException.
1.32 Handling Checked Exceptions
One way to handle a checked Nearly every Java I/O operation may throw an
exception is to rethrow it. IOException if something goes wrong. IOException
is checked, and so must be handled in some way.
public static void doSomething()
Update your Files class to better handle checked
throws AnException {
int x = aMethod();
exceptions if and when they occur.
}
● Open your Files class and navigate to the
Another is to try/catch it. printFile method.
○ Update the method signature to declare that it throws
public static void doSomething() IOException.
{ ● Use a try/catch in your main method to handle the
try {
doSomething(); exception.
} catch(RuntimeException e) {
○ If an IOException occurs, print an error message and
doSomethingElse();
} exit.
}
● Run the class.

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.

1 FileWriter fw = ● Create a new Java class named "TextEdit" and define


2 new FileWriter("a_file.txt"); a main method with the appropriate signature.
3 PrintWriter writer = ○ Prompt the user to enter a filename and use it to create a
4 new PrintWriter(fw); FileWriter.
5 writer.print("Your age is: "); ○ Use the FileWriter to create a PrintWriter that you will
6 writer.print(18); use to print lines to the file.
7 writer.println(" years old."); ○ Use a Scanner and a loop to allow the user to enter text
8 writer.flush(); into standard input. Use the PrintWriter to write each
9 writer.close(); line of text to the file. Stop if the user enters a blank line.
○ Don't forget to close your Scanner and FileReader!
○ Use a try/catch to handle any exceptions and exit
A FileWriter and PrintWriter can
be used in conjunction to make writing gracefully.
text fairly easy. ● Run the class.
62
on that file until it is closed.
○ This lock will prevent other processes from
try-with-resources ●
interacting with the file.
However, properly closing a file can be
When using try-with-resources, resources are challenging under some circumstances.
allocated in a semicolon-delimited list inside ○ What if there is an exception?
parentheses (shown in orange for emphasis). ○ What if the file fails to open at all?
○ What if closing the file throws an exception?!
1 try(FileWriter out = ● You should remember that Python includes a
2 new FileWriter(name); with-as statement that insures that a file is
3 PrintWriter writer = always closed, regardless of whether an error
4 new PrintWriter(out)) { is raised.
5 ● Java includes a similar feature: try-with-
6 writer.println("Hello, File!"); resources.
7 writer.flush(); ○ Resources like FileInputStream or
8 } PrintWriter are initialized in parentheses
after the try.
○ Any such resources are automatically closed
The scope of any resources that are opened is the
try block - they can be used normally anywhere when the body of the try exits (after the closing
between the curly braces. curly brace).
● A try-with-resources does not need to be
The resources are automatically closed when followed by a catch block.
execution exits the try block, even if an exception ○ If a catch block is used, the resources will be
is thrown in the block. closed after it is executed.
63
○ If you do omit the catch block, a checked
1.34 Using try-with-resources in Java
In Python we used with-as to open files and make sure that the file was closed (even
if an error occurred). Using try-with-resources in Java works exactly the same way.
Practice using it by updating your TextEdit class to use try-with-resources to insure
that the output file is closed.
1 try(FileWriter out = ● Open your TextEdit class and navigate to
2 new FileWriter(name);
the main method.
3 PrintWriter writer =
○ Modify your implementation so that it uses
4 new PrintWriter(out)) {
try-with-resources to open both the
5 FileWriter and the PrintWriter.
6 writer.println("Hello, ○ You may delete the explicit calls to close
File!"); both.
7 writer.flush(); ○ You will still need to make sure that the
8 } Scanner is closed.
Any resources opened between the parentheses
● Run the class.
after the try-with-resources are automatically
closed when the try block exits.
64
Summary & Reflection
ss es in
a
Cl & ma What is one thing
av a s that you wish you
● J ethod d What is one knew more about
r
● M tanda tput
as we move
new thing that
forward?
u
● S put/O es &
you learned
In Typ s
today?
av a or
● J perat nals & What one
O ditio question do
C on with you have about
● p s g
Loo Testin today’s class?

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

You might also like