1_cps209_python_to_java
1_cps209_python_to_java
Computer Science II
Prof. Alex Ufkes
Alex Ufkes
[email protected]
Class times:
Monday 11–12 (DSQ 13)
Thursday: 8-10 (DSQ 03)
Lab times:
Check your schedule
OOP through Java, with lots of fun topics along the way.
Nothing mandatory!
https://www.torontomu.ca/senate/policies/academic-integrity-policy-60/
The more languages you learn, the easier it becomes to learn the next one.
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/
java --version
javac --version
}
} This is a Java
Method body defined by curly braces. method
Yes.
The same public class Hello {
public static void main(String args[])
as this? { System.out.println("Hello, world!"); } }
Primitive? Not objects. They have value, but no associated behavior (methods)
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
Condition
In Python:
No semicolon!
Semicolons go here!
initialization condition
for (int i = 1; i <= 3; i++)
{
Loop
System.out.print(“Hello!”);
body }
Exit loop
Order of execution: False
int n;
for (n = 1; n >= 0; n++) {
System.out.println(n);
}
int n;
for (n = 1; n >= 0; n++) {
System.out.println(n);
}
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
S1[0:3]=‘foo’ S1[5:5]=‘’
S1 =
© Alex Ufkes, 2020, 2025 89
Strings in Java: Handy Methods
Extract a substring:
start is inclusive,
end is exclusive.