(Updated January 31, 2024)
Table of Contents
-
Overview
Statements
Data Types
Basic I/O
Conditional Constructs
Iterative Constructs
Files
Arrays
Functions/Methods
Overview
This document is intended to provide a 10,000-foot view of the differences between Python and Java. This is not intended to be an exhaustive comparison of features and/or details. This document should be viewed by the Python programmer looking to jump Java programming and the Java programmer looking to do Python.
There are significant differences between the languages that will not be covered in this document. However, specific details regarding idiomatic constructs will be noted throughout.
As you look through the code examples, you will notice a copious amount of whitespace – especially in the Python code. This is due to the nature of Java being more verbose than Python. The additional whitespace intentionally lines up the constructs in both languages side-by-side.
Statements
In Python, the basic program syntax follows these simple rules:
Python
- Statements do NOT end with semicolons (except statement lists).
- Code blocks that appear after a colon (:) are uniformly indented, not enclosed in curly brackets.
- Conditional tests do not require parentheses.
- Statements must end with semicolons.
- Code blocks that are compound statements must be enclosed in curly brackets.
- Conditional tests MUST be enclosed in parentheses.
Data Types
Python
Data types do not need to be declared. They are generally inferred through their use. However, sometimes you will need to cast in order to mix types. For example, the code below will work fine in Java due to auto-boxing, but fails in Python.
age = 26
s = "You are " + age + " years old."
This works in Java but not Python.
In Python, you cannot directly concatenate strings with integers. You need to do the following:
age = 26
s = "You are " + str(age) + " years old."
The integer must be cast to a string in Python.
Java
While Python allows undeclared variables, data variables in Java must be explicitly typed; that is, you must designate a type for a variable to use. Whole number literals are type int
. Floating point literals are type double
.
i = 10
f = 3.4
s = 'd' # single character string
y = "Tom Thumb" # This is a string
Assigning data types in Python and Java.
int i = 10;
double f = 3.4;
char s = 'd'; // this is a char
String t = "Tom Thumb";
Casting
As we saw above, there is often a need to cast from one type to another. This is true for both languages, even though Java has the auto-boxing feature. The next example shows conversions from various data types through casting.
x = 3.14
y = int(x)
z = float(y)
print (x, y, z)
print ("x is " + str(x))
Examples of basic casting.
double x;
int y;
float z;
x = 3.14;
y = (int)x;
z = (float)y;
System.out.println (x + " " + y + " " + z);
System.out.println("x is " + x);
Basic I/O
I/O in Python can be interactive or with files. The interactive forms are usually with input()
or sys.stdin
(see the EOF loop in iterative constructs below).
With input()
, the value returned is always a string and would need to be cast to another type. In Java, we use something like Scanner
.
This section focuses on user input. The section on Files specifically addresses file-base I/O.
n = input('Enter your name: ')
i = int(input('Enter an integer: '))
f = float(input('Enter a float: '))
Basic text-based user input.
import java.util.Scanner;
// ...
Scanner kb = new Scanner(System.in);
int i;
double f;
String n;
System.out.print("Enter your name: ");
n = kb.nextLine();
System.out.print("Enter an integer: ");
i = kb.nextInt();
System.out.print("Enter a double: ");
f = kb.nextDouble();
Using simple dialog boxes for user input is pretty straightforward. The big difference is the simpledialog
class of tkinter
has multiple forms of ask that allow for specific types.
The showInputDialog()
method of JOptionPane
only returns a String
and requires additional processing.
import tkinter as tk
from tkinter import simpledialog
# ...
window = tk.Tk()
n = simpledialog.askstring('input', 'Enter your name: ',
parent=window)
i = simpledialog.askinteger('Input', 'Enter an integer: ',
parent=window)
f = simpledialog.askfloat('Input', 'Enter a float: ',
parent=window)
Basic GUI dialog box input.
import javax.swing.JOptionPane;
// ...
int i;
double f;
String s, n;
n = JOptionPane.showInputDialog("Enter your name:");
s = JOptionPane.showInputDialog("Enter an integer:");
i = Integer.parseInt(s);
s = JOptionPane.showInputDialog("Enter aa double:");
f = Double.parseDouble(s);
Conditional Constructs
The conditional constructs of if
, else
/if
and else
are a bit different between Python and Java.
See Statements, above, for details on compound statements.
Below are two variations of reading a number and applying simple classification to demonstrate the differences. One uses text only, and the other uses trivial dialog boxes.
x = int(input('Enter an integer: '))
print('The value ',x,' is ', end='')
if x < 0:
print('Negative.')
elif x > 0:
print('Positive.')
else:
print('Zero.')
import java.util.Scanner;
// ...
System.out.print("Enter an integer: ");
x = kb.nextInt();
System.out.print("The value " + x + " is ");
if ( x < 0 )
System.out.println("Negative.");
else if ( x > 0 )
System.out.println("Positive.");
else
System.out.println("Zero.");
import tkinter as tk
from tkinter import simpledialog
from tkinter import messagebox
window = tk.Tk()
x = simpledialog.askinteger('Input', 'Enter an integer: ',
parent=window)
s = 'The number ' + str(x) + ' is '
if x < 0:
s = s + 'Negative.'
elif x > 0:
s = s + 'Positive.'
else:
s = s + 'Zero.'
messagebox.showinfo("Information",s)
import javax.swing.JOptionPane;
// ...
int x;
String s;
s = JOptionPane.showInputDialog("Enter an integer:");
x = Integer.parseInt(s);
s = "The number " + x + " is ";
if ( x < 0 ) {
s = s + "Negative.";
} else if ( x > 0 ) {
s = s + "Positive.";
} else {
s = s + "Zero.";
}
JOptionPane.showMessageDialog(null, s, "Results",
JOptionPane.PLAIN_MESSAGE);
Iterative Constructs
For the iterative constructs, there is no do/while in Python, so it will not be covered here. You can read about do/while in Java.
The use of for
and while
are dispersed throughout this section. This has been broken into range-based, flag, sentinel, and EOF.
Range-Based Loop
The for
loop is designed in Python to be more like the for-each loop of Java. It is designed to work with lists of objects (yes, primitive data types are designated as objects in Python). However, the range()
function can be used to access members of a string.
s = "A bunch of characters!"
for x in range(0, len(s)):
print(s[x])
String s = "A bunch of characters!";
int x;
for (x = 0 ; x < s.length(); x++)
System.out.println(s.charAt(x));
The above example uses the string length to display all of the characters, each on a separate line. The next example uses an iterator. The Java version first converts the String
to an array of char
since iterators cannot be applied directly to strings.
s = "A bunch of characters!"
for c in s:
print(c)
String s = "A bunch of characters!";
for (char c : s.toCharArray())
System.out.println(c);
Our final example prints the strings in reverse on the same line.
s = "A bunch of characters!"
for x in reversed(range(0, len(s))):
print(s[x], end='')
String s = "A bunch of characters!";
int x;
for (x = s.length() - 1; x >= 0; x--)
System.out.print(s.charAt(x));
Flag-Based Loop
Flag-based loops are typically while
loops.
import random
# ...
# random number between 1 and 20
randomNumber = random.randint(1, 20)
print("I'm thinking of a number between 1 and 20.")
found = False;
while not found:
guess = int(input('Guess the value between 1 and 20: '))
if guess == randomNumber:
found = True
else:
print("It's not " + str(guess) + '.')
print('\nYou got it!\n');
Flag-based loops for Python and Java.
import java.util.Scanner;
// ...
Scanner kb = new Scanner(System.in);
int randomNumber, guess;
boolean found;
// random number between 1 and 20
randomNumber = (int)(Math.random() * 20 + 1);
System.out.println("I'm thinking of a number between 1 and 20.");
found = false;
while ( ! found )
{
System.out.print("Guess the value between 1 and 20: ");
guess = kb.nextInt();
if ( guess == randomNumber )
found = true;
else
System.out.println("It's not " + guess + ".\n");
}
System.out.println("\nYou got it!\n");
Sentinel-Based Loop
Like flag-based, sentinel-based loops typically use while
.
sum = 0
count = 0
value = int(input('Enter integers (-1 to end): ')); #initialization
while value != -1: #condition
sum = sum + value;
count=count+1
value = int(input('Enter integers (-1 to end): ')); #update
avg = sum / float(count);
print("The sum is " + str(sum) + ".");
print("The average is " + str(avg) + ".");
Senntinel-based loops for Python and Java.
import java.util.Scanner;
// ...
Scanner kb = new Scanner(System.in);
int sum = 0, count = 0;
int value;
double avg;
System.out.print("Enter integers (-1 to end): ");
value = kb.nextInt(); //initialization
while ( value != -1 ) //condition
{
sum = sum + value;
count++;
System.out.print("Enter integers (-1 to end): ");
value = kb.nextInt(); //update
}
avg = sum / (double)count;
System.out.println("The sum is " + sum + ".");
System.out.println("The average is " + avg + ".");
EOF Loop
The EOF loop is a style that is used for both keyboard and file input. In the examples shown here, the idea is to use CTRL-D as the EOF indicator. The user presses this key sequence to signal the end of the input.
Input is assumed to be line-based and relies on newlines for breaks, which are captured as part of the input by default and removed with strip()
.
In the Python example, the use of end=''
aesthetically keeps the cursor on the same line - the Java print()
equivalent. The use of flush=True
forces the output stream to push the characters of the prompt to the output terminal (try the first one without it to see.)
import sys
# ...
print('Enter a number (CTRL-D to end): ', end='', flush=True)
for line in sys.stdin:
line = line.strip()
print("Input was " + str(len(line)) + " characters long.")
print('Enter a number (CTRL-D to end): ', end='', flush=True)
EOF loops for Python and Java.
import java.util.Scanner;
// ...
String line;
System.out.print("Enter a string (CTRL-D to end): ");
while ( kb.hasNext() )
{
line = kb.nextLine(); // read the line
System.out.println("Input was " + line.length() + " characters long.");
System.out.print("Enter a string (CTRL-D to end): ");
}
Files
There is always a need to read data from files. The examples shown here rely on exceptions thrown when there is an error and the detection of EOF.
import sys
#...
pfile = 'file.txt'
try:
inFile = open(pfile, 'r')
except IOError:
print('Cannot open pfile.')
sys.exit(1)
line = inFile.readline().strip()
inFile.close()
Read a single line from a file.
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
// ...
String line, pfile="file.txt";
Scanner inFile= null;
try {
inFile = new Scanner(new FileReader(pfile));
}
catch (FileNotFoundException e) {
System.out.println("Cannot open file.");
System.exit(1);
}
line = inFile.nextLine();
inFile.close();
import sys
# ...
try:
inFile = open('quotes.txt','r')
except IOError:
print('Cannot open file.')
sys.exit(1)
for line in inFile:
print(line)
inFile.close()
Print lines from input file.
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
// ...
String line;
Scanner inFile=null;
try {
inFile = new Scanner(new FileReader("quotes.txt"));
} catch (FileNotFoundException e) {
System.out.println("Cannot open file.");
System.exit(1);
}
while ( inFile.hasNext() ) {
line = inFile.nextLine();
System.out.println(line);
}
inFile.close();
import sys
# ...
try:
inFile = open('quotes.txt','r')
except IOError:
print('Cannot open input file.')
sys.exit(1)
try:
outFile = open('copy.txt','w')
except IOError:
print('Cannot open output file.')
sys.exit(2)
for line in inFile:
outFile.write(line)
inFile.close()
outFile.close()
Copy contents of one file to another.
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
// ...
String line;
Scanner inFile=null;
PrintWriter outFile=null;
try {
inFile = new Scanner(new FileReader("quotes.txt"));
} catch ( FileNotFoundException e) {
System.out.println("Cannot open input file.");
System.exit(1);
}
try {
outFile = new PrintWriter("copy.txt");
} catch ( FileNotFoundException e) {
System.out.println("Cannot open output file.");
System.exit(2);
}
while ( inFile.hasNext() ) {
line = inFile.nextLine();
outFile.println(line);
}
outFile.close();
inFile.close();
Arrays
Arrays in Python can be done with lists. Alternatively, this can be done with the array
class in NumPy (not shown here). There is no declared size for Python lists. You can declare a variable of list type and use append
to add to it directly.
In Java, arrays are a typical array type found in many other languages. The array must be a declared type with the size determined at compile- or run-time and space allocated before placing values inside.
Python allows you to print the list as a simple variable. Java requires the use of Arrays.toString()
to accomplish the same task.
The examples provided highlight the basics of arrays and their use with loops.
# Using a list as an array.
a = []
# place values 0 - 9 in list.
for x in range(10):
a.append(x)
# print list
print(a)
# print elements of the list
for v in a:
print(v)
############################################
# populate by 3's
a = []
for x in range (1,30,3):
a.append(x)
print(a)
for v in a:
print(v)
############################################
# populate even numbers
a = []
for x in range(50):
a.append(2 * x + 2)
print(a)
for v in a:
print(v)
Various approaches to handling arrays.
// Array of ints.
int x, a[] = new int[10];
// place values 0 - 9 in array.
for ( x = 0 ; x < 10; x++)
a[x] = x;
// print as a list
System.out.println(Arrays.toString(a));
// print elements of the array
for ( x = 0; x < 10; x++ )
System.out.println(a[x]);
// print as for-each loop
for ( int i : a )
System.out.println(i);
//############################################
// populate by 3's
int v = 1;
a = new int[10];
for ( x = 0; x < 10; x++, v+=3)
a[x] = v;
System.out.println(Arrays.toString(a));
for ( x = 0; x < 10; x++ )
System.out.println(a[x]);
//############################################
// populate even numbers
a = new int[50];
for ( x = 0; x < 50; x++ )
a[x] = 2 * x + 2;
System.out.println(Arrays.toString(a));
for ( x = 0; x < 50; x++ )
System.out.println(a[x]);