From Java to Python — Basic Syntax Reference
Introduction
Hello. My name is David, and I’ll be starting a small series over the next few weeks that’s meant to help you learn a new programming language based on one you already know. This means that I’m not teaching you programming, but instead showing you how these languages are related. I’ll only talk about the core concepts, since the advanced concepts of any programming language are beyond the scope of a single article.
In this article, I’ll show you how you can start programming in Python if you’re familiar with Java. I’ll be using Java 8 and Python 3.
Core Concepts
The core concepts I’ll be covering in this tutorial include:
- Major Differences
- Data Types
- Variable Declaration and Initialization
- Type Conversion
- Operators and Operations
- Flow Control
- Loops
- Functions
- Standard I/O
Cheat Sheet
In case you need a single page reference to look at whenever you need to remember something, I’ve included a cheat sheet that I’ve linked here. Let me know what you think in the responses section.
Let’s get started
Major Differences
- Perhaps the biggest difference between Java and Python is that Java is compiled while Python is interpreted.
- In Java, all your methods and data have to be placed in a class. Python, on the other hand, supports top-level functions and variables making it easier to start writing code.
- Python is a whitespace-sensitive language. This means that tabs and spaces are recognized by the language indents are used to define blocks of code. As a result, Python has no curly braces.
- For naming conventions, while they both use PascalCase for class names, Java uses camelCase for variable names and Python uses snake_case. Constants are declared in UPPER_SNAKE_CASE for both.
- Other differences will be covered in the rest of this article.
Data Types
- For numeric types, Python has only one integer type:
int
, with infinite or arbitrary precision. This is in contrast to the four integer types Java has with different sizes. - For floating-point types, Python once again only has one type:
float
, with arbitrary precision. - For character types, there is no data type for single characters, but there are functions to convert single-character strings to their Unicode equivalent
int
and vice-versa. - The
str
class is used for character strings in Python. Single and double quotes can be used for strings. bool
is used to represent Boolean values.- For arrays, which are not primitive types, but are a fundamental data structure, the closest structure to a Java array in Python is a
list
, which behaves like a JavaList
.
Special Values
True
andFalse
(note the uppercase ‘T’ and ‘F’) are the two Boolean values in Python- The
None
type is used to represent null or empty values
Variable Declaration and Initialization
Java:
int x; // 1
x = 10; // 2
//x = 10.0F; // 3 (ERROR)
int y = 20, z = 30; // 5
final int MULTIPLE = 200; // 4
Foo fooBar = new Foo(MULTIPLE); // 1
System.out.println(fooBar.product(3)); // Prints 600
Python:
>>> x = 10 # 1, 2
>>> x = 10.0 # 3
>>> MULTIPLE = 200; # 4
>>> y,z = 20, 30 # 5
>>> foo_bar = Foo(MULTIPLE) # 1
>>> print(foo.product(3)) # Prints 600
- In Java, you have to specify the type of your variable, whether it’s a primitive or an object. In Python, however, the type is inferred and you don’t have to specify its type.
- Another difference from variable declaration in Java is that Python variables are initialized without the need to declare them first.
- You can reassign a variable to a value of a different type in Python without any errors, which strongly differs from Java.
- There are no constants in Python. You simply choose to not reassign the variable. You can also try to exploit immutable data types like
tuple
s. - Multiple assignment in Python is slightly different from Java. You specify the list of variables on one side of the
=
operator and the list of values on the other side, both lists being comma-separated.
Type Conversion
There’s not much to say here. Each primitive type in Python has a respective constructor that can be used to convert one primitive to another where applicable
>>> x = 0 # int
>>> x = str(x) # str - "0"
>>> x = float(x) # float - 0.0
>>> x = bool(x) # bool - False
>>> x = str(x) # str - "False"
>>> # x = int(x) # ERROR
Operators and Operations
Arithmetic and Numbers
Most arithmetic operators are the same in Python as there are in Java. Some differences, however, do exist:
i++
,i--
,++i
, and--i
don’t exist in Python,x**y
returnsx
to the power ofy
, andx//y
returns the floored, though not necessarily integral, division ofx
byy
.
Bitwise
Most bitwise operators in Java are the same in Python. However, there is no unsigned right-shift ( >>>
).
Boolean
&&
in Java maps toand
in Python||
in Java maps toor
in Python!
in Java maps tonot
in Python
Relational and Equality
instanceof
is the only Java operator that’s different in this category. The Python equivalent isis
.- In addition, the
in
operator in Python tests membership of a set.
Ternary
A code snippet like this in Java:
int z = x > 0 ? y : x;
Corresponds to this in Python:
>>> z = y if x > 0 else x
String Concatenation
The +
operator is overloaded for concatenation in both languages. Python, however, needs the operands to be implicitly converted to str
objects, or else it will throw an error.
Java:
String numWord = 6 + " is six in words";
Python:
>>> num_word = 6 + " is six in words" # TypeError!
>>> num_word = str(6) + " is six in words"
Flow Control
- For selection statements, the
switch
statement doesn’t exist in Python. The closest you can get to that is with chainedif-then-elseif
statements. - For loops, the
do-while
loop doesn’t exist in Python, either.
The remaining structures are discussed, assuming the following:
>>> x,y,z,a = 1,2,3,1
If-Then
>>> if y > x:
>>> print("Y is greater")
If-Then-Else
>>> if y < x:
>>> print("X is greater")
>>> else:
>>> print("Y is greater") # This statement gets executed
If-Then-Elseif
>>> if z < y:
>>> print("Y is the greatest")
>>> elif x < z:
>>> print("Z is the greatest") # This statement gets executed
>>> else:
>>> print("X is the greatest")
For Loop
There are no traditional “counter” for loops in Python. You can only iterate over sequences using a for each
loop. There is, however, a data type that represents a range of values over a certain interval, range
, that you can use for a counter loop. To create a range
object, you need a start
, stop
, and step
parameter in its’ constructors. It has two constructors:
>>> # Constructor 1 - range(stop)
>>> list(range(5)) # [0, 1, 2, 3, 4]
>>> # start defaults to 0, stop = 5 (exclusive), step defaults to 1
>>> # Constructor 2 - range(start, stop[, end])
>>> list(range(1,11)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> # start = 1, stop = 11
>>> range(1, 11, 2) # [1, 3, 5, 7, 9]
>>> # start = 1, stop = 11, step = 2
While Loop
>>> while (a <= 10):
>>> print(a)
>>> a+= 1
>>> # prints 1 through 10
Functions
Java
class Program { // 1
public static final String HELLO = "Hello"; // 1, 5
public static void main(String[] args) { // 7
printTopLevel();
Program p = new Program();
p.printLocal("John");
} public static void printTopLevel() { // 1
System.out.println("Top Level Java Function");
} public void printLocal(String name) { // 2
String greeting = greet(name); // 4
System.out.println(greeting);
}
public String greet(String name) { // 6
return HELLO + ", " + name + "!";
}
}
Python
>>> HELLO = "Hello" # 1, 5
>>> def printTopLevel(): # 1
>>> print("Top Level Python Function")
>>> class Program:
>>> def greet(self, name): # 2, 6
>>> return HELLO + ", " + name + "!"
>>> def printLocal(self, name): # 3
>>> greeting = self.greet(name) # 4
>>> print(greeting)
>>> def main(): # 7
>>> printTopLevel()
>>> p = Program()
>>> p.printLocal("John")
>>> if __name__ == "__main__": # 7
>>> main()
- Due to the nature of Java, the closest thing we can have to a top-level function or variable is a
static
member for a particularclass
. In Python, we have the liberty of declaring functions both in and out of classes. Inside a class, we call a function a method. - Methods in Java need to have the type of their parameters specified just like regular variables. Python, however, doesn’t require this
- Methods in Python need to have
self
as their first parameter, even if there are no other parameters in the method declaration. - Methods must reference other local methods with
self
in Python. This isn’t required in Java. - As discussed earlier, there are no constants in Python. Declaring variables at the top of the file with UPPER_SNAKE_CASE is the convention for Python constants.
- Functions with no return type are
void
in Java. Python functions have no return type but simply choose whether to include areturn
statement. - The
main
method in Python is different from Java due to their difference in structure.main
methods in Java are required to execute code while Python code will execute line by line. Themain
method isn’t commonly used in Python and has few use cases.
Standard I/O
There’s a lot to input and output in any language, so I’ll just cover some common snippets for console I/O.
Java
import java.util.Scanner; // 1class JavaIO {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // 1
System.out.print("Your first name: "); // 2
String firstName = scanner.nextLine(); // 2
System.out.print("Your last name: ");
String lastName = scanner.nextLine();
String username = firstName + "_" + lastName;
System.out.printf("Your username is %s\n", username); // 3
System.out.println("Nice to meet you!"); // 4
System.out.print("Good"); // 5
System.out.print("bye!");
scanner.close();
}
}
Python
>>> first_name = input("Your first name: ") # 1, 2
>>> last_name = input("Your last name: ")
>>> username = first_name + "_" + last_name
>>> print("Your username is %s\n"%(username), end="") # 3
>>> print("Nice to meet you!") # 4
>>> print("Good", end="") # 5
>>> print("bye!", end="")
- Standard input in Java requires a
Scanner
object to read from the standardInputStream
,System.in
. Python, however, includes a built-in function to collect input as astr
. - There’s no straightforward way to prompt for input in Java. You have to use the
print
method followed by theScanner.nextLine()
method to achieve this. - String formatting done using the
%
operator.%s
is used for strings in both languages,%d
for decimal integers,%c
for characters, and%g
for floating-point numbers. There’s much more to string formatting, so I’ll simply stop there. - Printing to a new line is done using
System.out.println()
in Java, andprint()
in Python. - Printing to the same line is done using
System.out.print()
in Java, andprint()
in Python and specifying theend
parameter asend=""
.
Conclusion
Moving from Java to Python, the main difficulty you may encounter may be coping with type inference and unspecified types when declaring variables and functions. Other than that, there’s also a lot of advanced concepts that make both languages applicable in different use cases. Thank you for your time.
Further Reading
Python 3 Docs: https://docs.python.org/3/