4

Syntax at a Glance: Java Versus Python

 1 year ago
source link: https://devm.io/python/java-vs-python-syntax
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Battle of the Languages – Part 1

Syntax at a Glance: Java Versus Python


Java and Python have each been around for over 25 years. However, instead of getting old or even frail and unpopular, the complete opposite is true. Both enjoy enormous popularity in both the private and professional sectors. While Java led the pack for a long time, over the past two years, the picture has increasingly changed towards Python. According to the TIOBE index, Python now holds first place among the most popular programming languages. Java takes third place but was first for years. In this article series, we want to familarize with both languages and their respective strengths and potential weaknesses by using entertaining programming puzzles.

In this first part of this series, we will start comparing essential elements of both languages in a quick run-through, so that you can follow the examples and programming puzzles, even without prior Python knowledge. After a quick introduction to the essential syntax elements, we’ll start with the first programming puzzle — a vowel guessing quiz.

Java versus Python: Introducing REPL

Before we get started with the content, let's take a quick look at how to directly follow the examples. Conveniently, both Java and Python provide an interactive command line application as REPL (Read Eval Print Loop).

Java REPL

Introduced in Java 9, the JShell is an interactive tool, which should make the entry into Java easier. Open a console and enter the following command:

$ jshell
| Welcome to JShell -- Version 17.0.3
| For an introduction type: /help intro
jshell>

In the following text, I always use $ to indicate input on the console, i.e. the terminal on macOS/Linux or the Windows command prompt:

Besides the version hint, the jshell> prompt indicates that we can now enter Java commands. Let's try it out right away:

jshell> System.out.println("Hello World from JShell!")
Hello World from JShell!

Python REPL

If you want to try out the examples presented below directly, please install the modern Python 3.10 or the brand-new version 3.11. Both are freely available for download [2] for the most common operating systems. As briefly mentioned, an interactive command line application is included as REPL. You start this under Windows with the command python and under macOS with python3. This allows an interactive working style and the execution of small code snippets. So: Let's go!

Let's start the REPL and try out some actions and calculations. A variation of a Hello World example serves as our starting point, followed by a mathematical calculation including a cast (Listing 1).

Listing 1

$ python3
Python 3.11.3 (v3.11.3:f3909b8bc8, Apr  4 2023, 20:12:10) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>>
>>> print("Hello Python")
Hello Python
>>>
>>> int(2 * 7 * 3.1415)
>>> 43

Java versus Python: Basic knowledge of variables and types

In contrast to the statically typed Java which requires a strict assignment of a type for each variable, Python follows a more laissez-faire attitude. It allows variables to be defined without specifying types. The following shows a definition of variables representiong an age, a name, and a list of hobbies:

>>> age = 51
>>> name = "Michael"
>>> hobbies = ["Java", "Python", "Reading", "Cycling"]  

However, not specifying types doesn’t mean that Python doesn’t know types, quite the contrary. We get the type for a variable by calling type() as follows:

>>> type(age)
<class 'int'>
>>> type(name)
<class 'str'>
>>> type(hobbies)
<class 'list'>

Special mathematical operators in Python

Just like Java, Python supports common mathematical operations, like addition, multiplication, etc. Additionally, Python brings two special features: integer division (without a remainder) using // and power calculation using ** (Listing 2).

Listing 2

>>> 1000 // 13
76
>>> 1000 / 13
76.92307692307692
>>> 13 ** 2
169
>>> 1000 ** 3
1000000000

Within numbers, we can use the _ character to simulate a kind of thousands symbol, just like in Java. This makes it possible to write down larger numerical values clearly. In principle, the _ can be used as many times and as often as we wish, but not several times in a row:

>>> one_million = 1_000_000
>>> one_thousand = 1_0_0_0
>>> one_million = 1_000__000
  File "<stdin>", line 1
    one_million = 1_000__000
                       ^
SyntaxError: invalid decimal literal

Special strings

Strings consist of a sequence of single characters. Unlike other languages, Python doesn’t have a separate data type for individual characters. These are simply represented as a string with a length of 1. Strings can be created in double or single quotes, as shown in the following two lines:

str1 = "DOUBLE QUOTED STRING"
str2 = 'SINGLE QUOTED STRING'
They can be added with + and multiplied with *:
>>> name = "Inden"
>>> fullname = "Michael " + name
>>> fullname
'Michael Inden'
>>> "Morning" * 3
'MorningMorningMorning'

You might be a bit surprised if you want to link texts and numbers, since it’s possible in Java:

>>> number = 3
>>> "Please ring " + number + " times!"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

With this error message in mind, it is obvious that Python can only add strings with +. For other types, a cast must be performed explicitly, which can sometimes seem a bit awkward:

>>> "Please ring " + str(number) + " times!"
'Please ring 3 times!'

Java versus Python: Special strings and output with print()

Sometimes we already have output values, often by simply entering the name in the console. Alternatively, we can use the function print(), which we already briefly mentioned. In Python programs, this is the only possibility for output.

>>> print("Hello " + fullname)
Hello Michael Inden

It’s often handy that an automatic line break occurs at the end. But sometimes, you don’t want this. For example, you may need to display several outputs in a program one after another in one line. For this, you can use print() with an empty end character passing end="" as parameter. Even on the console, there is no line break:

>>> print("Hello " + fullname, end="")
Hello Michael Inden>>>

Alternatively, you can vary the string:

>>> print("Hello " + fullname, end="!!!")
Hello Michael Inden!!!>>>

In order to output values with print(), they must be converted to textual form. This is done automatically if you use a comma-separated variant that adds a space between the values:

>> print("Hello", fullname, "the answer is", 42, "and not", age)
Hello Michael Inden the answer is 42 and not 51

Alternatively, you can convert the components into a string by...


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK