Trying to learn new language when you already know another one is most at times easier to do. And it is much more so easy when the new language you want to pick up is very related to the one you already know in one way or the other.

Both Java and Python are great programming languages and they are both Object Oriented Programming languages.

This post looks at sample Java codes snippets and their equivalent or similar ones in Python. The emphasis is on the code snippets and not much on explanation of the codes as it is assumed the reader is slightly familiar and understands basic Java codes. (Credit to Krohn – Education on Youtube)

 

Snippet 1: Let’s take a user input and print the input back to him.

Java code:

Scanner reader = new Scanner(System.in);
System.out.print("Input a number :");
int x = reader.nextInt();
System.out.println("You entered "+x);

Java Result:

Input a number :5
You entered 5

Python equivalent:

print("enter a number : ")
x = input()

print("You entered ", x)

Python Result

enter a number :

5
('You entered ', 5)

 

 

Working with Strings

Snippet 2:  Declare a String

Java code:

 String s  = "input method";

Python equivalent:

s = "input method"

 

 

Snippet 3:  Get the length of the String

Java code: 

System.out.println("Length = " + s.length());

Python equivalent:

print("length = " , len(s))

 

 

Snippet 4:  Get the substring of the String

Java code: 

System.out.println("Substring :"+s.substring(2)); /*text starting from index number 2*/

Python equivalent:

print("substring : ", s[2 : ])

 

Get substring wtith text starting from index number 2 ending at index number 5 but the string at that index number 5 is not included

Java code: 

System.out.println("Substring :"+s.substring(2, 5));

Python equivalent:

print("substring : ", s[2 : 5])

 

 

Snippet 5:  Get the last 3 characters of the string 

Java code: 

System.out.println("Substring :"+s.substring(s.length()-3));

Python equivalent:

print("substring : ", s[-3 : ])

 

 

Snippet 6:  Check if an item is contained in a string

Java code: 

System.out.println("Substring :"+s.contains("me"));

Python equivalent:

print("substring : ", "me" in s)

 

Working with Lists

Snippet 7:  Create and Add items to a list and print the list

Java code: 

List list = new ArrayList();
list.add("car");
list.add("bike");
list.add("plane");
System.out.println("List = "+list)

Python equivalent:

list = []
list.append("car")
list.append("bike")
list.append("plane")
print(list)

 

 

Snippet 8:  Get the size of the list

Java code:

System.out.println("Size of list = :" + list.size());

Python equivalent:

print("List length :" , len(list))

 

 

Snippet 9:  Get an item from the list at an index

Java code:

System.out.println("get item from list: " + list.get(1));

Python equivalent:

print("Get item at an index ", list[1])

 

 

Snippet 10:  Add an item to the list

Java code:

list.add(1, "scooter");
System.out.println("List = "+list);

Python equivalent:

list.insert(1, "scooter")

 

 

Snippet 11:  Delete item from the list at an index

Java code:

list.remove(1);

Python equivalent:

del(list[1])

 

Extra Python List methods

Python has another method with list called “extend”. It basically grabs all the elements in  a second list and add all of them to the end of the elements in the first list.

For example we will create a second list called list2

list2 = []
list2.append("car")
list2.append("bike")
list2.append("plane")

#Let's print the list2
print(list2)

Now let’s use the extend method:

list.extend(list2)
print(list)

Result :

['car', 'bike', 'plane', 'car', 'bike', 'plane']

 

We can also create a new list by adding the two list

list3 = list + list2
print("list 3", list3)

Result:

['car', 'bike', 'plane', 'car', 'bike', 'plane']

We can also add up the  individual lists as elements of one list

list4 = []
list4.append(list)
list4.append(list2)
list4.append(list3)
print("list 4", list4)

 

 

Working with comparison operators

Snippet 12: Let’s take a user input and check if it is the same as a value we have stored or kept in our program.

Java code:

Scanner reader = new Scanner(System.in);
System.out.print("Input a number :");
String input = reader.nextLine();
String ours = "car";

/*== checks if the items compared are exact same instance/object, whereas .equals checks the characters of 
of the compared items*/
System.out.println( input == ours);

/*check if characters are the same*/
System.out.println( input.equals(ours));

Java result:

run:
Input a number :car
false
true

The “== “ comparison checks if the items compared are exact same instance/object, whereas “.equals” checks the characters of the compared items

 

Similar Python code:
The  “== ” comparison in Python does the opposite of what the “==” operator does in Java. In Python it checks if the values are the same instead of checking if they are of the same instance type.

There is a second comparison operator in this category for Python called “is”. This checks if the two items are exact same object or instance

x = 15
y = 14
z= x

print("x is y" , x is y)
print("x == y" , x == y)
print("z is x" , z is x)

Python result:

('x is y', False)
('x == y', False)
('z is x', True)

 

 

Snippet 13 : The following comparisons work same in Python as they do in Java:

 <     >      <=      >=     != 

 

 

Now let’s look at these 3 operators:      !,      && ,    ||

Snippet 14 :Negating a result with the not (!) sign

Java code:

System.out.println(!(4>5));

Python equivalent:

print(not (4>5)) #uses the 'not' keyword

 

 

Snippet 15: The “&&”  operator; both sides of the comparison should be ‘true’

Java code:

System.out.println((4<5) && (10<5));
System.out.println((4<5) && (10>5));

Python equivalent:

#Python uses the and keyword

print(4< 5 and 10< 5)
print(4< 5 and 10> 5)

 

 

Snippet 16: Java uses || and Python uses “or” , either side of the equation should be ‘true’

Python code:

print(4< 5 or 10< 5)
print(4< 5 or 10> 5)
print(4> 5 or 10> 5)

 

 

Snippet 17:  The “if” operator

Java code:

if(4<5)
System.out.println("Yes");

Python equivalent:

#the "if" operator in Python using indentation
if 4<5:
   print("Yes")

 

 

Snippet 18: The “if” operator with “else”

Java code:

if(4>5)
System.out.println("Yes");
else
System.out.println("No");

Python equivalent:

#the "if" operator withe "else" in Python using indentation
if 4>5:
   print("Yes")
else:
   print("No")

 

 

Snippet 19: the “if” operator with “else” and elseif

Java code:

if(4>5)
System.out.println("Yes");
else if(3<4)
System.out.println("Mid"); 

else
System.out.println("No");

Python equivalent:

#the "if" operator withe "elif" and "else" in Python using indentation
if 4>5:
   print("Yes")
elif 3< 4:
   print("Mid")
else:
   print("No")

 

 

 

Working with Loops

Snippet 20: While Loops

Java code:

int x = 0;
while (x<5){
System.out.println(x);
x++;

}

Python equivalent:

x = 0
while x < 5:
    print(x)
    x += 1

 

 

Snippet 21: FOR Loops

Java code:

for(int i = 0; i <10; i++){

System.out.println(i);
}

Python equivalent:

#Python uses range

for x in range(5):
        print(x)

#FOR LOOPS; range start from 2 and go up to 20 with each increase of 4

for x in range(2, 20, 4):
print(x)

 

 

Snippet 22:  FOR Each Loop

Java code:

int [] arry = {1,2,8,20};
for(int i : arry)
System.out.println(i);

System.out.println(sum(1,2,3));

Python equivalent:

lst1 = [1,2,8 ,20,56,3 ]
for n in lst1:
print(n)
else:
print("finished running with no break")

 

Additional notes for Python
# FOR EACH loop WITH an else statement in Python. The else statement will execute if all the FOR EACH loop run
# without the break statement being called

lst1 = [1,2,8 ,20,56,3 ]
for n in lst1:
if n == 200:
break
print(n)
else:
print("finished running with no break")

 

 

Working With Functions / Methods

Snippet 23: Declare a function / Method

Java code:

private static int sum(int a, int b, int c){
return a+b+c;
}

Python equivalent:

#working with FUNCTIONS / methods in Python
# no need to declare return data type,
# no need to declare data type of arguments

def sum(a,b,c):
return a+b+c

print(sum(1,2,3))

 

Additional notes about Python functions:

You can  declare a mystery method. Like assigning your function to a variable and the variable will act just like the function you already created.  For example

mystery= sum

print(mystery(1,2,3))

 

With Python you can also have optional parameters
You can also set the value of one of the paramaters of the function to a default value. Example:

def sum2(a, b, c=2):
return a+b+c

print(sum2(2,2))

 

 

Working with Classes and Objects

Java code:

public class Dog {

public int age ;
public String name ;

public Dog(String nm, int age){
this.age = age;
this.name = nm;
}

public int getAge(){
return this.age;
}

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

public void setAge(int a){
this.age = a;
}
public void setName(String nm){
this.name = nm;
}

public String toString(){
return "Dog \nName: " + name +" \nAge: "+ age;
}

public static void main(String[] args){
Dog d1 = new Dog("Hope",5);
System.out.println(d1);
}
}

Python equivalent:

#CREATING A CLASS OBJECT IN PYTHON
#the class name in Python must not necessarily be same as the name of the file as in Java

class Dog:

    #create a constructor with the __init__
    def __init__(self, name, age):

    # in python you do not have to necessarily declare the variables outside of the 
    #constructor indicating , there will be these instance/object variables. you can create them 
    # on the file inside the constructor

    ##placing underscore infront of the instance variables indicate that they are private variables
    # and should be changed with our setter and getter methods
    self._name = name
    self._age = age


    # lets declare our getter functions
    def get_name(self):
    return self._name

    def get_age(self):
    return self._age

    #lets declare our setter functions
    def set_name(self, name):
    self._name = name

    def set_age(self, age):
    self._age = age

    #class method: it does not use the "self" keyword
    def random():
    return 7


    ## lets create a toString version just like in java
    def __str__(self):
    return "Dog \nName: " + self._name +"\nAge: "+ str(self._age)

    ## passing the keyword: self in the functions indicate that they are instance/object functions and 
    #can be accessed by creating instance of our class. 
    #if we do not pass the self keywords, it means, the function is a class function and does not need 
    #object /instance of the class before they can be called. we can simply get the name of the class and call 
    # such a function


# we do not need a the "new" keyword as in java to create an instance in Python
d1 = Dog("Hope", 15)
print(d1)
print(d1.get_age())

#lets print the class function without needing an instance of the dog
#print(Dog.random())

 

This is a very quick reference tip to help out when you need some slight clarifications. I hope it will be helpful to you. If you have any questions, please ask in the comment box below.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *