Fork me on GitHub

Language compare

Java

Python

String

Create

class StringCreate {
  public static void main(String[] args) {
    String greeting = "Hello World!";
    System.out.println(greeting);
  }
}
Hello World!
greeting = 'Hello World!'
print(greeting)
Hello World!

Concatenation

class StringConcat {
  public static void main(String[] args) {
    System.out.println("Don't worry," + " be happy");
  }
}
Don't worry, be happy
print("Don't worry," + ' be happy')
Don't worry, be happy

Interpolation

No easy way to do that
first = "Don't worry,"
second = 'be happy'
print('%s %s' % (first, second))
Don't worry, be happy
<span class='small'>[ 3.6 ]</span><div class="highlight"><pre class="highlight python"><code><span class="n">first</span> <span class="o">=</span> <span class="s">"Don't worry,"</span> <span class="n">second</span> <span class="o">=</span> <span class="s">'be happy'</span> <span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">'</span><span class="si">{</span><span class="n">first</span><span class="si">}</span><span class="s"> </span><span class="si">{</span><span class="n">second</span><span class="si">}</span><span class="s">'</span><span class="p">)</span> </code></pre></div>
Don't worry, be happy

Remove part

class StringRemove {
  public static void main(String[] args) {
    String s = "This is not funny! I am not like him!";
    System.out.println(s.replaceAll("not ", ""));
  }
}
This is funny! I am like him!
print('This is not funny! I am not like him!'.replace('not ', ''))
This is funny! I am like him!

Replace

class StringReplace {
  public static void main(String[] args) {
    String s = "You should work";
    System.out.println(s.replaceAll("work", "rest"));
  }
}
You should rest
print('You should work'.replace('work', 'rest'))
You should rest

Split

import java.util.Arrays;

class StringSplit {
  public static void main(String[] args) {
    String s = "I like beer";
    String[] arr = s.split(" ");
    System.out.println(Arrays.toString(arr));
  }
}
[I, like, beer]
print('I like beer'.split())
['I', 'like', 'beer']

Remove leading and trailing whitespace

class StringRemoveWhitespace {
  public static void main(String[] args) {
    System.out.println(" eh? ".trim());
  }
}
eh?
print(' eh? '.strip())
eh?

Compare

class StringCompare {
  public static void main(String[] args) {
    System.out.println("string".equals("string"));
    System.out.println(!"string".equals("string"));
  }
}
true
false
print('string' == 'string')
print('string' != 'string')
True
False

Regex

import java.util.regex.*;

class StringRegex {
  public static void main(String[] args) {
    System.out.println(Pattern.compile("^b").matcher("apple").find());
    System.out.println(Pattern.compile("^a").matcher("apple").find());
  }
}
false
true
import re

print(re.search('^b', 'apple'))
print(re.search('^a', 'apple'))
None
<re.Match object; span=(0, 1), match='a'>

Number

Increment

class NumberIncrement {
  public static void main(String[] args) {
    int i = 9;
    i++;
    System.out.println(i);
  }
}
10
i = 9
i += 1
print(i)
10

Compare

class NumberCompare {
  public static void main(String[] args) {
    System.out.println(1 < 2 && 2 < 3);
    System.out.println(5 == 5);
    System.out.println(5 != 5);
  }
}
true
true
false
print(1 < 2 < 3)
print(5 == 5)
print(5 != 5)
True
True
False

Random

import java.util.concurrent.ThreadLocalRandom;

class NumberRandom {
  public static void main(String[] args) {
    System.out.println(ThreadLocalRandom.current().nextInt(1, 2 + 1));
  }
}
1
import random

print(random.randint(1, 2))
2

Float

class NumberFloat {
  public static void main(String[] args) {
    System.out.println(9 / 2);
    System.out.println(9 / 2.0);
    System.out.println(Math.floor(9 / 2.0));
    System.out.println(Math.round(9 / 2.0));
  }
}
4
4.5
4.0
5
import math

print(9 // 2)
print(9 / 2)
print(math.floor(9 / 2))
print(round(9 / 2))  # rounds half to even
4
4.5
4
4

Type

Get type of object

class TypeGetType {
  public static void main(String[] args) {
    System.out.println("hi".getClass());
    System.out.println(new Integer(1).getClass());
  }
}
/Users/evmorov/projects/lang-compare/code/java/TypeGetType.java:4: warning: [removal] Integer(int) in Integer has been deprecated and marked for removal
    System.out.println(new Integer(1).getClass());
                       ^
1 warning
print(type('hi'))
print(type(1))
<class 'str'>
<class 'int'>

Int to Float

class TypeIntToFloat {
  public static void main(String[] args) {
    System.out.println((float) 10);
  }
}
10.0
print(float(10))
10.0

Int to String

class TypeIntToString {
  public static void main(String[] args) {
    System.out.println(Integer.toString(10));
  }
}
10
print(str(10))
10

String to Int

class TypeStringToInt {
  public static void main(String[] args) {
    System.out.println(Integer.parseInt("10"));
  }
}
10
print(int('5'))
5

String?

class TypeIsString {
  public static void main(String[] args) {
    System.out.println("10" instanceof String);
  }
}
true
print(isinstance('10', str))
True

Null/True/False?

import java.util.*;

class TypeNullTrueFalse {
  public static void main(String[] args) {
    List<String> emptyArray = new ArrayList<String>();
    System.out.println(emptyArray.isEmpty());

    String emptyString = "";
    System.out.println(emptyString.isEmpty());

    String nullVar = null;
    System.out.println(nullVar == null);
  }
}
true
true
true
def check(label, fn, values):
    print(label)
    for value in values:
        try:
            result = 'true' if fn(value) else 'false'
        except TypeError as e:
            result = 'error: %s' % e
        print("  %-9r - %s" % (value, result))
    print()

values = ['string', '', [1, 2, 3], [], 5, 0, True, False, None]

check('if value:', lambda v: v, values)
check('if value is None:', lambda v: v is None, values)
check('if len(value):', lambda v: len(v), values)
if value:
  'string'  - true
  ''        - false
  [1, 2, 3] - true
  []        - false
  5         - true
  0         - false
  True      - true
  False     - false
  None      - false

if value is None:
  'string'  - false
  ''        - false
  [1, 2, 3] - false
  []        - false
  5         - false
  0         - false
  True      - false
  False     - false
  None      - true

if len(value):
  'string'  - true
  ''        - false
  [1, 2, 3] - true
  []        - false
  5         - error: object of type 'int' has no len()
  0         - error: object of type 'int' has no len()
  True      - error: object of type 'bool' has no len()
  False     - error: object of type 'bool' has no len()
  None      - error: object of type 'NoneType' has no len()

Array

Create populated

import java.util.*;

class ArrayCreatePopulated {
  public static void main(String[] args) {
    List<String> arr = Arrays.asList("first", "second");
    System.out.println(arr);
  }
}
[first, second]
arr = ['first', 'second']
print(arr)
['first', 'second']

Add

import java.util.*;

class ArrayAdd {
  public static void main(String[] args) {
    List<String> arr = new ArrayList<String>();
    arr.add("first");
    arr.add("second");
    System.out.println(arr);
  }
}
[first, second]
arr = []
arr.append('first')
arr.append('second')
print(arr)
['first', 'second']

With different types

import java.util.*;

class ArrayDifferentTypes {
  public static void main(String[] args) {
    System.out.println(Arrays.asList("first", 1));
  }
}
[first, 1]
print(['first', 1])
['first', 1]

Include?

import java.util.*;

class ArrayIsInclude {
  public static void main(String[] args) {
    System.out.println(Arrays.asList(1, 2).contains(1));
  }
}
true
print(1 in [1, 2])
True

Iterate

import java.util.*;

class ArrayIterate {
  public static void main(String[] args) {
    for (int num : Arrays.asList(1, 2)) {
      System.out.println(num);
    }
  }
}
1
2
for num in [1, 2]:
  print(num)
1
2

Iterate with index

import java.util.*;

class ArrayIterateWithIndex {
  public static void main(String[] args) {
    List<String> arr = Arrays.asList("one", "two");
    for (int i = 0; i < arr.size(); i++) {
      System.out.println(arr.get(i));
      System.out.println(i);
    }
  }
}
one
0
two
1
for i, num in enumerate(['one', 'two']):
  print(num)
  print(i)
one
0
two
1

Get first, last element

import java.util.*;

class ArrayGetFirstAndLast {
  public static void main(String[] args) {
    List<String> arr = Arrays.asList("one", "two");
    System.out.println(arr.get(0));
    System.out.println(arr.get(arr.size() - 1));
  }
}
one
two
arr = ['one', 'two']
print(arr[0])
print(arr[-1])
one
two

Find first

import java.util.*;

class ArrayFind {
  public static void main(String[] args) {
    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
    int first = 0;
    for (int n : arr) {
      if (n % 2 == 0) {
        first = n;
        break;
      }
    }
    System.out.println(first);
  }
}
10
arr = [1, 5, 10, 20]
print(next(i for i in arr if i % 2 == 0))
10

Select (find all)

import java.util.*;

class ArraySelect {
  public static void main(String[] args) {
    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
    List<Integer> all = new ArrayList<Integer>();
    for (int n : arr)
      if (n % 2 == 0)
        all.add(n);
    System.out.println(all);
  }
}
[10, 20]
arr = [1, 5, 10, 20]
print([i for i in arr if i % 2 == 0])
[10, 20]

Map (change all)

import java.util.*;

class ArrayMap {
  public static void main(String[] args) {
    List<Integer> arr = Arrays.asList(1, 5, 10, 20);
    List<Integer> mapped = new ArrayList<Integer>();
    for (int n : arr)
      mapped.add(n * 2);
    System.out.println(mapped);
  }
}
[2, 10, 20, 40]
arr = [1, 5, 10, 20]
print([num * 2 for num in arr])
[2, 10, 20, 40]

Concatenation

import java.util.*;

class ArrayConcat {
  public static void main(String[] args) {
    List<Integer> arr1 = Arrays.asList(1, 2);
    List<Integer> arr2 = Arrays.asList(3, 4);
    List<Integer> concated = new ArrayList<Integer>(arr1);
    concated.addAll(arr2);
    System.out.println(concated);
  }
}
[1, 2, 3, 4]
print([1, 2] + [3, 4])
[1, 2, 3, 4]

Sort

import java.util.*;

class ArraySort {
  public static void main(String[] args) {
    List<Integer> arr = Arrays.asList(4, 2, 3, 1);
    Collections.sort(arr);
    System.out.println(arr);
  }
}
[1, 2, 3, 4]
print(sorted([4, 2, 3, 1]))
[1, 2, 3, 4]

Multidimensional

import java.util.*;

class ArrayMulti {
  public static void main(String[] args) {
    List<List<String>> arr = new ArrayList<List<String>>();
    arr.add(Arrays.asList("first", "second"));
    arr.add(Arrays.asList("third", "forth"));
    System.out.println(arr.get(1).get(1));
  }
}
forth
multi = [['first', 'second'], ['third', 'forth']]
print(multi[1][1])
forth

Size

import java.util.*;

class ArraySize {
  public static void main(String[] args) {
    List<Integer> arr = Arrays.asList(1, 2, 3);
    System.out.println(arr.size());
  }
}
3
print(len([1, 2, 3]))
3

Count

import java.util.*;

class ArrayCount {
  public static void main(String[] args) {
    List<Integer> arr = Arrays.asList(1, 11, 111);
    int count = 0;
    for (int n : arr)
      if (n > 10)
        count++;
    System.out.println(count);
  }
}
2
arr = [1, 11, 111]
print(sum(1 for i in arr if i > 10))
2

Reduce

import java.util.*;

class ArrayReduce {
  public static void main(String[] args) {
    int sum = 0;
    for (int n : Arrays.asList(1, 2, 3))
      sum += n;
    System.out.println(sum);
  }
}
6
import functools, operator

print(functools.reduce(operator.add, [1, 2, 3]))
print(sum([1, 2, 3]))  # a more Pythonic example
6
6

Index of element

import java.util.*;

class ArrayIndexOfElement {
  public static void main(String[] args) {
    List<String> arr = Arrays.asList("a", "b", "c");
    System.out.println(arr.indexOf("c"));
  }
}
2
print(['a', 'b', 'c'].index('c'))
2

Delete element

import java.util.*;

class ArrayDeleteElement {
  public static void main(String[] args) {
    List<String> arr = new LinkedList<String>(Arrays.asList("a", "b", "c"));
    Iterator<String> iter = arr.iterator();
    while(iter.hasNext()) {
      if(iter.next().equalsIgnoreCase("b"))
        iter.remove();
    }
    System.out.println(arr);
  }
}
[a, c]
arr = ['a', 'b', 'c']
arr.remove('b')
print(arr)
['a', 'c']

Unique

import java.util.*;

class ArrayUnique {
  public static void main(String[] args) {
    List<String> arr = Arrays.asList("a", "b", "a");
    Set<String> unique = new LinkedHashSet<>(arr);
    System.out.println(unique);
  }
}
[a, b]
print(set(['a', 'b', 'a']))
{'a', 'b'}

Hash (map)

Create populated

import java.util.*;

class HashCreatePopulated {
  public static void main(String[] args) {
    Map<String, String> options = new HashMap<String, String>() {{
      put("fontSize", "10");
      put("fontFamily", "Arial");
    }};
    System.out.println(options);
  }
}
{fontFamily=Arial, fontSize=10}
options = {'font_size': 10, 'font_family': 'Arial'}
print(options)
{'font_size': 10, 'font_family': 'Arial'}

Add

import java.util.*;

class HashAdd {
  public static void main(String[] args) {
    Map<String, String> options = new HashMap<String, String>();
    options.put("fontSize", "10");
    options.put("fontFamily", "Arial");
    System.out.println(options);
  }
}
{fontFamily=Arial, fontSize=10}
options = {}
options['font_size'] = 10
options['font_family'] = 'Arial'
print(options)
{'font_size': 10, 'font_family': 'Arial'}

Iterate

import java.util.*;

class HashIterate {
  public static void main(String[] args) {
    Map<String, String> options = new HashMap<String, String>() {{
      put("fontSize", "10");
      put("fontFamily", "Arial");
    }};
    for (Map.Entry<String, String> entry : options.entrySet()) {
      System.out.println(entry.getKey());
      System.out.println(entry.getValue());
    }
  }
}
fontFamily
Arial
fontSize
10
for key, value in {'font_size': 10, 'font_family': 'Arial'}.items():
  print(key, value)
font_size 10
font_family Arial

Include?

import java.util.*;

class HashIsInclude {
  public static void main(String[] args) {
    Map<String, String> options = new HashMap<String, String>() {{
      put("fontSize", "10");
      put("fontFamily", "Arial");
    }};
    System.out.println(options.containsKey("fontSize"));
  }
}
true
options = {'font_size': 10, 'font_family': 'Arial'}
print('font_size' in options)
True

Get value

import java.util.*;

class HashGetValue {
  public static void main(String[] args) {
    Map<String, String> options = new HashMap<String, String>() {{
      put("fontSize", "10");
      put("fontFamily", "Arial");
    }};
    System.out.println(options.get("fonSize"));
  }
}
null
options = {'font_size': 10, 'font_family': 'Arial'}
print(options['font_size'])
10

Size

import java.util.*;

class HashSize {
  public static void main(String[] args) {
    Map<String, String> options = new HashMap<String, String>() {{
      put("fontSize", "10");
      put("fontFamily", "Arial");
    }};
    System.out.println(options.size());
  }
}
2
options = {'font_size': 10, 'font_family': 'Arial'}
print(len(options))
2

Other structure

Boolean

class OtherStructureBoolean {
  public static void main(String[] args) {
    boolean tryIt = true;
    if (tryIt)
      System.out.println("Garlic gum is not funny");
  }
}
Garlic gum is not funny
try_it = True
if try_it:
    print('Garlic gum is not funny')
Garlic gum is not funny

Constant

class OtherStructureConstant {
  public static void main(String[] args) {
    final int COST = 100;
    COST = 50;
    System.out.println(COST);
  }
}
/Users/evmorov/projects/lang-compare/code/java/OtherStructureConstant.java:4: error: cannot assign a value to final variable COST
    COST = 50;
    ^
1 error
COST = 100
COST = 50
print(COST)
50

Constant list

enum Color {
  RED("#FF0000"),
  GREEN("#00FF00");

  private String color;

  private Color(String color) {
    this.color = color;
  }

  public String toString() {
    return color;
  }
}

class OtherStructureConstantList {
  public static void main(String[] args) {
    System.out.println(Color.GREEN);
  }
}
#00FF00
class Colors:
    RED = '#FF0000'
    GREEN = '#00FF00'

print(Colors.GREEN)
#00FF00

Struct

No easy way to do that
import collections

class Customer(collections.namedtuple('Customer', 'name address')):
    def greeting(self):
        return "Hello %s!" % self.name

print(Customer('Dave', '123 Main').greeting())
Hello Dave!

Conditional

If

class ConditionalIf {
  public static void main(String[] args) {
    if (true)
      System.out.println("Hello");
  }
}
Hello
if True:
    print('Hello')
Hello

Unless

class ConditionalUnless {
  public static void main(String[] args) {
    boolean angry = false;
    if (!angry)
      System.out.println("smile!");
  }
}
smile!
angry = False
if not angry:
    print('smile!')
smile!

If/else

class ConditionalIfElse {
  public static void main(String[] args) {
    if (true)
      System.out.println("work");
    else
      System.out.println("sleep");
  }
}
work
if True:
  print('work')
else:
  print('sleep')
work

And/Or

class ConditionalAndOr {
  public static void main(String[] args) {
    if (true && false)
      System.out.println("no");
    if (true || false)
      System.out.println("yes");
  }
}
yes
if True and False:
    print('no')
if True or False:
    print('yes')
yes

Switch

class ConditionalSwitch {
  public static void main(String[] args) {
    String s = "Hello!";
    switch (s) {
      case "Bye!":
        System.out.println("wrong");
        break;
      case "Hello!":
        System.out.println("right");
        break;
      default: break;
    }
  }
}
right
foo = 'Hello!'
if foo in range(1, 6):
    print("It's between 1 and 5")
elif foo in (10, 20):
    print('10 or 20')
elif foo == 'And':
    print('case in one line')
elif isinstance(foo, str):
    print("You passed a string %r" % foo)
else:
    print("You gave me %r" % foo)
You passed a string 'Hello!'

Switch as else if

No easy way to do that
score = 76
grades = [
    (60, 'F'),
    (70, 'D'),
    (80, 'C'),
    (90, 'B'),
]
print(next((g for x, g in grades if score < x), 'A'))
C

Ternary

class ConditionalTernary {
  public static void main(String[] args) {
    String s = false ? "no" : "yes";
    System.out.println(s);
  }
}
yes
print('no' if False else 'yes')
yes

If assign

No easy way to do that
result = 'a' if True else 'b'
print(result)
a

Loop

For

class LoopFor {
  public static void main(String[] args) {
    for (int i = 1; i <= 3; i++)
      System.out.println(i + ". Hi");
  }
}
1. Hi
2. Hi
3. Hi
for i in range(1, 4):
    print('%d. Hi' % i)
1. Hi
2. Hi
3. Hi

For with a step

class LoopForWithStep {
  public static void main(String[] args) {
    for (int i = 0; i <= 4; i += 2)
      System.out.println(i);
  }
}
0
2
4
for i in range(0, 5, 2):
    print(i)
0
2
4

Times

class LoopTimes {
  public static void main(String[] args) {
    for (int i = 0; i < 3; i++)
      System.out.println("Hi");
  }
}
Hi
Hi
Hi
for i in range(3):
  print('Hi')
Hi
Hi
Hi

While

class LoopWhile {
  public static void main(String[] args) {
    int i = 0;
    while (i < 3)
      i++;
    System.out.println(i);
  }
}
3
i = 0
while i < 3:
  i += 1
print(i)
3

Until

class LoopUntil {
  public static void main(String[] args) {
    int i = 0;
    while (i != 3)
      i++;
    System.out.println(i);
  }
}
3
i = 0
while i != 3:
    i += 1
print(i)
3

Return array

No easy way to do that
greetings = ["%d. Hello!" % time for time in range(1, 4)]
print(greetings)
['1. Hello!', '2. Hello!', '3. Hello!']

Break

class LoopBreak {
  public static void main(String[] args) {
    for (int i = 0; i < 3; i++) {
      System.out.println((i + 1) + ". Hi");
      if (i == 1)
        break;
    }
  }
}
1. Hi
2. Hi
for time in range(1, 4):
  print("%d. Hi" % time)
  if time == 2:
    break
1. Hi
2. Hi

Next/Continue

class LoopNext {
  public static void main(String[] args) {
    for (int i = 0; i < 3; i++) {
      if (i == 1)
        continue;
      System.out.println((i + 1) + ". Hi");
    }
  }
}
1. Hi
3. Hi
for time in range(1, 4):
  if time == 2:
      continue
  print("%d. Hi" % time)
1. Hi
3. Hi

Math

Max/Min

import java.util.*;

class MathMaxMin {
  public static void main(String[] args) {
    List<Integer> arr = Arrays.asList(1, 2, 3);
    System.out.println(Collections.min(arr));
    System.out.println(Collections.max(arr));
  }
}
1
3
arr = [1, 2, 3]
print(min(arr))
print(max(arr))
1
3

Sqrt

class MathSqrt {
  public static void main(String[] args) {
    System.out.println(Math.sqrt(9));
  }
}
3.0
import math

print(math.sqrt(9))
3.0

Error handling

Try/catch/finally

class ErrorTryCatch {
  public static void main(String[] args) {
    try {
      int i = 1 / 0;
    } catch (Exception e) {
      System.out.println("Can't divide");
    } finally {
      System.out.println("But that's ok");
    }
  }
}
Can't divide
But that's ok
try:
  1 / 0
except:
  print("Can't divide")
finally:
  print("But that's ok")
Can't divide
But that's ok

With a message

class ErrorWithAMessage {
  public static void main(String[] args) {
    try {
      int i = 1 / 0;
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}
/ by zero
try:
  1 / 0
except Exception as e:
  print(e)
division by zero

Method

No easy way to do that
def divide(num1, num2):
  try:
    num1 / num2
  except Exception as e:
    print(e)
divide(1, 0)
division by zero

Throw exception

class ErrorThrow {
  public static void main(String[] args) {
    try {
      throw new Exception("An error!");
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}
An error!
try:
  raise Exception('An error!')
except Exception as e:
  print(e)
An error!

File

Read

import java.io.*;

class FileRead {
  public static void main(String[] args) throws IOException {
    String filePath = System.getProperty("user.dir") + "/code/file.txt";
    String content;
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
      StringBuilder sb = new StringBuilder();
      String line = br.readLine();
      while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
      }
      content = sb.toString();
    }
    System.out.println(content);
  }
}
Hello
World

import os

with open(os.path.join(os.getcwd(), 'code', 'file.txt')) as f:
    print(f.read())
Hello
World

Write

import java.io.*;

class FileWrite {
  public static void main(String[] args) throws IOException {
    String filePath = System.getProperty("user.dir") + "/code/output.txt";
    try (Writer writer = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(filePath), "utf-8"))) {
      writer.write("Some glorious content");
    }
  }
}

import pathlib

with (pathlib.Path(__file__).parent / 'output.txt').open('w') as f:
    f.write('Some glorious content')

Get working dir path

class FileGetWorkingDir {
  public static void main(String[] args) {
    System.out.println(System.getProperty("user.dir"));
  }
}
/Users/evmorov/projects/lang-compare
import os

print(os.getcwd())
/Users/evmorov/projects/lang-compare

File path

import java.net.*;

class FilePath {
  public static void main(String[] args) {
    URL location = FilePath.class.getProtectionDomain().getCodeSource().getLocation();
    System.out.println(location.getFile() + "FilePath.class");
  }
}
/Users/evmorov/projects/lang-compare/code/java/FilePath.class
print(__file__)
/Users/evmorov/projects/lang-compare/code/python/file_path.py

Dir path

import java.net.*;

class FileDirPath {
  public static void main(String[] args) {
    URL location = FileDirPath.class.getProtectionDomain().getCodeSource().getLocation();
    System.out.println(location.getFile());
  }
}
/Users/evmorov/projects/lang-compare/code/java/
import pathlib

print(pathlib.Path(__file__).parent)
/Users/evmorov/projects/lang-compare/code/python

Parent dir path

import java.net.*;
import java.io.*;

class FileParentDirPath {
  public static void main(String[] args) {
    URL location = FileParentDirPath.class.getProtectionDomain().getCodeSource().getLocation();
    String parentPath = new File(location.getFile()).getParent();
    System.out.println(parentPath);
  }
}
/Users/evmorov/projects/lang-compare/code
import pathlib

print(pathlib.Path(__file__).parents[1])
/Users/evmorov/projects/lang-compare/code

Sister dir path

import java.net.*;
import java.io.*;

class FileSisterDirPath {
  public static void main(String[] args) throws IOException {
    URL location = FileSisterDirPath.class.getProtectionDomain().getCodeSource().getLocation();
    String parentPath = new File(location.getFile() + ".." + "/java").getCanonicalPath();
    System.out.println(parentPath);
  }
}
/Users/evmorov/projects/lang-compare/code/java
import pathlib

print(pathlib.Path(__file__).parents[1] / 'ruby')
/Users/evmorov/projects/lang-compare/code/ruby

Method

Declare

class MethodDeclare {
  public static void main(String[] args) {
    new MethodDeclare().hey();
  }

  public void hey() {
    System.out.println("How are you?");
  }
}
How are you?
def hey():
  print('How are you?')
hey()
How are you?

Multiple arguments

import java.util.*;

class MethodMultiArg {
  public static void main(String[] args) {
    new MethodMultiArg().sweets(true, "snickers", "twix", "bounty");
  }

  public void sweets(boolean buy, String... brands) {
    if (buy)
      System.out.println(Arrays.toString(brands));
  }
}
[snickers, twix, bounty]
def sweets(buy, *brands):
  if buy:
      print(brands)
sweets(True, 'snickers', 'twix', 'bounty')
('snickers', 'twix', 'bounty')

Default value for argument

No easy way to do that
def send(abroad=False):
  print('Send abroad' if abroad else 'Send locally')
send()
send(True)
Send locally
Send abroad

Return

class MethodReturn {
  public static void main(String[] args) {
    MethodReturn obj = new MethodReturn();
    System.out.println(obj.divide(0, 10));
    System.out.println(obj.divide(10, 5));
  }

  public int divide(int a, int b) {
    if (a == 0)
      return 0;
    return a / b;
  }
}
0
2
def multiply(a, b):
    return a * b

def divide(a, b):
    return 0 if a == 0 else a / b

def default_value():
    pass

print(multiply(2, 3))
print(divide(0, 10))
print(default_value())
6
0
None

Closure

No easy way to do that
square = lambda x: x * x
print(list(map(square, [2, 3])))

greeting = lambda: print('Hello World!')
greeting()
[4, 9]
Hello World!

Block passing

No easy way to do that
def select(arr):
    yield from arr

def select_filter(arr, filter):
    for a in arr:
        if filter(a):
            yield a

print([x for x in select([1, 5, 10]) if x < 6])
print(list(select_filter([1, 5, 10], lambda x: x < 6)))
[1, 5]
[1, 5]

Block binding

No easy way to do that
class Action:
  name = 'Ann'

  @staticmethod
  def say(sentence):
    print(sentence())


class Person:
  def __init__(self, name):
    self.name = name

  def greet(self):
    Action.say(lambda: "My name is %s!" % self.name)


Person('Alex').greet()
My name is Alex!

Initialize in runtime

No easy way to do that
class ProccessElements:
  def __init__(self):
    def element(el_name):
      def render(content):
        return '<{0}>{1}</{0}>'.format(el_name, content)
      return render

    for el_name in self.elements:
      setattr(self, el_name, element(el_name))


class HtmlELements(ProccessElements):
  elements = ('div', 'span')

print(HtmlELements().div('hello'))
<div>hello</div>

Alias

No easy way to do that
class Greetings:
  def hey(self):
    print('How are you?')
  hi = hey

Greetings().hi()
How are you?

Class

Declare

class Animal {
  public void walk() {
    System.out.println("I'm walking");
  }
}

class ClassDeclare {
  public static void main(String[] args) {
    new Animal().walk();
  }
}
I'm walking
class Animal:
  def walk(self):
    print("I'm walking")

Animal().walk()
I'm walking

Constructor

class Animal {
  private String name;

  public Animal(String name) {
    this.name = name;
  }

  public void walk() {
    System.out.println("My name is " + this.name + " and I'm walking");
  }
}

class ClassConstructor {
  public static void main(String[] args) {
    new Animal("Kelya").walk();
  }
}
My name is Kelya and I'm walking
class Animal:
  def __init__(self, name):
    self.name = name

  def walk(self):
    print("My name is %s and I'm walking" % self.name)

Animal('Kelya').walk()
My name is Kelya and I'm walking

Method call

class Animal {
  public void walk() {
    bark();
    guard();
    System.out.println("I'm walking");
  }

  public void bark() {
    System.out.println("Wuf!");
  }

  private void guard() {
    System.out.println("WUUUF!");
  }
}

class ClassMethodCall {
  public static void main(String[] args) {
    new Animal().walk();
  }
}
Wuf!
WUUUF!
I'm walking
class Animal:
  def walk(self):
    self.bark()
    self._guard()
    print("I'm walking")

  def bark(self):
    print('Wuf!')

  # Private by convention
  def _guard(self):
    print('WUUUF!')

Animal().walk()
Wuf!
WUUUF!
I'm walking

Class method

class Animal {
  public static void feed() {
    System.out.println("Om nom nom");
  }
}

class ClassClassMethod {
  public static void main(String[] args) {
    Animal.feed();
  }
}
Om nom nom
class Animal:
  @classmethod
  def feed(cls):
    print('Om nom nom')

Animal.feed()
Om nom nom

Private method

class Animal {
  public void eat(String food) {
    if (isMeat(food))
      System.out.println("Om nom nom");
  }

  private boolean isMeat(String food) {
    return food.equals("meat");
  }
}

class ClassPrivateMethod {
  public static void main(String[] args) {
    new Animal().eat("meat");
  }
}
Om nom nom
class Animal:
  def eat(self, food):
    if self._is_meat(food):
      print('Om nom nom')

  def _is_meat(self, food):
    return food == 'meat'

Animal().eat('meat')
Om nom nom

Private method, access instance variable

class Animal {
  private String name;

  public Animal(String name) {
    this.name = name;
    greet();
  }

  private void greet() {
    System.out.println("Hello! My name is " + this.name);
  }
}

class ClassPrivateMethodAccessInstance {
  public static void main(String[] args) {
    new Animal("Kelya");
  }
}
Hello! My name is Kelya
class Animal:
  def __init__(self, name):
    self.name = name
    self._greet()

  def _greet(self):
    print("Hello! My name is %s" % self.name)

Animal('Kelya')
Hello! My name is Kelya

Field

class Animal {
  private String toy;

  public void take(String toy) {
    this.toy = toy;
  }

  public void play() {
    System.out.println("I'm playing with " + this.toy);
  }
}

class ClassField {
  public static void main(String[] args) {
    Animal animal = new Animal();
    animal.take("a ball");
    animal.play();
  }
}
I'm playing with a ball
class Animal:
  def take(self, toy):
    self.toy = toy

  def play(self):
    print("I'm playing with %s" % self.toy)

animal = Animal()
animal.take('a ball')
animal.play()
I'm playing with a ball

Get/set

class Animal {
  private String name;

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return this.name;
  }
}

class ClassGetSet {
  public static void main(String[] args) {
    Animal animal = new Animal();
    animal.setName("Kelya");
    System.out.println(animal.getName());
  }
}
Kelya
class Animal:
  name = None

animal = Animal()
animal.name = 'Kelya'
print(animal.name)
Kelya

Inheritance

class Animal {
  public void walk() {
    System.out.println("I'm walking");
  }
}

class Dog extends Animal {
  public void sing() {
    System.out.println("Bark!");
  }
}

class ClassInheritance {
  public static void main(String[] args) {
    new Dog().walk();
  }
}
I'm walking
class Animal:
  def walk(self):
    print("I'm walking")

class Dog(Animal):
  def sing(self):
    print('Bark!')

Dog().walk()
I'm walking

Mixin

No easy way to do that
class Moving:
  def walk(self):
    print("%s is walking" % self.__class__.__name__)

class Interacting:
  def talk(self):
    print("%s is talking" % self.__class__.__name__)

class Human(Moving, Interacting):
    pass

human = Human()
human.walk()
human.talk()
Human is walking
Human is talking

Has method?

import java.lang.reflect.*;

class Animal {
  public void walk() {
    System.out.println("I'm walking");
  }
}

class ClassHasMethod {
  public static void main(String[] args) {
    Animal animal = new Animal();
    boolean hasMethod = false;
    for (Method m : animal.getClass().getMethods()) {
      if (m.getName().equals("walk")) {
        hasMethod = true;
        break;
      }
    }
    System.out.println(hasMethod);
  }
}
true
class Animal:
  def walk(self):
    print("I'm walking")

animal = Animal()
print(hasattr(animal, 'walk'))
True

Other

Comment

class OtherComment {
  public static void main(String[] args) {
    // it's a comment
  }
}

# it's a comment

Assign value if not exist

No easy way to do that
speed = 0
speed = 15 if speed is None else speed
print(speed)
0

Import another file

// OtherFileToImport.java
// class OtherFileToImport {
//   public OtherFileToImport() {
//     System.out.println("I am imported!");
//   }
// }

class OtherImportFile {
  public static void main(String[] args) {
    new OtherFileToImport();
  }
}
I am imported!
# other_file_to_import.py
# class Import:
#   def __init__(self):
#     print('I am imported!')

import other_file_to_import
other_file_to_import.Import()
I am imported!

Destructuring assignment

No easy way to do that
one, two = 1, 2
print(one, two)
1 2

Date

import java.util.Date;
import java.text.SimpleDateFormat;

class OtherDate {
  public static void main(String[] args) {
    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    System.out.println(date);
  }
}
2024-05-28
import datetime
print(datetime.date.today())
2024-05-28

Time

import java.util.Date;
import java.text.SimpleDateFormat;

class OtherTime {
  public static void main(String[] args) {
    String time = new SimpleDateFormat().format(new Date());
    System.out.println(time);
  }
}
28/05/2024, 20:16
import datetime
print(datetime.datetime.now())
2024-05-28 20:18:14.644332

Not

class OtherNot {
  public static void main(String[] args) {
    boolean angry = false;
    if (!angry)
      System.out.println("smile!");
  }
}
smile!
angry = False
if not angry:
  print('smile!')
smile!

Assign this or that

No easy way to do that
yeti = None
footprints = yeti or 'bear'
print(footprints)
bear

Run command

import java.io.*;

class OtherRunCommand {
  public static void main(String[] args) throws IOException, InterruptedException {
    String result = "";
    ProcessBuilder ps = new ProcessBuilder("java", "-version");
    ps.redirectErrorStream(true);
    Process pr = ps.start();
    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
      result += line + "\n";
    pr.waitFor();
    in.close();
    System.out.println(result);
  }
}
openjdk version "17.0.8.1" 2023-08-24
OpenJDK Runtime Environment Temurin-17.0.8.1+1 (build 17.0.8.1+1)
OpenJDK 64-Bit Server VM Temurin-17.0.8.1+1 (build 17.0.8.1+1, mixed mode, sharing)

import subprocess
subprocess.call(['python3', '--version'])
Python 3.11.2