From Python to Java
/
Introduction
Beginners learning to code for the first time often chose Python due to its simplistic syntax. Compared to other languages, Python is simple to grasp and uses fewer lines of code to achieve the same task. It serves as a very accessible and straightforward introduction to programming.
However, once the fundamentals of coding have been adopted from learning Python, it is useful to learn other languages for different applications. While you can explore many different implementation of Python's due to its versatility, other languages such as Java and C++ are favoured for large-scale projects because of their improved performance and robustness.
A typical progression of language difficulty is often described as follows: Python, which is relatively easy; Java, which is moderately difficult; and C++, which is considered the most challenging. The jump from Python to learning C++ would undoubtedly be difficult; learning Java can ease the transition into more challenging languages by building on existing knowledge of data structures and object-oriented programming.
This article focuses on translating some of the fundamentals of Python code to its counterpart in Java.
Implementation
print(Hello, World!)
In Python, a simple statement such as "Hello, World!" can be output in one simple line of code.
#Python
print("Hello, World!)
#Output: Hello, World!
Getting the same output in Java is not so simple. All Java program must start with the declaration of a class, a logical template that groups objects with common properties. Because all of your code resides within classes and object, Java is object-oriented. When a class is declared, it is assigned a public or private modifier that will determine its visibility to other classes. Methods, which are comparable to functions in Python, are declared within classes. Like functions, methods can be reused to perform specific tasks such as printing out "Hello, World!".
public class josiesBlog {
public static void main(String... args) {
System.out.println("Hello, World!");
}
}
//Output: Hello, World!
//Note: Java uses "//" instead of # for inline comments!
Notice that instead of using ":" to indent the new line, Java encompasses everything within a class or method in "{}". All statements, such as the print statement, or any other declarations, must end its line with ";".
Variables and Types
Assigning values to a variable in Python is rather straightforward, the only requirements being that the variable name is states and assigned a value through the assignment operator.
helloWorld = "Hello, World!"
thisInt = 98
In Java, variables must be declared with their type and their assigned name. A variable cannot hold a value of a type other than that which is stated.
public class josiesBlog {
String helloWorld = "Hello, World!!";
int thisInt = 98;
//Note: Variable names use lower camelCase notation
}
There are two types of variables in Python: primitive and reference types.
Primitive types include boolean, integer values (byte, char, short, int, long), and floating-point values (float, double). When referenced, they always begin with a lowercase letter. They store a primitive value which occupies a fixed amount of space.
Reference types include String, List, ArrayList, and Class (a user-defined referenced type!). When referenced, they always begin with an uppercase letter. In comparison to primitive types, they only store a reference to the reference object.
Classes and methods
Now back to classes and methods; they are both declared with a modifier (public/private).
Methods can also be declared as static or void. A static method is associated with its class and will always return a value while a void method will not return 0 or no value. Following this, the return type of the method's parameters will be stated in the brackets. Methods can be user-defined, like Python functions, by stating the parameter type and its assigned variable within the brackets. The method can then be used by inputing an argument when called.
// A static method
public class josiesBlog {
public static int average(int a, int b) {
int add = a + b;
return add / 2;
}
//Output: Average of a and b
// A void method
public static void main(String[] args) {
int x = max(2, 3);
}
// Output: None - no return statement
}
Arrays
Arrays are the same idea as "Lists" in Python. They are a container object that holds a fixed number of values of a single type in a comma separated list. They are contained within "{}" and accessed using "[]". To reference an array of a specific type, declare the type followed by the square brackets.
public class josiesBlog {
String[] colors; //declare an array
String[] colors = {"Red", "Orange", "Blue"};
int[] myNums = {1, 2, 3, 4};
}
Conditionals and Operators
Conditional statements in Java and Python are almost identical, except for the differences in formatting.
def max(a, b, c):
if a>=b and a>=c:
result = a
elif b>=a and b>=c:
result = b
else:
result = c
return result
#Output: greatest number out of a, b, c
Java retains "if" and "else" as conditional statements, however "else if" is used in place of Python's "elif". Notably, Java also utilizes symbols instead of the "and/or" operators. "&&" is the logical AND operator while "||" is the logical OR operator.
public class josiesBlog {
public static double max(double a, double b, double c) {
if (a>= b && a>=c) {
result = a;
}
else if (b>= a && b>=c) {
result = b;
}
else {
result = c;
}
return result;
}
}
//Outpit: greatest number out of a, b, c
Loops
A for loop is index based and keeps track of a variable as it iterates through a list. In Python, the loop variable is commonly assigned the value "i".
def find5(a):
target = 5
for i in a:
if i == target:
return True
return False
In Java, an indexed-based loop also uses a loop variable to iterate through a list. For loops are composed of the following components:
Initialization expression: The loop variable is declared and initialized (int i =0).
Termination condition: If the loop evaluates to false, it stops (i<a.length).
Update expression: Evaluated after each iteration of the loop and modifies the loop variable (i++).
Loop body
For loop: Executes a block of code until an expression returns false.
For-each loop: Executes a block of code through items.
public class josiesBlog{
//For loop
public class Find5 {
public static boolean find5(int[] a) {
int target = 5;
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
return true;
}
}
return false;
}
//For each loop
public class find5 {
public static boolean find5(int[] a) {
int target = 5;
for (int i : a) {
if (i == target) {
return true;
}
}
return false;
}
}
Conclusion
This article covered the basis of understanding Java from the lens of Python users. The process of translation often requires careful consideration of language-specific features such as data types, loops, and conditionals. When translating between the two, it is crucial to maintain the logic and functionality of the original Python code while adhering to Java's more complex syntax rules.
Despite the challenges, translating Python code to Java can be beneficial, especially in scenarios where Java's performance and platform compatibility improve the overall performance of the code. Ultimately, you gain more experience and versatility as a programmer from bridging the two languages together.