02 From Python To Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

From Python to Java

CISC124

1
A Python program starts running from the first line of
the script
 this means that a program can be a single line long

print('Hello, world!')

2
A Java program starts running from a main method
 a main method must belong to a class (or interface)
and it must have a specific form

public class HelloWorld {


public static void main(String... args) {
System.out.println("Hello, world!");
}
}

3
A Java program starts running from a main method
 there are two legal forms of main
 see previous slide for one of the two forms
 the second form is shown below

public class HelloWorld {


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

4
A Java class name starts with an uppercase letter and
contains no spaces
 use upper CamelCase for multiword class names (first
letter of every word of the name is capitalized)
 avoid underscores except in unusual cases

public class HelloWorld {


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

5
Java statements end with a semi-colon
 not precisely true, but the easiest way to convey the
idea at this point

public class HelloWorld {


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

6
Python string literals can be single quoted, double
quoted, or triple quoted

s = 'Hello, world!'
s = "Hej verden!"
s = '''Molo lizwe!'''

7
Java string literals can only be double quoted

String s = "Hello, world!";


s = "Hej verden!";
s = "Molo lizwe!";

8
Python's print function can print more than one value

print(2, 'plus', 3, 'equals', 5)

outputs

2 plus 3 equals 5

9
Java's println method accepts only one argument
 can use string concatenation to compute the string to
be printed

System.out.println(2 + " plus " + 3 + " equals " + 5);

10
Python variables have no type associated with the
variable name

s = 'Hello, world!'
s = 123
s = [1, 2, 3]

11
Java variables have a type
 the type is declared along with the variable name
 the type cannot be changed
 variable can hold values only of the declared type

String s = "Hello, world!";


int t = 123;
List<Integer> aList = new ArrayList<>();
aList.add(1);
aList.add(2);
aList.add(3);

12
Java variable names begin with a lowercase letter and
contain no spaces
 use lower camelCase for multiword variable names
 first letter of every word after the first is capitalized

String s = "Hello, world!";


int t = 123;
List<Integer> aList = new ArrayList<>();
aList.add(1);
aList.add(2);
aList.add(3);

13
A Python comment starts with a # and ends the line that
it is on

# initial investment
p = 100

# annual interest rate in percent


r = 1.25 / 100

final_value = p * (1 + r) ** 10 # after 10 years

14
An inline Java comment starts with // and ends the line
that it is on

// initial investment
double p = 100;

// annual interest rate in percent


double r = 1.25 / 100;

double finalValue =
p * Math.pow(1 + r, 10); // after 10 years

15
A multiline Java comment starts with /* and ends with
*/

/* initial investment and


annual interest rate in percent */
double p = 100;
double r = 1.25 / 100;

double finalValue = /* hey, I can put a comment here */


p * Math.pow(1 + r, 10); // after 10 years

16
There is no exponentiation operator in Java
 use the method Math.pow instead

/* initial investment and


annual interest rate in percent */
double p = 100;
double r = 1.25 / 100;

double finalValue = /* hey, I can put a comment here */


p * Math.pow(1 + r, 10); // after 10 years

17
Some common Python types and literals

tf = True # a boolean or logical


x = 1 # an int
y = 1.0 # a float
s = 'Hello' # a string
t = [] # an empty list of anything

18
And their corresponding Java types and literals
 there are no list literals in Java

boolean tf = true; // a boolean


int x = 1; // an int
double y = 1.0; // a double
String s = "Hello"; // a string
List<Integer> t = new ArrayList<>(); // a list

19
Primitive versus reference types
 in Python, everything is a reference type
 values are actually references to objects
 Java has reference types
 any type that begins with a capital letter is a reference type
 e.g., String, List, ArrayList
 classes are user-defined reference types
 that is why their names should always begin with a capital letter
 Java has primitive types
 any type that begins with a lowercase letter is a primitive
type
 unless you are a jerk and name your classes starting with a
lowercase letter

20
Primitive types
 eight primitive types in Java
 boolean true/false
 byte
 char
 short integer values
 int
 long
 float
floating-point values
 double

21
Reference variables store references to objects
 all variables in Python store references

x = 1 # a reference to an int object


y = 1.0 # a reference to a float object
s = 'Hello' # a reference to a str object

22
Primitive type variables actually store a primitive value

int x = 1; // x stores the value 1


double y = 1.0; // y stores the value 1.0

// s stores a reference to a String object


String s = "Hello";

23
Primitive types
 all of the primitive types occupy a defined fixed
amount of memory
 different primitive types occupy different amounts of
memory

 what is the implication of this?


 each primitive type represents a finite number of values
 e.g., there must be some smallest int value and some greatest int
value

24
int is the usual choice for routine calculations involving
integer values

int lo = Integer.MIN_VALUE; // -2147483648


int hi = Integer.MAX_VALUE; // 2147483647

25
An int literal is any number written without using a
decimal and not ending in L or l (long literals)
 it is a compile-time error if the numeric value is
outside the range that an int can represent

int x = -1;
int y = 99 – 98 + 1 – 0;

// underscores allowed between digits


// (not allowed at beginning or end)
int z = 1_000_000;

// binary, octal, and hexadecimal allowed but not


// relevant for our purposes

26
An arithmetic operation involving two int values always
produces an int value
 division is truncating division (throw away the
fractional part of the quotient)

int x = 1;
int y = 3;
int z = 13;
int result = x + y; // 4
result = x – y; // -2
result = x * y; // 3
result = x / y; // 0
result = z / y; // 4
result = (x + y + z) / 3; // 5

27
An arithmetic calculation involving two int values that
produces a value greater than Integer.MAX_VALUE
wraps around to the other end of the range

int x = Integer.MAX_VALUE;
int y = x + 1; // Integer.MIN_VALUE
y = x + 2; // Integer.MIN_VALUE + 1
y = x + 3; // Integer.MIN_VALUE + 2

28
An arithmetic calculation involving two int values that
produces a value less than Integer.MIN_VALUE wraps
around to the other end of the range

int x = Integer.MIN_VALUE;
int y = x - 1; // Integer.MAX_VALUE
y = x - 2; // Integer.MAX_VALUE - 1
y = x - 3; // Integer.MAX_VALUE - 2

29
Integer overflow
 integer overflow occurs when an arithmetic calculation
with an integer type results in a value that is outside
the range that can be represented by the type
 in Java, wrapping occurs, but different results occur in other
programming languages
 cause of many infamous events:
 Ariane 5 https://en.wikipedia.org/wiki/Cluster_(spacecraft)#Launch_failure
 Deep Impact https://en.wikipedia.org/wiki/Deep_Impact_(spacecraft)#Contact_lost_and_end_of_mission
 Therac 25 https://en.wikipedia.org/wiki/Therac-25
 GPS week rollover https://en.wikipedia.org/wiki/GPS_week_number_rollover
 Year 2000 problem https://en.wikipedia.org/wiki/Year_2000_problem
 Year 2038 problem https://en.wikipedia.org/wiki/Year_2038_problem
30
double is the usual choice for routine calculations
involving floating-point values

double hi = Double.MAX_VALUE; // a very big value


double lo = -hi;

// the smallest positive value


double tiny = Double.MIN_VALUE;

31
A double literal is any number written using a decimal
and not ending in F or f (float literals)
 it is a compile-time error if the numeric value is
outside the range that a double can represent

double x = 1.0;
double y = 2.;

// underscores allowed between digits


// (not allowed at beginning or end)
double z = 1_000_000.99;

// scientific notation
double alsoZ = 1.00000099e6;

32
An arithmetic operation involving two double values
always produces a double value

double x = 1.0;
double y = 3.0;
double z = 13.0;
double result = x + y; // 4.0
result = x – y; // -2.0
result = x * y; // 3.0
result = x / y; // 0.33...
result = z / y; // 4.33...
result = (x + y + z) / 3; // 5.66...

33
Unlike the integer types, floating-point computations do
not wrap when values exceed the range of double
 values saturate at Double.POSITIVE_INFINITY and
Double.NEGATIVE_INFINITY

double x = 1e200 * 1e200; // Double.POSITIVE_INFINITY


double y = -1e200 * 1e200; // Double.NEGATIVE_INFINITY

34
Python has user-defined functions
 procedures that can be called to perform a specific
task, e.g., find the max of two integer values

def max2(a, b):


twice_max = a + b + abs(a – b)
return twice_max / 2

# in another module after importing the module


# containing max2
x = max2(5, -3)

35
𝑎+𝑏
𝑎 2 𝑏
c

𝑏 𝑎+𝑏 𝑎
2

𝑎−𝑏

c
𝑎+𝑏 𝑎−𝑏
+
2 2
36
Java has no functions
 the closest analog is a public static method
 a method is similar to a function but it must be
defined inside of a class (or interface)

public class Lecture2 {

public static int max2(int a, int b) {


int twiceMax = a + b + Math.abs(a – b);
return twiceMax / 2;
}
}

// continued on next slide

37
To call the max2 method, a method in another package
must import the Lecture2 class and then call the max2
method using the syntax
Lecture2.max2(arg1, arg2)

import Lecture2;

public class TestLecture2 {

public static void main(String[] args) {


int x = Lecture2.max2(5, -3);
}
}

38
In Python, indentation is fundamental to the language
 required to denote the body of a function, if
statement, for loop, etc.

def max2(a, b):


twice_max = a + b + abs(a – b)
return twice_max / 2

39
In Java, indentation is used only for readability
 the compiler does not care if your code is indented
 but use the examples in the slides and course notes for
guidance on good Java programming style

// this compiles cleanly, but don't format your code


// like this

public class Lecture2 { public static int


max2(int a, int b) {
int twiceMax = a + b + Math.abs(a – b);
return twiceMax / 2;}
}

40
Java uses braces to delimit the bodies of classes,
methods, if statements, and loops
 the braces are required

public class Lecture2 {

public static int max2(int a, int b) {


int twiceMax = a + b + Math.abs(a – b);
return twiceMax / 2;
} // end of method body

} // end of class body

41

You might also like