Tangible Software Solutions

Java and Python Comparison and Equivalents


Equivalents were produced with the Free Edition of Java to Python Converter.


The closest thing in Python to an abstract method is an empty method:

Java Python
public abstract class AbstractClass
{
    public abstract void abstractMethod();
}
class AbstractClass:
    def abstractMethod(self):
        pass

The closest equivalent to Java anonymous inner classes in Python is to use a class which extends the corresponding interface (which is converted to a Python class).

Java Python
public class TestClass
{
    void testMethod()
    {
        MyInterface localVar = new MyInterface()
        {
            public void method1()
            {
                someCode();
            }
            public void method2(int i, boolean b)
            {
                someCode();
            }
        };
    }
}
class TestClass:
    def testMethod(self):
        localVar = MyInterfaceAnonymousInnerClass(self)

class MyInterfaceAnonymousInnerClass(MyInterface):

    def __init__(self, outerInstance):
        self._outerInstance = outerInstance

    def method1(self):
        someCode()
    def method2(self, i, b):
        someCode()

You can convert Java arrays to Python's 'list'.

Unsized Array

Java Python
int[] myArray; myArray = []

Sized Array

Java Python
int[] myArray = new int[2]; myArray = [0 for _ in range(2)]

Access Array Element

Java Python
x = myArray[0]; x = myArray[0]   # no change

Jagged Array

Java Python
float[][] myArray = new float[][] {{x, y}}; myArray = [[x, y]]

Rectangular Array

Java Python
int[][] myArray = {
    {10, 20, 30 ,40},
    {50, 60, 70, 80, 90, 100},
    {110, 120}
};
myArray = [[10, 20, 30, 40], [50, 60, 70, 80, 90, 100], [110, 120]]

Java requires statements to end with semi-colons and multi-statement blocks to be enclosed in braces, while Python only requires indentation to correspond to the logical block levels and block headers to end in colons. The current instance is only available within instance methods via the first parameter of the method, usually named 'self' by convention (static methods are distinguished by the @staticmethod decorator).

Java Python
class FooClass
{
    void instanceMethod()
    {
        if (fooCondition)
        {
            fooLogicOne();
            fooLogicTwo();
        }
    }
}
class FooClass:
    def instanceMethod(self):
        if fooCondition:
            fooLogicOne()
            fooLogicTwo()
Java Python
void casts()
{
    x = (int)y;
    x = (float)y;
    x = (String)y;
}
def casts(self):
    x = int(y)
    x = float(y)
    x = str(y)

ArrayLists/Lists

Java's java.util.ArrayList collection and Python's 'list' are very close equivalents.

Java Python
void arrayLists()
{
    ArrayList<Integer> myList = new ArrayList<>();
    myList.add(1);
    myList.add(1, 2);
    int i = 1;
    myList.set(0, i);
    i = myList.get(0);
}
def arrayLists(self):
    myList = []
    myList.append(1)
    myList.insert(1, 2)
    i = 1
    myList[0] = i
    i = myList[0]

HashMaps/Dictionaries

Java's java.util.HashMap collection and Python's 'dict' are very close equivalents.

Java Python
void hashMaps()
{
    HashMap<String, Integer> map = new HashMap<>();
    String s = "test";
    map.put(s, 1);
    int i = map.get(s);
    i = map.size();
    boolean b = map.isEmpty();
    map.remove(s);
}
def hashMaps(self):
    map = {}
    s = "test"
    map.update({s: 1})
    i = map[s]
    i = len(map)
    b = not map
    map.pop(s)

Python has a single comment format, starting with the '#' symbol. Multiline comments can also be created using triple quoted multiline strings.

Java Python
// single-line comment

foo(); // end-of-line comment

/* comment
over multiple lines
*/
# single-line comment

foo() # end-of-line comment

# comment
# over multiple lines
#

# using multiline strings to simulate multiline comments:
"""
comment
over multiple lines
"""

Local Variable

Java Python
int myVar = 2; myVar = 2  # Python infers the type

Inferred Types

Inferred typing is available in Java 10, but Python always infers the type:

Java Python
// Java 10:
var myVar = 2;
myVar = 2

Static Field

In Python, static fields are initialized at the class level:

Java Python
class FooClass
{
    public static int staticField = 7;
}
class FooClass:
    staticField = 7

Instance Field

In Python, instance fields are not listed at the class level and are qualified with the instance object, given by the first instance method parameter (usually named 'self' by convention):

Java Python
class FooClass
{
    public int instanceField = 2;
}
class FooClass:
    def __init__(self):
        self.instanceField = 2

Local Constant

Java Python
final int myConst = 2; MY_CONST = 2  # at method level — up to programmers to respect the naming convention and avoid changing it

Class Constant

Java Python
public static final int myConst = 2; MY_CONST = 2  # at class level — up to programmers to respect the naming convention and avoid changing it

Python constructors are named __init__, but a serious shortcoming of Python is the restriction of allowing only one constructor per class.

Java Python
class Foo
{
    public Foo()
    {
    }
}
class Foo:
    def __init__(self):
        pass

Python allows default parameters, but Java does not. Overloaded methods are the only alternative in Java to default parameters.

Java Python
public void defaultParam()
{
    defaultParam(0);
}
public void defaultParam(int param)
{
    ...
}
def defaultParam(self, param=0):
    ...

Enums in Java have equivalents in Python using the 'enum' module:

Java Python
public enum Simple
{
    Foo,
    Bar
}
from enum import Enum

class Simple(Enum):
    FOO = 0
    BAR = 1

Java uses '==' for determining both value equality for primitive types and identity equality for other types. In Python, '==' is only for determining value equality and the 'is' operator is only used for identity equality. In both languages you should not rely on identity equality for strings due to string interning.

Java Python
// value equality with primitives:
int i = 1;
int j = 1;
boolean valuesIdentical = i == j;

// identity equality with class types:
Foo f = new Foo();
Foo g = f;
boolean objectsIdentical = f == g;

// strings:
String s1 = "abc";
String s2 = s1;
valuesIdentical = s1.equals(s2);
// caution: Java string internment often
// makes this true whenever 'equals' is true:
objectsIdentical = s1 == s2;
# value equality:
i = 1
j = 1
valuesIdentical = i == j

# identity equality
f = Foo()
g = f
objectsIdentical = f is g

# strings:
s1 = "abc"
s2 = s1
valuesIdentical = s1 == s2
# caution: Python string internment often
# makes this true whenever '==' is true:
objectsIdentical = s1 is s2

The Python try/except/finally scheme is equivalent to Java's try/catch/finally:

Java Python
void exceptionHandling()
{
    try
    {
    }
    catch (Foo f)
    {
        throw new Foo();
    }
    catch (Bar)
    {
        throw new Bar();
    }
    catch (Exc1 e1 | Exc2 e2)
    {
        throw new FooAck();
    }
    catch (Exc3 | Exc4)
    {
        throw new AckBar();
    }
    finally
    {
    }
}
def exceptionHandling(self):
    try:
        pass
    except Foo as f:
        raise Foo()
    except Bar:
        raise Bar()
    except (Exc1 as e1, Exc2 as e2):
        raise FooAck()
    except (Exc3, Exc4):
        raise AckBar()
    finally:
        pass

The Python 'with' statement is a shortcut for a try/finally block. Java has the 'try with resources' statement, which operates on objects of type java.io.Closeable:

Java Python
try (Foo f = new Foo())
{
    ... some logic
}
with Foo() as f:
    ... some logic
Java Python
if (conditionA)
{
}
else if (conditionB)
{
}
else
{
}
if conditionA:
    pass
elif conditionB:
    pass
else:
    pass

Java allows incrementing and decrementing integers within expressions, while Python doesn't. The following shows how Java to Python Converter handles some cases.

Java Python
public void incrementDecrement()
{
    i = ++j;

    i = j++;

    i = j--;

    i = s + --t;

    i = s + t--;

    i = s + ++t;

    i = s + t++;
}
def incrementDecrement(self):
    j += 1
    i = j

    i = j
    j += 1

    i = j
    j -= 1

    t -= 1
    i = s + t

    i = s + t
    t -= 1

    t += 1
    i = s + t

    i = s + t
    t += 1
Java Python
public class one
{
    protected int baseField = 1;

    public one(int i)
    {
    }

    public void baseMethod()
    {
    }
}

public class two extends one
{
    public two()
    {
        super(0);
    }

    public final void method()
    {
        super.baseField = 2;
        super.baseMethod();
    }
}
class one:

    def __init__(self, i):
        self.baseField = 1

    def baseMethod(self):
        pass

class two(one):
    def __init__(self):
        super().__init__(0)

    def method(self):  # no 'final' equivalent
        self.baseField = 2
        super().baseMethod()

Defining Interfaces

Interfaces in Python are just classes with empty methods:

Java Python
public interface MyInterface
{
    void method();
}
class MyInterface:
    def method(self):
        pass

Implementing Interfaces

Java Python
public class Foo implements MyInterface
{
    public void method()
    {
        ... some code
    }
}
class Foo(MyInterface):
    def method(self):
        ... some code
Java Python
import foo.*;
import ack.Bar;
from foo import *
from ack import Bar

Expression Lambda

Java Python
myVar = (String text) -> text.length(); myVar = lambda text : len(text)

Multi-statement Lambda

Java Python
myVar = (Foo param1, Bar param2) ->
{
    // ...multiple statements
}
No direct Python equivalent
Java Python
x = y && z;
x = y || z;
x = !y;
i = j | k;
i = j & k;
i = j ^ k;
x = y and z
x = y or z
x = not y
i = j | k
i = j & k
i = j ^ k
Java Python
// while loop:
while (while_condition)
{
    foo();

    // break and continue:
    if (b)
        break;
    else
        continue;
}

// do-while loop:
do
{
    foo();
} while (do_condition);

// traditional for loop:
for (int i = 0; i < 10; i++)
{
    foo();
}

// 'for each' loop:
for (Foo f : FooList)
{
}
# while loop:
while while_condition:
    foo()

    # break and continue:
    if b:
        break
    else:
        continue

# do-while loop:
# Python doesn't have a do-while loop, so simulate it:
condition = True
while condition:
    foo()
    condition = do_condition

# traditional for loop:
for i in range(0, 10):
    foo()

# 'for each' loop:
for f in FooList:
    pass
Java Python
void exponentiation()
{
    x = Math.pow(y, z);
}

void integerDivision()
{
    // Java integer division always rounds towards 0:
    int i = -5;
    int j = 2;
    int result = i / j;   // result is -2
}

void modulusOperator()
{
    // Java and Python '%' operators are only equivalent for positive numbers:
    int i = 2;
    int j = -3;
    int result = i % j;   // result is 2
}

void otherMathOperations()
{
    x = Math.abs(y);

    // see the java.lang.Math class for many more functions:
    x = Math.cos(y);
    x = Math.E;
    x = Math.PI;
}
import math

def exponentiation(self):
    x = y ** z

def integerDivision(self):
    i = -5
    j = 2
    result = math.trunc(i / float(j))   # result is -2

    # Python integer division rounds away from 0 when negative:
    result = i / j   # result is -3

def modulusOperator(self):
    i = 2
    j = -3
    result = math.fmod(i, j)   # result is 2

    # Python modulus operator produces a different result:
    result = i % j   # result is -1

def otherMathOperations(self):
    x = abs(y)   # 'abs' is a built-in Python function

    # see the Python 'math' module for many more functions:
    x = math.cos(y)
    x = math.e
    x = math.pi

Python instance methods have a first parameter indicating the instance ('self' is the convention for this parameter and not a keyword), and static methods have the '@staticmethod' decorator.

Java Python
public void instanceMethod()
{
}

public static void staticMethod()
{
}
def instanceMethod(self):
    pass

@staticmethod
def staticMethod():
    pass
Java Python
void method(String... args)
{
    for (String x : args)
    {
        ... logic for each item in args
    }
}
def method(self, *args):
    for x in args:
        ... logic for each item in args

Java static initializer blocks and Python code at the class level serve the same purpose.

Java Python
class Foo
{
    public static int field;

    static
    {
        ... logic to set 'field' value
    }
}
class Foo:
    field = 0

    ... logic to set 'field' value
Java Python
String s = initValue;
int i = s.indexOf(y);
i = s.lastIndexOf(y);
i = s.length();
boolean b = s.contains(y);
s = s.substring(i);
s = s.substring(i, j);
b = s.endsWith(y);
b = s.startsWith(y);
s = s.toLowerCase();
s = s.toUpperCase();
s = s.stripLeading();
s = s.stripTrailing();
s = initValue
i = s.find(y)
i = s.rfind(y)
i = len(s)
b = y in s
s = s[i:]
s = s[i:j]
b = s.endswith(y)
b = s.startswith(y)
s = s.casefold()
s = s.upper()
s = s.lstrip()
s = s.rstrip()

Python 3.10 has 'match' syntax, but if/elif/else is used prior to Python 3.10.

Java Python
switch (pivot)
{
    case 1:
        foo();
        break;
    case 2:
    case 3:
        bar();
        break;
    case 4:
        break;
    default:
        ack();
        break;
}

Python 3.10:

match pivot:
    case 1:
        foo()
    case 2 | 3:
        bar()
    case 4:
        pass
    case other:
        ack()

Prior to Python 3.10:

if pivot == 1:
    foo()
elif pivot == 2 or pivot == 3:
    bar()
elif pivot == 4:
    pass
else:
    ack()
Java Python
result = condition ? truePart : falsePart; result = truePart if condition else falsePart
Java Python
String s = """
multiline
    raw
    string""";
s = """multiline
    raw
    string"""
Java Python
// checking if 'f' is an instance of type 'Foo':
boolean b = f instanceof Foo;

// getting the reliable name of the type 'Foo' (unbroken if the type name changes):
String s = Foo.class.getName();
# checking if 'f' is an instance of type 'Foo':
b = isinstance(f, Foo)

# getting the reliable name of the type 'Foo' (unbroken if the type name changes):
s = Foo.__name__

Copyright © 2004 – 2024 Tangible Software Solutions Inc.