0% found this document useful (0 votes)
10 views8 pages

Python - Java help sheet

Uploaded by

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

Python - Java help sheet

Uploaded by

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

Python & Java code comparisons

Task Python Java


Declaring a There are no constants in Python. The best Use ‘static final’ to declare a constant in Java:
constant you can do is to follow the standard naming static final int NUMBER_OF_PLAYERS = 25;
convention used by many programmers, i.e. to (Note the use of capital letters for the identifier – this is
put your variable names fully in capital not required, but it is standard
letters: programming practice for naming
PI = 3.14 constants.)
This is just a naming convention – Python will
still let you change the value of PI later in
the program.
Add or subtract 1 x = 3 int x = 3;
from a variable x += 1 #x now equals 4 x++; #x now equals 4
x -= 1 #x now equals 3 again x--; #x now equals 3 again

NOTE:
int a = 5;
int b = ++a;
System.out.println(a); //It displays: 6 System.out.println(b);
//It displays: 6

COMPARE WITH:
int a = 5;
int b = a++;
System.out.println(a); //It displays: 6 System.out.println(b);
//It displays: 5
In the first example, variable a is incremented by one and then
its new value is assigned to variable b. In the end, both
variables contain a value of 6. In the second example, the
value 5 of variable a is assigned to variable b, and then
variable a is incremented by one. In the end, variable a
contains a value of 6 but variable b contains a value of 5!

1 of 8
Python & Java code comparisons
Task Python Java
Swap the values of a = 3 int a = 3;
two variables b = 4 int b = 4;
a, b = b, a #a now = 4; b now = 3. int tmp = a;
a = b;
b = tmp;

NOTE: you can swap values without creating another variable by


exploiting some simple Maths:
int a = 3;
int b = 4;
a = a + b;
b = a – b;
a = a – b;
NEAT! But it only works with numbers, not Strings.
Strings x = “Hello” String x = “Hello”; //Double quotes must be used for a String
x = ‘Hello’ char x = ‘a’; //Single quotes are used for chars.
Double quotes or single quotes are fine.
String – finding the x = “Hello world!” String x = “Not confusing at all.”;
length y = len(x) #y now = 12 int y = z.length(); //y now = 21.

NOTE: the double brackets are required, after length. However,


the double brackets are not required when using length to find
the length of an array!!! Not confusing at all.
Replacing x = “Hello Mellow” String a, b; a = "I am newbie in C++. C++ rocks!";
substrings in a y = x.replace(“ello”,””) b = a.replace("C++", "Java");
string print(y) #Output: H Mw
The content of b is now: I am newbie in Java. Java rocks!
Getting part of a x = “HELLO” String x = “HELLO”;
string y = x[:] #This copies the whole of x String y = x.substring(1,3); //y now = “EL”.
y = x[2:] #This copies x from the item at
index position 2 to the end of the Getting part of a string:
list, i.e. LLO. subject.substring(beginIndex [, endIndex] )
y = x[:3] #This copies from start of x up to This method returns a portion of subject. Specifically, it
just before the item at index pos. returns the substring starting from position beginIndex and
3, i.e. HEL. running up to, but not including, position endIndex. The
y = x[2:4] #This copies from item at index argument endIndex is optional. If it is omitted, the substring
pos. 2 up to just before item at index pos. 4, starting from position beginIndex until the end of subject is
i.e. LL. returned.
Convert a string to x = “Hello” String x = “Hello”;
lower or upper case x = x.upper() # x now = HELLO String y = x.toUpperCase();
x = x.lower() # x now = hello String y = x.toLowerCase();

2 of 8
Python & Java code comparisons
Task Python Java
Extracting x = “HELLO!” String x = “HELLO!”;
character at a print(x[4]) #Output: O char y = x.charAt(4); //y now = ‘O’.
certain index
position in a string
Convert String to x = "3" String x = "3";
integer y = int(x) int k = Integer.parseInt(x); //k now equals the integer 3.
Convert a double or x = 5.8 double x = 5.8;
float to an integer y = int(x) # y now 5. Note how it is rounded int y = (int) x; //y now = 5.
down.
Round to nearest round(2.8) #Outputs 3 double a = 5.9;
number round(1.2) #Outputs 1 System.out.println(Math.round(a)); //It displays: 6
System.out.println(Math.round(5.4)); //It displays: 5
BUT …
round(3.5) #Outputs 4. Good … To round to a certain number of decimal places:
round(2.5) #Outputs 2. Aaarrrrgggh! This is double x = Math.round(2.3447 * Math.pow(10,3)) /Math.pow(10,3);
true for all even numbers, e.g. This will make x = 2.345. Can you work out how it does this?
round(4.5) >>> 4.

Floor division and 20 // 6 #Gives the quotient, i.e. 3. int number1 = 20;
modular division 20 % 6 #Gives the remainder, i.e. 2. int number2 = 6;
int quotient = (int)(number1 / number2);
int remainder = number1 % number2;
Find the power of a x = 2**3 # x now equals 2 to the power of int x = 9;
number 3, i.e. 8. double y = Math.pow(x, 0.5); //y = 3.
Generate a random import random int x = 5 + (int)(Math.random() * (100 - 5 + 1)));
number x = random.randint(0,100) #Generate a random This generates a random number between 5 and 100.
number between and
including 0 and 100.

3 of 8
Python & Java code comparisons
Task Python Java
Getting inputs from x = input(“Enter a number:\t”) In Java, data input is accomplished using the class Scanner as
a user Note that any input will be treated by Python shown in the code that follows.
as a string. In the example above, therefore, import java.util.*; //OR: java.util.Scanner;
x will hold a string. If it is meant to be a public class MainClass
number you will need to explicitly convert it: {
x = int(x) static Scanner cin = new Scanner(System.in);
public static void main(String[] args)
{
String var_name_str;
int var_name_int;
//Read a string from the keyboard
var_name_str = cin.nextLine();
//Read an integer from the keyboard
var_name_int = Integer.parseInt(cin.nextLine());
}
}

4 of 8
Python & Java code comparisons
Task Python Java
Array / List – create int myArray[]; //Step 1: Declares an array
(one-dimensional myArray = new int[5]; //Step 2: allocates 5 memory
array) spaces to the array

OR

int[] myArray = new int[5]; //Declares & allocates 5 memory


spaces to array

int myArray[] = new int[5]; //This does the same thing. This
way matches the style of other
languages, like C++, whereas the
way above it is truer to the style
of Java.

OR

int[] myArray = {10,20,30,40,50}; //Declares & allocates 5


memory spaces to array and
fills them with the five
values given.

int myArray[] = {10,20,30,40,50}; // This does the same thing.


This way matches the style
of other languages, like C+
+, whereas the way above it
is truer to the style of
Java.

Array / List – length len(myArray) myArray.length //Note – do not add () brackets.

NOTE: the double brackets are not required after length.


However, the double brackets are
required when using length to find
the length of a string!!! Not
confusing at all.
Array / List – myArray = [1,2,3] int[] myArray = {1,2,3};
looping through for item in myArray: for (int item : myArray)
items print(item) {
(For Each x in y) System.out.println(item);
}

5 of 8
Python & Java code comparisons
Task Python Java
Array / List – myArray = [1,2,3] int[] myArray = {1,2,3};
looping through for arrIndex in range(0,len(myArray)): for (int arrIndex=0; arrIndex < myArray.length; arrIndex++)
items print(myArray[arrIndex]) {
(by index position) System.out.println(myArray[arrIndex]);
}
Array / List – add myArray.append(5) #Adds the integer ‘5’ to the You cannot add or delete items to an array in Java. Once it is
items end of the list created, the size / length is fixed.
Array / List – delete myArray.remove(3) #Removes the first item in You cannot add or delete items to an array in Java. Once it is
items the list that matches the created, the size / length is fixed.
item in the brackets. The
item in the brackets,
therefore, is not an index
position. E.g.
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

myArray.del(3) #Removes item in the list at


the index position given by
the number in the brackets.
>>> a = [3, 2, 2, 1]
>>> del a[1]
>>> a
[3, 2, 1]

myArray.pop(3) # Removes item in the list at


the index position given by
the number in the brackets
and returns it.
>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

6 of 8
Python & Java code comparisons
Task Python Java
Array / List – create #To create a 2D array with 5 rows and 2 int[][] myArray = new int[5][2]; //Declares 2D array – 5 rows,
(multi-dimensional columns, and fill each slot with a 0: 2 columns.
array) int myArray[][] = new int[5][2]; //Ditto, but with C++ style.
rows = 5
cols = 2 int[] myArray[] = new int[5][2]; //Ditto – merging both styles
myArray = [[0]*cols]*rows above for maximum confusion.

[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]] Or

int[][] myArray = { {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };


#To create a 3D array with x = 5, y = 2, z = //Declares and initialises
3, and fill each slot with a 0: 2D array in one line of
code.
x = 5
y = 2 3D array
z = 3 int[][][] myArray = { {{0,1},{0,1}}, {{0,1},{0,1}}, {{0,1},
myArray = [[[0]*z]*y]*x {0,1}}, {{0,1},{0,1}}, {{0,1},{0,1}} };

[[[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, //The code above is fine, but here is an easier way to
0]], [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, visualise what is going on:
0, 0]], [[0, 0, 0], [0, 0, 0]]]
int[][][] myArray = {
{
{0,1},
{0,1}
},
{
{0,1},
{0,1}
},
{
{0,1},
{0,1}
},
{
{0,1},
{0,1}
},
{
{0,1},
{0,1}
}
};

7 of 8
Python & Java code comparisons
Task Python Java
Array / List – #To create a 3D array with x = 5, y = 2, z = int[][][] myArray = { {{0,1},{0,1}}, {{0,1},{0,1}}, {{0,1},
accessing items in 3, and fill each slot with a 0: {0,1}}, {{0,1},{0,1}}, {{0,1},{0,1}} };
multi-dimensional
array x = 5 //To access the item in red, use this code:
y = 2
z = 3 myArray[2][1][0]
myArray = [[[0]*z]*y]*x
[ [[0,1],[0,1]], [[0,1],[0,1]], [[0,1],[0,1]], [[0,1],[0,1]],
#To access the item in red, use this code: [[0,1],[0,1]] ]

myArray[2][1][0]

[[[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0,


0]], [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0,
0, 0]], [[0, 0, 0], [0, 0, 0]]]
Array – make a x = [1, 2, 3, 4, 5] import java.util.Arrays;
copy of whole array y = x[:] #This copies the whole of x int[] myArray = {10,20,30,40,50};
or a slice / chunk of y = x[2:] #This copies x from the item at int[] mySlice = Arrays. copyOfRange(myArray, 2, 4);
the array index position 2 to the end of the
list, i.e. 3, 4, 5. In the above code, mySlice has become a copy of the section of
y = x[:3] #This copies from start of x up to myArray that starts at index position 2 and finishes with the
just before the item at index pos. item that is one before what is at index position 4.
3, i.e. 1, 2, 3. So mySlice = 30, 40.
y = x[2:4] #This copies from item at index
pos. 2 up to just before item at
index pos. 4, i.e. 3, 4.

8 of 8

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy