Python to Java Code Converter
Port algorithms, interview snippets, and learning examples from Python to Java without installing anything. The rule-based converter runs locally in your browser, so code stays private; for larger programs, the optional Convert with AI button produces an idiomatic Java translation with notes on what to check.
Typical use cases: migrating utility scripts, comparing syntax across languages, preparing Java stubs from Python prototypes, and speeding up CS homework refactoring.
Select your languages, paste code, and iterate with swap-and-edit until the output matches your target idioms.
Python to Java uses dedicated rewrite rules. This pair has hand-written rules rather than a generic fallback: block structure, string literals, loops, conditionals and function declarations are translated directly from Python into Java idioms.
Python types and their Java equivalents
| Python | Java | Watch out for |
|---|---|---|
int |
int, long or BigInteger |
Python integers never overflow; int is 32-bit |
float |
double |
|
str |
String |
Compare with .equals(), not == |
bool, None |
boolean, null or Optional<T> |
|
list[int] |
List<Integer> (ArrayList) |
Collections hold boxed types: Integer, not int |
dict[str, int] |
Map<String, Integer> |
HashMap has no order; LinkedHashMap keeps insertion order like Python |
set, tuple |
Set (HashSet), a record |
|
print(a, b) |
System.out.println(a + " " + b) |
|
f"{x:.2f}" |
String.format("%.2f", x) |
Worked example: counting words
def word_counts(words):
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
return counts
for word, n in word_counts(["to", "be", "or", "not", "to", "be"]).items():
print(word, n)
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
static Map<String, Integer> wordCounts(List<String> words) {
Map<String, Integer> counts = new LinkedHashMap<>(); // keeps insertion order, like a Python dict
for (String w : words) {
counts.merge(w, 1, Integer::sum); // counts.get(w, 0) + 1 in one call
}
return counts;
}
public static void main(String[] args) {
for (Map.Entry<String, Integer> e : wordCounts(List.of("to", "be", "or", "not", "to", "be")).entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
}
}
Both print the same four lines in the same order. Two choices make that happen: LinkedHashMap instead of HashMap, because a Python dict remembers insertion order and a plain HashMap does not, and counts.merge(w, 1, Integer::sum), Java's one-call version of counts.get(w, 0) + 1. Everything lives inside a class with a main method. Save it as Main.java and run javac Main.java && java Main.
What the converter does with your code
Paste this Python on the left:
class Student:
def __init__(self, name):
self.name = name
self.marks = []
def add_mark(self, mark):
self.marks.append(mark)
def average(self):
return sum(self.marks) / len(self.marks)
s = Student("Asha")
for m in [78, 85, 91]:
s.add_mark(m)
print(f"{s.name}: {s.average():.1f}")
The converter writes a complete Main.java:
public class Main {
static class Student {
String name;
ArrayList<Integer> marks;
Student(String name) {
this.name = name;
this.marks = new ArrayList<>();
}
void add_mark(int mark) {
this.marks.add(mark);
}
double average() {
return (double) this.marks.stream().mapToInt(Integer::intValue).sum() / this.marks.size();
}
}
public static void main(String[] args) {
Student s = new Student("Asha");
for (int m : List.of(78, 85, 91)) {
s.add_mark(m);
}
System.out.println(s.name + ": " + String.format("%.1f", s.average()));
}
}
Compiled with javac -Xlint:all Main.java it builds without warnings, and java Main prints Asha: 84.7, the same as Python. The class became a nested static class with typed fields, __init__ became a constructor, self became this, the empty list became an ArrayList<Integer> because whole numbers are appended to it, add_mark takes an int because that is what it is called with, and / kept Python's true division with a (double) cast.
What it translates: functions with default and keyword arguments, classes with constructors, methods, inheritance, super(), class-level counters and __str__ as toString, lists as ArrayList, dictionaries as LinkedHashMap (which keeps Python's insertion order), string methods and slicing, for over range, lists, strings, enumerate and .items(), input() including map(int, input().split()), print with sep and end, f-strings with widths and :.2f, conditional expressions, swaps, and try/except/raise with matching Java exceptions. Floats, booleans, None, lists and dictionaries print the way Python prints them.
Types are worked out over the whole program: from literals, from the arguments each function, method and constructor is called with, from return values and from what is appended to lists. What it leaves as // TODO comments: comprehensions, lambdas, generators, with blocks, tuples and sets, zip, and anything whose type cannot be worked out. Python integers never overflow and Java int is 32-bit; the header comment says so.
Rules or AI?
The rule-based converter runs instantly in your browser and is built for homework-sized programs: the test suite compiles more than twenty typical programs, including classes, inheritance and dictionaries, with all warnings on, and checks that each prints exactly what Python prints. For larger programs that use libraries, comprehensions or lambdas, press Convert with AI for an idiomatic translation with streams and records where they fit, then compile it and compare its output with the Python version.