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.

Core Concepts

The core concepts I’ll be covering in this tutorial include:

  1. Data Types
  2. Variable Declaration and Initialization
  3. Type Conversion
  4. Operators and Operations
  5. Flow Control
  6. Loops
  7. Functions
  8. 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.

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 Java List .

Special Values

  • True and False (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
>>> 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
  1. Another difference from variable declaration in Java is that Python variables are initialized without the need to declare them first.
  2. You can reassign a variable to a value of a different type in Python without any errors, which strongly differs from Java.
  3. 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.
  4. 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:

  • x**y returns x to the power of y , and
  • x//y returns the floored, though not necessarily integral, division of x by y .

Bitwise

Most bitwise operators in Java are the same in Python. However, there is no unsigned right-shift ( >>> ).

Boolean

  • && in Java maps to and in Python
  • || in Java maps to or in Python
  • ! in Java maps to not in Python

Relational and Equality

  • instanceof is the only Java operator that’s different in this category. The Python equivalent is is .
  • 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;
>>> 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.

String numWord = 6 + " is six in words";
>>> 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 chained if-then-elseif statements.
  • For loops, the do-while loop doesn’t exist in Python, either.
>>> 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()
  1. Methods in Java need to have the type of their parameters specified just like regular variables. Python, however, doesn’t require this
  2. Methods in Python need to have self as their first parameter, even if there are no other parameters in the method declaration.
  3. Methods must reference other local methods with self in Python. This isn’t required in Java.
  4. 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.
  5. Functions with no return type are void in Java. Python functions have no return type but simply choose whether to include a return statement.
  6. 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. The main 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="")
  1. There’s no straightforward way to prompt for input in Java. You have to use the print method followed by the Scanner.nextLine() method to achieve this.
  2. 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.
  3. Printing to a new line is done using System.out.println() in Java, and print() in Python.
  4. Printing to the same line is done using System.out.print() in Java, and print() in Python and specifying the end parameter as end="" .

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/

--

--

Android Programmer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store