|

Python Similarities Comparison With Java – Short Code Snippets

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:

Java Result:

Python equivalent:

Python Result

 

 

Working with Strings

Snippet 2:  Declare a String

Java code:

Python equivalent:

 

 

Snippet 3:  Get the length of the String

Java code: 

Python equivalent:

 

 

Snippet 4:  Get the substring of the String

Java code: 

Python equivalent:

 

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: 

Python equivalent:

 

 

Snippet 5:  Get the last 3 characters of the string 

Java code: 

Python equivalent:

 

 

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

Java code: 

Python equivalent:

 

Working with Lists

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

Java code: 

Python equivalent:

 

 

Snippet 8:  Get the size of the list

Java code:

Python equivalent:

 

 

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

Java code:

Python equivalent:

 

 

Snippet 10:  Add an item to the list

Java code:

Python equivalent:

 

 

Snippet 11:  Delete item from the list at an index

Java code:

Python equivalent:

 

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

Now let’s use the extend method:

Result :

 

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

Result:

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

 

 

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:

Java result:

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

Python result:

 

 

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:

Python equivalent:

 

 

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

Java code:

Python equivalent:

 

 

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

Python code:

 

 

Snippet 17:  The “if” operator

Java code:

Python equivalent:

 

 

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

Java code:

Python equivalent:

 

 

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

Java code:

Python equivalent:

 

 

 

Working with Loops

Snippet 20: While Loops

Java code:

Python equivalent:

 

 

Snippet 21: FOR Loops

Java code:

Python equivalent:

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

 

 

Snippet 22:  FOR Each Loop

Java code:

Python equivalent:

 

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

 

 

Working With Functions / Methods

Snippet 23: Declare a function / Method

Java code:

Python equivalent:

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

 

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

 

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:

 

 

Working with Classes and Objects

Java code:

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

 

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.

Want more information like this?

Similar Posts

  • |

    Create Batch Dot Bat File to Run Your Python Script With Windows Scheduler

    After writing your script, you might want to schedule it to run periodically, let’s say, Daily, Weekly or Any Time interval you will decide Before you schedule that you want to  simply create a batch file and schedule it run with a Windows Scheduler. Here are simple steps to do that. First of all, if…

  • ImportError: No module named ‘scikits’ – Python Fix Jupyter Notebook

    If you have the above problem, to fix this, follow these guidelines as advised by Flowerowl  at this link (https://github.com/muricoca/crab/issues/92): The steps are as follows:   Don’t install crab in this way: pip install crab / easy_install crab You can find crab in pypi.python.org, this is not our scikits.crab source Solution: git clone https://github.com/muricoca/crab.git python setup.py…

  • |

    Declare Public Protected and Private Variables in Python – Object Oriented Programming

    In Python, the scope ( Public, Protected, Private) characteristic of an attribute or member of the class is indicated by “the naming conventions of the member”. These are the naming conventions Public: This means the member can be accessed outside of the class by other instances. The naming convention denotes that it has no underscores…

  • |

    Pandas DataFrame and Series Alignment Python Notes

    This week we have a look at Data Alignment in Python In [1]:

      In [2]:

      Out[2]:

    In [3]:

      Out[3]:

    In [4]:

      Out[4]:

    In [6]:

      Out[6]: A B LA 0 1 GA 2 3 In [10]:

      Out[10]: A B C LA 0 1 2 NYC 3 4…

  • Read_csv Is Not Returning A Dataframe Python Pandas

    I was working with a CSV file on a project and after reading the CSV into the Program with the pandas.read_csv function the returned data type seemed not be a Dataframe for some reason code was as follows: sample = pd.read_csv(‘sample.csv’) When i tried to run some functions on the supposed ‘returned dataframe object -sample’ I…

  • | |

    Testing a Basic Linear Regression Model – Data Analysis and Intrepretation

    Testing a Basic Linear Regression Model Background My research work deals with Ghana, a country from the Gapminder dataset as has already been discussed from the beginning and progression through this course.     1)     Program  Code and Output

           #####################     OUTPUT BEGIN  #####################     Axes(0.125,0.125;0.775×0.775) Describe the centered…

Leave a Reply

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