Input
Output

Java to python converter

This is simple basic alpha version of Java to Python code converter. The main goal of this tool is to provide functionality to deal with converting custom Java code into equivalent Python code.

Java to python converter

Example of java to python

Here mentioned few examples which is based on arrays, strings and some useful packages which is generally used in java programming language.

Java array to python list

Java Code

class MyArray
{
  public static void main(String[] args)
  {
        // Simple array of integer elements
    int[] a = new int[]{1,2,3,4,5};
        int[][] b = new int[][]{{1,2,3},{4,5,6}};
        int[] c = new int[10];
    System.out.println(a.length);
        System.out.println(b.length);
        System.out.println(c.length);
  }
}

Converted Python

class MyArray :
    @staticmethod
    def main( args) :
        # Simple array of integer elements
        a = [1, 2, 3, 4, 5]
        b = [[1, 2, 3], [4, 5, 6]]
        c = [0] * (10)
        print(len(a))
        print(len(b))
        print(len(c))
    

if __name__=="__main__":
    MyArray.main([])

Java String to python string method

Java Code

class MyString
{
  public static void main(String[] args)
  {
        String a = new String("Abc");
        String b = "ABC" + "dec";
        // Abc
        System.out.println(a);
        // ABCdec
        System.out.println(b);
      // ABC
        System.out.println(a.toUpperCase());
        // abcdec
        System.out.println(b.toLowerCase());
      
  }
}

Converted Python

class MyString :
    @staticmethod
    def main( args) :
        a =  "Abc"
        b = "ABCdec"
        # Abc
        print(a)
        # ABCdec
        print(b)
        # ABC
        print(a.upper())
        # abcdec
        print(b.lower())
    

if __name__=="__main__":
    MyString.main([])

Java Hashmap to python dictionary

Java Code

import java.util.HashMap;
class MyHashMap
{
  public static void main(String[] args)
  {
    HashMap < String, Integer > hm = new HashMap < String, Integer > ();
    hm.put("One", 1);
    hm.put("Ten", 10);
    hm.put("Year", 2022);
    // {Year=2022, One=1, Ten=10}
    System.out.println(hm);
    // 3
    System.out.println(hm.size());
  }
}

Converted Python

class MyHashMap :
    @staticmethod
    def main( args) :
        hm =  dict()
        hm["One"] = 1
        hm["Ten"] = 10
        hm["Year"] = 2022
        # {Year=2022, One=1, Ten=10}
        print(hm)
        # 3
        print(len(hm))
    

if __name__=="__main__":
    MyHashMap.main([])

How to convert Python to java ?

We were on our way to convert Python to Java. In which we faced some difficulty. That's because, in Python, everyone acts like an object. But Java has its limitations. We can say that the task of converting from Python to Java is not easy, for this you have to keep the following things in mind.

  • AST Implementation : There are many ways to implement AST (abstract syntax tree), You can use python ast package to implement AST.

    import ast
    code = "print('I am good')"
    result = ast.parse(code)
    print(ast.dump(result))  
    
    Module(body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Str(s='I am good')], keywords=[]))])

    It does not check unnecessary variable methods and packages. Means it doesn't do error detection which is possible in your code.

    You can also use ANTLR v4 to generate the AST. This too will lack the same type detection. When you use antlr you will feel that it works slowly. But it has many benefits that it also provides your visitors, grammar and visualization.

  • Parse Tree Visitor : This is the critical step in which you can control how you represent your code.

  • Type Detection

  • Package detection

  • Syntax Transformation

  • Class Decoration

  • Loop transformation


Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







S     392 Day ago
ffff
Kouta-kun     412 Day ago
On generic code like:
```
class LinkedList<T> {
    private T value;
    private LinkedList<T> next;
    
    public void add(T newVal) {
        if(value == null) {value = newVal; return;}
        if(next == null) {next = new LinkedList<T>();}
        next.add(newVal);
    }
}
```

It for some reason generates Python classes that inherit on T instead of just ignoring it:

```
class LinkedList(T)(object) :
    value = None
    next = None
    def add(self, newVal) :
        if (self.value == None) :
            self.value = newVal
            return
        if (self.next == None) :
            self.next = LinkedList()
        self.next.add(newVal)
```

I think the later versions of Python have some sort of type hinting (like in typing.List[int]) but no runtime type checking, maybe you can just ignore template parameters
Anthony Albert     436 Day ago
python doesn't like:

m_baseURLs[baseCount += 1]

it should be:

baseCount += 1
m_baseURLs[baseCount]
Anthony Albert     436 Day ago
In code like:

t[2] = t[3] = 64;

your translation was:

                t[2] =
                t[3] = 64
Hhdh     650 Day ago
Doesn't work well with functionals and array instantiation.

import java.util.*;
class Test
{
    public static void main(String[] args) {
        List<Long> a = new ArrayList<Long>(Arrays.asList(new Long[] {1L,2L}));
        a.forEach(System.out::println);

    }
}
MANTOSH KUMAR     704 Day ago
Please convert the following JAVA code to PYTHON code the description of the files has been provided below as a link

1.https://github.com/DataLabUPO/CVOA_academic/blob/master/src/parallelcvoa/CVOA.java
2.https://github.com/DataLabUPO/CVOA_academic/blob/master/src/parallelcvoa/CVOAMain.java
3.https://github.com/DataLabUPO/CVOA_academic/blob/master/src/parallelcvoa/Individual.java
>:(     740 Day ago
this program is dumb andruins your javascript please dont use this https://github.com/chrishumphreys/p2 
instead use this convert that can actual transfer in between files, 
(only under the "(..)" rule anything other would be invalid.
Kalkiteam     777 Day ago
It is capable, but it is designed to work with a single file to reduce the load on the server. If you use more than one file it will take more time. 
John     778 Day ago
Seriously? This can't handle dependence between files?
John     778 Day ago
Seriously? This can't handle dependence between files?
Kalkiteam     780 Day ago
It is very important to test for syntax errors, which detect valid code, before starting to convert the code. This is done so that your code can be changed without interruption.
By : kalkicode@gmail.com
Nag     781 Day ago
Why do you compile the java class when converting in to python. How can you expect all import packages are available to you.
Pp021     834 Day ago
// file : XORCrypt
public class XORCrypt {
	private static String key = "o23sSendevia";

	public static String encrypt(String str) {
		int[] output = new int[str.length()];
		for (int i = 0; i < str.length(); i++) {
			int o = (Integer.valueOf(str.charAt(i)) ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
			output[i] = o;
		}
		String out = "";
		for (int enc : output) {
			out += enc + "'";
		}
		return out.substring(0, out.length() - 1);
	}

	public static String decrypt(String input) {
		String output = "";
		String[] str_split = input.split("'");
		int[] split = new int[str_split.length];
		for (int i = 0; i < str_split.length; i++) {
			try {
				split[i] = Integer.parseInt(str_split[i]);
			} catch (NumberFormatException e) {
				new RuntimeException(input, e);
				return input;
			}
        }
		
		for (int i = 0; i < split.length; i++) {
			output += (char) ((split[i] - 48) ^ (int) key.charAt(i % (key.length() - 1)));
		}
		return output;
	}
}
// Write note here
on decrypt method it has same variable on the loop please fix :)
take some min to fix the code but still useful