ToolSphere

Python to Java Converter

More tools

Convert Python to Java online: functions, loops, classes and string formatting rewritten as Java. Free, private, runs in your browser.

Verified pairDedicated rewrite rules — syntax, blocks, strings and loops are translated.
Python input
Java output

AI conversion

For real programs the rules can't handle, translate with Google Gemini: idiomatic Java, imports included, with notes on what to check. This sends the code above to Google, so don't use it for confidential code (privacy). Up to 6,000 characters, 15 conversions a day.

Rewrite rules cover 13 source and 13 target languages (Python, JavaScript, TypeScript, Java, C#, Go, Ruby, PHP, Rust, Kotlin, Swift); the remaining 31 are listed for reference and pass through annotated rather than translated. Complex projects still need manual review. The rule-based conversion runs entirely in your browser; only the optional AI conversion sends code anywhere.

On this browser only

Give feedback

Did this tool help?

Tell us what worked, what didn’t, or what you’d like next.

Opens Google Forms in a new tab with this tool’s name filled in. No sign-in or email required. Feedback is optional.

How to use Python to Java Converter

  1. 1Choose the source and target programming languages from the dropdowns.
  2. 2Paste your source code into the left editor (or click Load sample).
  3. 3Review the converted output on the right; use Copy or Download to export.
  4. 4Swap languages to reverse the conversion direction when supported.

About Python to Java Converter

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.

Frequently asked questions

How reliable is Python to Java conversion?

This is one of the converter's directly supported pairs, so everyday syntax — functions, classes, loops, conditionals and string formatting — translates cleanly. Library and framework calls still need manual work, since only language syntax is mapped.

Is my source code uploaded to a server?

Not by the converter itself: the rule-based conversion runs entirely in your browser. Only if you press Convert with AI is the code sent to Google Gemini for translation, so keep confidential code to the rule-based converter.

How accurate is automatic code conversion?

Popular pairs (Python, JavaScript, Java, Go, C#, etc.) use dedicated rewrite rules. Other pairs may use a JavaScript pivot or annotated passthrough — always review before production use.

Can I convert entire projects?

This tool is optimized for snippets, homework samples, and algorithm ports. Multi-file projects need manual structure and import adjustments.

Does this support every Python library?

No. Standard language syntax is mapped; framework-specific APIs must be rewritten manually in Java.

Does the converted Java code compile?

For typical homework programs, yes: the converter is tested by compiling programs with classes, inheritance, lists, dictionaries, strings, input and exceptions with javac -Xlint:all, and checking that each prints the same output as Python. Anything it cannot translate is left as a TODO comment rather than a guess.

How are Python classes converted to Java?

Each class becomes a nested static class inside Main. __init__ becomes a constructor, self becomes this, self.x fields become typed fields, methods become instance methods, and a subclass extends its base and calls super(...). __str__ becomes toString, so printing an object works as in Python.

How does the converter choose Java types?

It works them 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 or stored in dictionaries. Parameters it cannot type are declared Object, so check those first.

What do Python lists and dictionaries become?

Lists become ArrayList and dictionaries become LinkedHashMap, which keeps keys in insertion order the way Python 3.7+ does. Indexing becomes get and set, append becomes add, d.get(k, 0) becomes getOrDefault, and printing them shows the same text Python shows.

How are input() and print() converted to Java?

input() becomes a small input helper built on Scanner that reads a whole line, int(input()) becomes Integer.parseInt, and map(int, input().split()) reads several numbers from one line. print becomes System.out.println, keeping sep, end and f-string formatting.

Which Java version do I need?

Java 17 or later, because the output uses var and pattern matching in its print helper. Save the file as Main.java and run javac Main.java, then java Main.

Have a suggestion for Python to Java Converter?Share your feedback ↗