0% found this document useful (0 votes)
8 views

1_cps209_python_to_java

CPS 209 is a Computer Science II course taught by Prof. Alex Ufkes, focusing on Object Oriented Programming (OOP) using Java. The course includes weekly lab assignments, quizzes, projects, a midterm, and a final exam, with specific grading criteria and penalties for late submissions. Students are advised to check D2L for course materials and announcements, and academic integrity is emphasized, prohibiting the use of unauthorized aids during evaluations.

Uploaded by

qasemali200502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

1_cps209_python_to_java

CPS 209 is a Computer Science II course taught by Prof. Alex Ufkes, focusing on Object Oriented Programming (OOP) using Java. The course includes weekly lab assignments, quizzes, projects, a midterm, and a final exam, with specific grading criteria and penalties for late submissions. Students are advised to check D2L for course materials and announcements, and academic integrity is emphasized, prohibiting the use of unauthorized aids during evaluations.

Uploaded by

qasemali200502
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

CPS 209

Computer Science II
Prof. Alex Ufkes

Topic 1: Course intro, from Python to Java


Notice!

Obligatory copyright notice in the age of digital


delivery and online classrooms:

The copyright to this original work is held by Alex Ufkes. Students


registered in course C/CPS 209 can use this material for the purposes
of this course, but no other use is permitted, and there can be no sale
or transfer or use of the work for any other purpose without explicit
permission of Alex Ufkes.

© Alex Ufkes, 2020, 2025 2


Instructor

Alex Ufkes
[email protected]
Class times:
Monday 11–12 (DSQ 13)
Thursday: 8-10 (DSQ 03)
Lab times:
Check your schedule

© Alex Ufkes, 2020, 2025 3


When Contacting…

• E-mail – I check it often ([email protected])


• Please put CPS209 in the subject line
• Include your full name, use your TMU account

© Alex Ufkes, 2020, 2025 4


Course Administration

• Announcements related to this course will


be made on D2L. Be sure to check regularly!
• Course outline, labs, lecture slides, and
grades will all be found on D2L.

© Alex Ufkes, 2020, 2025 5


Course Description

“A continuation of CPS 109. Emphasis is placed


on code structure, algorithm development, and
Object Oriented design principles.”

OOP through Java, with lots of fun topics along the way.

© Alex Ufkes, 2020, 2025 6


Course Text

Nothing mandatory!

• Save your money.


• Refer to the slides/D2L for online resources.
• I will post lecture slides every week.

© Alex Ufkes, 2020, 2025 7


Evaluation

From the course outline:

5% - Weekly lab assignments: submitted at the end of each week on D2L


5% - Weekly lab quizzes: take place during the labs
20% - Projects (x2): deadlines for the 2 projects TBD
30% - Midterm test: Practical, involves coding on a lab computer. Saturday March 8
40% - Final exam: Takes place during final lecture period. Same style as midterm

Must achieve a combined grade of 50% across the midterm/exam.

© Alex Ufkes, 2020, 2025 8


Labs

• Labs begin in week 2 (week of January 20)


• Quizzes must be completed in-person in the lab
• Will count best 7 of 8 in-lab quizzes. This is so you are not
penalized due to an illness or other unexpected circumstances.
No academic consideration if you miss only one lab.

• Lab assignments due by midnight at the end of each week


• Submitted on D2L

© Alex Ufkes, 2020, 2025 9


Regarding Deadlines

From the course outline:


Late Submissions
Late lab submissions will be penalized at a rate of 3n%, where n is the
number of days late. One day late is a 3% penalty, two days 9%, three
days 27%, four days 81%, and five or more days receive zero.

• The late penalty starts small, but it ramps up quickly.

© Alex Ufkes, 2020, 2025 10


Lab Environment/IDE

Ubuntu Linux VScode


© Alex Ufkes, 2020, 2025 11
VScode

© Alex Ufkes, 2020, 2025 12


Academic Integrity

• No communication with other students during tests

• No aides aside from those specified for tests

• Posting lab/assignments anywhere on the internet is prohibited


• The use of contract cheating sites is also prohibited

© Rick Valenzano, 2025 13


Policy 60

https://www.torontomu.ca/senate/policies/academic-integrity-policy-60/

3. Cheating includes but is not limited to:


3.1. having ready access to and/or using aids or devices (including wireless
communication devices) not expressly allowed by the instructor during an
examination, test, quiz, or other evaluation

- No device capable of receiving or transmitting information


may be worn during tests.
- No smart watches, no meta glasses. If have a prescription,
you MUST wear a regular old pair of non-smart glasses.

© Alex Ufkes, 2020, 2025 14


AI Coding Assistants

• ChatGPT, GitHub CoPilot, etc.


• Not permitted for use in this class
o Single word auto-completion is fine
• More generally, be careful using them
o An effective tool you will use in your career, but need basics first
• The purpose of course assessments is to develop your skills
o Can’t send a robot to the gym and expect to get in better shape

© Rick Valenzano, 2025 15


Any Questions?

© Alex Ufkes, 2020, 2025 16


Today

From Python to Java:


• “Hello, world!” in Java
• Java primitive types, static typing
• Control structures in Java
• Static methods VS Python functions
• Java arrays VS Python lists
• Examples demonstrating the above

© Alex Ufkes, 2020, 2025 17


Why Java?

In general, why do we need to know more than a single language?

• Different languages have different strengths and weaknesses.


• Some things are easier in Python, others are easier in Java.
• Different languages let us think about programming in different ways.
o Much more on this in CPS506

The more languages you learn, the easier it becomes to learn the next one.

© Alex Ufkes, 2020, 2025 18


Java Overview

Java Design Goals


1. Be safe: can run inside a browser and will not attack your computer
2. Be portable: run on many different operating systems

Java programs distributed as instructions for a Java Virtual Machine (JVM)


• This makes it platform-independent since JVMs are available for most OSs

© Alex Ufkes, 2020, 2025 19


Installing Java

You all probably have Java installed, but you might not
have the JDK (compiler, developer tools) installed:

https://www.oracle.com/pk/java/technologies/downloads/

After installing, test the following commands in a terminal:

java --version
javac --version

© Alex Ufkes, 2020, 2025 20


If you see “command not found”
or similar, try rebooting after you
install the JDK.

© Alex Ufkes, 2020, 2025 21


Java Extension for VSCode

Already installed on the lab computers:

More on Java unit testing in the labs

© Alex Ufkes, 2020, 2025 22


© Alex Ufkes, 2020, 2025 23
• Download VScode, install Java extensions.
• Create a new Java file in VScode.
• You will see a Run|Debug indicator above
your main() method.

© Alex Ufkes, 2020, 2025 24


This class is public.
More on that later. Class name is Hello
• Capitalized, camel case.

public class Hello


{
Class body defined by curly braces
• In Python, we use indenting This is a Java class
• Java doesn’t care about whitespace

Let’s add a method to our Main class


© Alex Ufkes, 2020, 2025 25
Every Java program
Method is public, static, and void. begins execution in the
main() method
public class Hello
Method name is main
{
public static void main(String args[])
{

}
} This is a Java
Method body defined by curly braces. method

© Alex Ufkes, 2020, 2025 26


public static void:
• public – can be called from
public class Hello
{ outside HelloWorld class.
public static void main(String args[]) • (In Python, everything is public)
{ • static – method belongs to the
class, not an instance of the class.
} • More on static later.
}
• void – No return value.
• Unlike Python, not even None

We have a Hello class that contains a main method.


Right now this program doesn’t do anything.

© Alex Ufkes, 2020, 2025 27


String literal “Hello World”
public class Hello passed to System.out.println
{
public static void main(String args[])
{
System.out.println("Hello, world!");
}
• System is a class, out is a static instance
} of another class, println is a method. Semicolons are used
• There’s so much in a simple print to terminate Java
statement for us to unpack. statements

© Alex Ufkes, 2020, 2025 28


public class Hello
{
public static void main(String args[])
Is this: {
System.out.println("Hello, world!");
}
}

Yes.
The same public class Hello {
public static void main(String args[])
as this? { System.out.println("Hello, world!"); } }

(But don’t do this)

© Alex Ufkes, 2020, 2025 29


© Alex Ufkes, 2020, 2025 30
public class Hello
{
public static void main(String args[])
{
System.out.println("Hello, world!");
}
}

• String literals denoted with double quotes.


• Strings are not primitive! They are built from smaller pieces.
• Java has 8 primitive types.
• These are used as building blocks to create more complex types

© Alex Ufkes, 2020, 2025 31


Primitive Data Types

Primitive? Not objects. They have value, but no associated behavior (methods)

© Alex Ufkes, 2020, 2025 32


Primitive Data Types

Java double is the same as Python floating-point (IEEE-754)


© Alex Ufkes, 2020, 2025 33
As in Python….

© Alex Ufkes, 2020, 2025 34


So too in Java

Floating-point pitfalls are


not language-specific
© Alex Ufkes, 2020, 2025 35
Unlike Python:
• Java is statically typed
• Types must be known at
compile time.
• Requires type annotations
when declaring variables

© Alex Ufkes, 2020, 2025 36


Primitive Data Types

Standard int in Java is 4 bytes. Compare to Python…?


© Alex Ufkes, 2020, 2025 37
© Alex Ufkes, 2020, 2025 38
© Alex Ufkes, 2020, 2025 39
Overflow: Gangnam Style

© Alex Ufkes, 2020, 2025 40


Primitive Data Types

Different integer types, different sizes. Use whichever is appropriate.


© Alex Ufkes, 2020, 2025 41
Primitive Data Types

Unlike Python, Java has a distinct char type.


© Alex Ufkes, 2020, 2025 42
Unicode Table:
• Expanded version of ASCII table
• It’s huge (0-65535)
• Small portion shown here

© Alex Ufkes, 2020, 2025 43


Primitive Literals

Integer (byte, short, int, long): 0 -5 360 12000


Floating Point (double): 0.15 -33.3 3.14159
Floating Point (float): 0.15f -33.3f 3.14159f
Character (char): ‘a’ ‘A’ ‘#’ ‘ ’ ‘\n’
Boolean (boolean): true false

© Alex Ufkes, 2020, 2025 44


Type System

© Alex Ufkes, 2020, 2025 45


Static VS Dynamic

When are types checked?

Statically typed languages perform type checking at compile time


• Checked while converting source code to machine (or byte-) code

Dynamically typed languages perform type checking at run-time


• Checked on the fly while instructions are being executed.

Statically Typed languages: C/C++, Java, Haskell, Rust


Dynamically Typed languages: Python, Smalltalk, Elixir

© Alex Ufkes, 2020, 2025 46


public class Arithmetic
{
public static void main(String[] args)
{
int x = 42; • In Java, variable type must be
double y = 3.14; indicated explicitly.
char z = 'A'; • Unlike some languages, Java
} does not have type inference.
}

© Alex Ufkes, 2020, 2025 47


Type Mismatch

© Alex Ufkes, 2020, 2025 48


Type Precision

Compile errors will also occur when there is a loss of precision:

• No implicit truncation from floating point to integer


• Floating point literals are double precision
• Need to indicate single precision explicitly

© Alex Ufkes, 2020, 2025 49


Logic, Conditions

© Alex Ufkes, 2020, 2025 50


Logic, Comparison

public class Logic


{
public static void main(String args[])
{
boolean x = true, y = false;
System.out.println(!x);
System.out.println(x && y);
System.out.println(x || y);
not has higher precedence System.out.println(x && !y);
than and and or. System.out.println(!x || y);
}
}

© Alex Ufkes, 2020, 2025 51


Logic, Comparison

public class Logic


{
public static void main(String args[])
{
boolean x = true, y = false; • Logical operations must be
System.out.println(!x); between Boolean values.
System.out.println(x && y); • No such thing as “truthiness”
System.out.println(x || y); • &&, ||, ! VS and, or, not
System.out.println(x && !y);
System.out.println(!x || y);
}
}

© Alex Ufkes, 2020, 2025 52


Logic, Comparison

These are all the same as Python:


public class Logic
{
public static void main(String args[])
{
int x = 2, y = 7;
System.out.println(x > y);
System.out.println(x <= y);
System.out.println(x == y);
System.out.println(y != x);
System.out.println(y > x);
}
}
© Alex Ufkes, 2020, 2025 53
(x >= 3) && (x <= 5)

Are these the same?

3 <= x <= 5
• In Python they are, but this is not true of Java. Beware!
• Why? 3 <= x results in Boolean. Can’t do Boolean <= 5. Type error.
• Python reads this expression in the correct mathematical way.
© Alex Ufkes, 2020, 2025 54
3 <= x <= 5

© Alex Ufkes, 2020, 2025 55


Precedence

1. Method calls: Math.sqrt(x), ( )


2. Unary: -, !, ++, -- -> (int)
3. Binary: *, /, % -> +, -
4. Comparison: <, <=, >=, > -> ==, !=
5. Logical: && -> ||
6. Assignment: =

When in doubt, use parentheses!

© Alex Ufkes, 2020, 2025 56


Selection
True False

Condition

© Alex Ufkes, 2020, 2025 57


Selection: if-else

In Python:

© Alex Ufkes, 2020, 2025 58


Return type Parameter type

© Alex Ufkes, 2020, 2025 59


Selection: if-else

An if structure only applies to a single statement:

© Alex Ufkes, 2020, 2025 60


Selection: if-else

An if structure only applies to a single statement:

public static void main(String args[]) • Use curly braces to create a


{ compound statement.
int a = 7; • Everything in the braces
if (a < 0) belongs to the if clause.
{ • The same is true of all other
System.out.println("Negative"); control structures in Java.
System.out.println("Prints"); • Best practice for beginners?
} Always use curly braces.
}

© Alex Ufkes, 2020, 2025 61


Selection: if-else

• Nesting control structures in Java works the same way as Python


• In Java, however, curly braces indicate scope (not whitespace)
public static void main(String args[])
{
int a = 7;
if (a > 0) {
System.out.println("Positive");
}
else {
if (a > 0) {
System.out.println("Negative");
}
else {
System.out.println("Zero");
}
}
© Alex Ufkes, 2020, 2025 } 62
switch
Statements

© Alex Ufkes, 2020, 2025 63


switch(control_value) integer or character
{
case value1:
/* statement(s) */
break; Notice:
case value2: These are colons!
/* statement(s) */ Not semi-colons.
break;
case value3:
/* statement(s) */
break;
default:
/* statement(s) if no case value
matches the control value */
}
© Alex Ufkes, 2020, 2025 64
int control = 0;
If control == 0,
switch(control)
{ Execute the following statements:
case 0:
/* statement(s) */
The break keyword exits the
break;
case 1: switch control structure
/* statement(s) */
break;
case 2:
/* statement(s) */ Does not
break;
default: execute!
/* statement(s) if no case value
matches the control value */
}

© Alex Ufkes, 2020, 2025 65


if (control == value1)
{
switch(control) /* statement(s) */
{ }
case value1: else if (control == value2)
/* statement(s) */ {
break; /* statement(s) */
case value2: }
/* statement(s) */ else if (control == value3)
break; {
case value3: /* statement(s) */
/* statement(s) */ }
break; else
default: {
/* statement(s) if no /* statement(s) if no
value matches control */ value matches control */
} }
© Alex Ufkes, 2020, 2025 66
char colour = ‘G’;
We can have multiple cases per outcome.
switch(colour)
{
case ‘R’:
case ‘r’: False!
System.out.println(“Stop!”);
break; Output?
case ‘Y’:
case ‘y’: False!
System.out.println(“Caution!”);
Go!
break;
case ‘G’: True
case ‘g’:
System.out.println(“Go!”);
break;
default: Does not
System.out.println(“Invalid colour”);
} 2020, 2025
© Alex Ufkes,
execute! 67
char value = ‘A’;
Something’s missing ...
switch(value)
{
case ‘A’:
System.out.println(“A ”); Output?
case ‘B’:
System.out.println(“B ”);
case ‘C’:
A B C D E Default
System.out.println(“C ”);
We forgot the breaks! Once a
case ‘D’:
System.out.println(“D ”); true condition is found, everything
case ‘E’: below gets executed UNLESS we
System.out.println(“E ”); use a break to exit the switch.
default:
System.out.println(“Default”);
}
© Alex Ufkes, 2020, 2025 68
Looping in Java

© Alex Ufkes, 2020, 2025 69


Recall: for in Python

Good for iterating a known, fixed number of times


for x in range(0, 5):
print(x)

© Alex Ufkes, 2020, 2025 70


Recall: for in Python

• The values of the range aren’t necessarily important.


• The number of values are what control the number of iterations.

© Alex Ufkes, 2020, 2025 71


for Loop Examples: Factorial

© Alex Ufkes, 2020, 2025 72


for Loops in Java

No semicolon!
Semicolons go here!

for (initialization; condition; update)


{
/* statements executed/repeated */
/* if condition is true */
}

Compound statement defines loop body


© Alex Ufkes, 2020, 2025 73
for Loops in Java

initialization condition
for (int i = 1; i <= 3; i++)
{
Loop
System.out.print(“Hello!”);
body }
Exit loop
Order of execution: False

initialization condition True body update

© Alex Ufkes, 2020, 2025 74


Factorial: Static Java Method

public class Loops • HelloWorld has two


{
public static void main(String[] args) methods – main, factorial
{ • In main(), we’re calling
for (int i = 0; i <= 5; i++) factorial in a for loop
System.out.println(factorial(i));
}

public static int factorial (int n)


{
int f = 1;
for (int i = n; i > 1; i--)
f *= i;
return f;
}
}

© Alex Ufkes, 2020, 2025 75


What is the output of this for loop?

int n;
for (n = 1; n >= 0; n++) {
System.out.println(n);
}

n will ALWAYS be bigger than 0


© Alex Ufkes, 2020, 2025 76
What is the output of this for loop?

int n;
for (n = 1; n >= 0; n++) {
System.out.println(n);
}

n will ALWAYS be bigger than 0


© Alex Ufkes, 2020, 2025 77
Beware Infinite Loops!
Except…..
This loop is not truly infinite. Eventually, n will
overflow and become negative, thus making the
condition n >= 0 false.

© Alex Ufkes, 2020, 2025 78


Recall: while in Python

Roll until snake eyes:

Make an initial roll

If that roll isn’t snake eyes,


keep rolling until it is

Add to count each roll

© Alex Ufkes, 2020, 2025 79


Recall: while in Python

Roll until snake eyes:

© Alex Ufkes, 2020, 2025 80


import java.util.Random;
public class Loops
{
public static void main(String[] args)
{
while
for (int i = 0; i <= 5; i++)
System.out.println(rollSnakeEyes());
in Java
}
public static int rollSnakeEyes ()
{
Random rand = new Random();
int a = rand.nextInt(5) + 1;
Make an initial roll
int b = rand.nextInt(5) + 1;
int count = 1; If that roll isn’t snake eyes,
while (a + b != 2) {
keep rolling until it is
a = rand.nextInt(5) + 1;
b = rand.nextInt(5) + 1;
count += 1; Add to count each roll
}
return count; Hate to see duplicate code…
}
} © Alex Ufkes, 2020, 2025
In Java we have an additional loop style not present in Python 81
while VS do-while

while (condition) { Condition checked at the start.


/* statements */ If condition is initially false, body
} never executes.

Condition checked at the end. do {


If condition is initially false, /* statements */
body will still execute once. } while (condition);

The body of a do-while loop will execute at least once.


© Alex Ufkes, 2020, 2025 82
int n = 5; int n = 5;
while (n <= 2) do {
{ System.out.println(n);
System.out.println(n); n = n + 1;
n = n + 1; }
} while (n <= 2);
System.out.println( System.out.println(
“Done loop.”); “Done loop.”);

Output: Output:
Done loop. 5
Done loop.
© Alex Ufkes, 2020, 2025 83
import java.util.Random;
public class Loops
{
public static void main(String[] args) do-while
{
for (int i = 0; i <= 5; i++)
System.out.println(rollSnakeEyes());
in Java
}
public static int rollSnakeEyes () • do-while loop executes at least once.
{ • Condition isn’t checked until the end.
Random rand = new Random();
int a, b, count = 0;
do {
a = rand.nextInt(5) + 1;
b = rand.nextInt(5) + 1;
count += 1;
} while (a + b != 2);
return count;
}
} Ufkes, 2020, 2025
© Alex 84
while VS do-while

public static int rollSnakeEyes () public static int rollSnakeEyes ()


{ {
Random rand = new Random(); Random rand = new Random();
int a = rand.nextInt(5) + 1; int a, b, count = 0;
int b = rand.nextInt(5) + 1; do {
int count = 1; a = rand.nextInt(5) + 1;
while (a + b != 2) { b = rand.nextInt(5) + 1;
a = rand.nextInt(5) + 1; count += 1;
b = rand.nextInt(5) + 1; } while (a + b != 2);
count += 1; return count;
} }
return count;
} Much nicer!
© Alex Ufkes, 2020, 2025 85
© Alex Ufkes, 2020, 2025 86
Strings in Java: Concatenation

public class StringStuff


{
public static void main(String args[])
{
String text1 = "Hello";
String text2 = ", world!";
String text3 = text1 + text2;
System.out.println(text3);
}
} • + is one of the very few
overloaded operators in Java.
• Performs arithmetic addition
but also String concatenation.
© Alex Ufkes, 2020, 2025 87
public class StringStuff
{
public static void main(String args[])
{ Can also include
int age = 87;
other data types:
double height = 5.77;
boolean tf = true;
String msg = "Age: " + age + "\n" +
"Height: " + height + "\n" +
"Alive? " + tf + "\n";
System.out.println(msg);
}
}

© Alex Ufkes, 2020, 2025 88


Strings in Python: Indexing & Slicing

Declare a string named s1: s1 = "foobar"


Extract the first character: c1 = s1[0]
Extract the second character: c2 = s1[1]
Extract substring from index 1 to 4: s2 = s1[1:4]

S1[0:3]=‘foo’ S1[5:5]=‘’

S1 =
© Alex Ufkes, 2020, 2025 89
Strings in Java: Handy Methods

Sadly, it’s not so convenient in Java:

public static void main(String args[])


{
String text = "Hello";
System.out.println(text.charAt(0));
System.out.println(text.charAt(1));
System.out.println(text.charAt(2));
System.out.println(text.charAt(3));
System.out.println(text.charAt(4));
}

© Alex Ufkes, 2020, 2025 90


Strings in Java: Handy Methods

public class StringStuff


{
public static void main(String args[])
{
String text = "Toronto Metro University";
int n = text.length();
System.out.println(n);
}
}

© Alex Ufkes, 2020, 2025 91


Strings in Java: Handy Methods

Extract a substring:

start is inclusive,
end is exclusive.

© Alex Ufkes, 2020, 2025 92


Strings in Java: Handy Methods

public static void main(String args[])


{
System.out.println("String methods:");
String s = "Hello, world!";
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
System.out.println(s.substring(5));
System.out.println(s.substring(3, 8));
String s2 = s.replaceAll("ello", "owdy");
System.out.println(s2);
}

© Alex Ufkes, 2020, 2025 93


Strings in Java: Formatting with printf

Like fstrings in Python:

public static void main(String args[])


{
%s for printing Strings
String prefix = "CPS";
%d for integers
int code = 209;
%f for floating point
double grade = 91.22;
System.out.printf("%s%d grade is %.2f \n",
prefix, code, grade);
}

© Alex Ufkes, 2020, 2025 94


In Summary:

From Python to Java:


• Using VScode, the meaning of main(), “Hello World” in Java
• Java primitives, static typing, consequences of fixed-size integers
• Control structures in Java: if-else, for, while, do-while
• Multiple static methods belonging to a single Java class
• Java strings and some handy String methods

© Alex Ufkes, 2020, 2025 95


© Alex Ufkes, 2020, 2025 96

You might also like