Author: saqibkhan

  • Interpreter and Its Modes

    Python Interpreter

    Python is an interpreter-based language. In a Linux system, Python’s executable is installed in /usr/bin/ directory. For Windows, the executable (python.exe) is found in the installation folder (for example C:\python311).

    This tutorial will teach you How Python Interpreter Works in interactive and scripted mode. Python code is executed by one statement at a time method. Python interpreter has two components. The translator checks the statement for syntax. If found correct, it generates an intermediate byte code. There is a Python virtual machine which then converts the byte code in native binary and executes it. The following diagram illustrates the mechanism:

    Python Interpreter

    Python interpreter has an interactive mode and a scripted mode.

    Python Interpreter – Interactive Mode

    When launched from a command line terminal without any additional options, a Python prompt >>> appears and the Python interpreter works on the principle of REPL (Read, Evaluate, Print, Loop). Each command entered in front of the Python prompt is read, translated and executed. A typical interactive session is as follows.

    >>> price =100>>> qty =5>>> total = price*qty
    >>> total
    500>>>print("Total = ", total)
    Total =500

    To close the interactive session, enter the end-of-line character (ctrl+D for Linux and ctrl+Z for Windows). You may also type quit() in front of the Python prompt and press Enter to return to the OS prompt.

    >>> quit()
    
    $
    

    The interactive shell available with standard Python distribution is not equipped with features like line editing, history search, auto-completion etc. You can use other advanced interactive interpreter software such as IPython and bpython to have additional functionalities.

    Python Interpreter – Scripting Mode

    Instead of entering and obtaining the result of one instruction at a time as in the interactive environment, it is possible to save a set of instructions in a text file, make sure that it has .py extension, and use the name as the command line parameter for Python command.

    Save the following lines as prog.py, with the use of any text editor such as vim on Linux or Notepad on Windows.

    print (“My first program”) price = 100 qty = 5 total = price*qty print (“Total = “, total)

    When we execute above program on a Windows machine, it will produce following result:

    C:\Users\Acer>python prog.py
    My first program
    Total = 500
    

    Note that even though Python executes the entire script in one go, but internally it is still executed in line by line fashion.

    In case of any compiler-based language such as Java, the source code is not converted in byte code unless the entire code is error-free. In Python, on the other hand, statements are executed until first occurrence of error is encountered.

    Let us introduce an error purposefully in the above code.

    print("My first program")
    price =100
    qty =5
    total = prive*qty #Error in this statementprint("Total = ", total)

    Note the misspelt variable prive instead of price. Try to execute the script again as before −

    C:\Users\Acer>python prog.py
    My first program
    Traceback (most recent call last):
      File "C:\Python311\prog.py", line 4, in <module>
       total = prive*qty
       ^^^^^
    NameError: name 'prive' is not defined. Did you mean: 'price'?
    

    Note that the statements before the erroneous statement are executed and then the error message appears. Thus it is now clear that Python script is executed in interpreted manner.

    Python Interpreter – Using Shebang #!

    In addition to executing the Python script as above, the script itself can be a selfexecutable in Linux, like a shell script. You have to add a shebang line on top of the script. The shebang indicates which executable is used to interpret Python statements in the script. Very first line of the script starts with #! And followed by the path to Python executable.

    Modify the prog.py script as follows −

    #! /usr/bin/python3.11print("My first program")
    price =100
    qty =5
    total = price*qty
    print("Total = ", total)

    To mark the script as self-executable, use the chmod command

    $ chmod +x prog.py
    

    You can now execute the script directly, without using it as a command-line argument.

    $ ./hello.py
    

    Interactive Python – IPython

    IPython (stands for Interactive Python) is an enhanced and powerful interactive environment for Python with many functionalities compared to the standard Python shell. IPython was originally developed by Fernando Perez in 2001.

    IPython has the following important features −

    • IPython‘s object introspection ability to check properties of an object during runtime.
    • Its syntax highlighting proves to be useful in identifying the language elements such as keywords, variables etc.
    • The history of interactions is internally stored and can be reproduced.
    • Tab completion of keywords, variables and function names is one of the most important features.
    • IPython’s Magic command system is useful for controlling Python environment and performing OS tasks.
    • It is the main kernel for Jupyter notebook and other front-end tools of Project Jupyter.

    Install IPython with PIP installer utility.

    pip3 install ipython
    

    Launch IPython from command-line

    C:\Users\Acer>ipython
    Python 3.11.2(tags/v3.11.2:878ead1, Feb 72023,16:38:35)[MSC v.193464 bit (AMD64)] on win32
    Type 'copyright','credits'or'license'for more information
    IPython 8.4.0-- An enhanced Interactive Python. Type '?'forhelp.
    In [1]:

    Instead of the regular >>> prompt as in standard interpreter, you will notice two major IPython prompts as explained below −

    • In[1] appears before any input expression.
    • Out[1]appears before the Output appears.
  • Application Areas

    Python is a general-purpose programming language. It is suitable for the development of a wide range of software applications. Over the last few years Python has been the preferred language of choice for developers in the following application areas −

    Let’s look into these application areas in more detail:

    Data Science

    Python’s recent meteoric rise in the popularity charts is largely due to its Data science libraries. Python has become an essential skill for data scientists. Today, real time web applications, mobile applications and other devices generate huge amount of data. Python’s data science libraries help companies generate business insights from this data.

    Libraries like NumPyPandas, and Matplotlib are extensively used to apply mathematical algorithms to the data and generate visualizations. Commercial and community Python distributions like Anaconda and ActiveState bundle all the essential libraries required for data science.

    Machine Learning

    Python libraries such as Scikit-learn and TensorFlow help in building models for prediction of trends like customer satisfaction, projected values of stocks etc. based upon the past data. Machine learning applications include (but not restricted to) medical diagnosis, statistical arbitrage, basket analysis, sales prediction etc.

    Web Development

    Python’s web frameworks facilitate rapid web application development. DjangoPyramidFlask are very popular among the web developer community. etc. make it very easy to develop and deploy simple as well as complex web applications.

    Latest versions of Python provide asynchronous programming support. Modern web frameworks leverage this feature to develop fast and high performance web apps and APIs.

    Computer Vision and Image processing

    OpenCV is a widely popular library for capturing and processing images. Image processing algorithms extract information from images, reconstruct image and video data. Computer Vision uses image processing for face detection and pattern recognition. OpenCV is a C++ library. Its Python port is extensively used because of its rapid development feature.

    Some of the application areas of computer vision are robotics, industrial surveillance, automation, and biometrics etc.

    Embedded Systems and IoT

    Micropython (https://micropython.org/), a lightweight version especially for microcontrollers like Arduino. Many automation products, robotics, IoT, and kiosk applications are built around Arduino and programmed with Micropython. Raspberry Pi is also very popular alow cost single board computer used for these type of applications.

    Job Scheduling and Automation

    Python found one of its first applications in automating CRON (Command Run ON) jobs. Certain tasks like periodic data backups, can be written in Python scripts scheduled to be invoked automatically by operating system scheduler.

    Many software products like Maya embed Python API for writing automation scripts (something similar to Excel micros).

    Desktop GUI Applications

    Python is a great option for building ergonomic, attractive, and user-friendly desktop GUI applications. Several graphics libraries, though built in C/C++, have been ported to Python. The popular Qt graphics toolkit is available as a PyQt package in Python. Similarly, WxWidgets has been ported to Python as WxPython. Python’s built-in GUI package, TKinter is a Python interface to the Tk Graphics toolkit.

    Here is a select list of Python GUI libraries:

    • Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python’s standard library.
    • wxPython − This is the Python interface for the wxWidgets GUI toolkit. BitTorrent Client application has been built with wxPython functionality.
    • PyQt – Qt is one of the most popular GUI toolkits. It has been ported to Python as a PyQt5 package. Notable desktop GUI apps that use PyQt include QGIS, Spyder IDE, Calibre Ebook Manager, etc.
    • PyGTK − PyGTK is a set of wrappers written in Python and C for GTK + GUI library. The complete PyGTK tutorial is available here.
    • PySimpleGUI − PySimpleGui is an open-source, cross-platform GUI library for Python. It aims to provide a uniform API for creating desktop GUIs based on Python’s Tkinter, PySide, and WxPython toolkits.
    • Jython − Jython is a Python port for Java, which gives Python scripts seamless access to the Java GUI libraries on the local machine.

    Console-based Applications

    Python is often employed to build CLI (command-line interface) applications. Such scripts can be used to run scheduled CRON jobs such as taking database backups etc. There are many Python libraries that parse the command line arguments. The argparse library comes bundled with Pythons standard library. You can use Click (part of Flask framework) and Typer (included in FastAPI framework) to build console interfaces to the web-based applications built by the respective frameworks. Textual is a rapid development framework to build apps that run inside a terminal as well as browsers.

    CAD Applications

    CAD engineers can take advantage of Python’s versatility to automate repetitive tasks such as drawing shapes and generating reports.

    Autodesk Fusion 360 is a popular CAD software, which has a Python API that allows users to automate tasks and create custom tools. Similarly, SolidWorks has a built-in Python shell that allows users to run Python scripts inside the software.

    CATIA is another very popular CAD software. Along with a VBScript, certain third-party Python libraries that can be used to control CATIA.

    Game Development

    Some popular gaming apps have been built with Python. Examples include BattleField2, The Sims 4, World of Tanks, Pirates of the Caribbean, and more. These apps are built with one of the following Python libraries.

    Pygame is one of the most popular Python libraries used to build engaging computer games. Pygame is an open-source Python library for making multimedia applications like games built on top of the excellent SDL library. It is a cross-platform library, which means you can build a game that can run on any operating system platform.

    Another library Kivy is also widely used to build desktop as well as mobile-based games. Kivy has a multi-touch interface. It is an open-source and cross-platform Python library for rapid development of game applications. Kivy runs on Linux, Windows, OS X, Android, iOS, and Raspberry Pi.

    PyKyra library is based on both SDL (Software and Documentation Localisation) and the Kyra engine. It is one of the fastest game development frameworks. PyKyra supports MPEG , MP3, Ogg Vorbis, Wav, etc., multimedia formats.

  • Hello World Program


    This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of Python built-in print() function to print the string.

    Hello World Program in Python

    Printing “Hello World” is the first program in Python. This program will not take any user input, it will just print text on the output screen. It is used to test if the software needed to compile and run the program has been installed correctly.

    Steps

    The following are the steps to write a Python program to print Hello World –

    • Step 1: Install Python. Make sure that Python is installed on your system or not. If Python is not installed, then install it from here: https://www.python.org/downloads/
    • Step 2: Choose Text Editor or IDE to write the code.
    • Step 3: Open Text Editor or IDE, create a new file, and write the code to print Hello World.
    • Step 4: Save the file with a file name and extension “.py”.
    • Step 5: Compile/Run the program.

    Python Program to Print Hello World

    # Python code to print "Hello World"print("Hello World")

    In the above code, we wrote two lines. The first line is the Python comment that will be ignored by the Python interpreter, and the second line is the print() statement that will print the given message (“Hello World”) on the output screen.

    Output

    Hello World
    

    Different Ways to Write and Execute Hello World Program

    Using Python Interpreter Command Prompt Mode

    It is very easy to display the Hello World message using the Python interpreter. Launch the Python interpreter from a command terminal of your Windows Operating System and issue the print statement from the Python prompt as follows −

    Example

    PS C:\> python
    Python 3.11.2(tags/v3.11.2:878ead1, Feb 72023,16:38:35)[MSC v.193464 bit (AMD64)] on win32
    Type "help","copyright","credits"or"license"for more information.>>>print("Hello World")
    Hello World
    

    Similarly, Hello World message is printed on Linux System.

    Example

    $ python3
    Python 3.10.6(main, Mar 102023,10:55:28)[GCC 11.3.0] on linux
    Type "help","copyright","credits"or"license"for more information.>>>print("Hello World")
    Hello World
    

    Using Python Interpreter Script Mode

    Python interpreter also works in scripted mode. Open any text editor, enter the following text and save as Hello.py

    print("Hello World")

    For Windows OS, open the command prompt terminal (CMD) and run the program as shown below −

    C:\>python hello.py
    

    This will display the following output

    Hello World
    

    To run the program from Linux terminal

    $ python3 hello.py
    

    This will display the following output

    Hello World
    

    Using Shebang #! in Linux Scripts

    In Linux, you can convert a Python program into a self executable script. The first statement in the code should be a shebang #!. It must contain the path to Python executable. In Linux, Python is installed in /usr/bin directory, and the name of the executable is python3. Hence, we add this statement to hello.py file

    #!/usr/bin/python3print("Hello World")

    You also need to give the file executable permission by using the chmod +x command

    $ chmod +x hello.py
    

    Then, you can run the program with following command line −

    $ ./hello.py
    

    This will display the following output

    Hello World
    

    FAQs

    1. Why the first program is called Hello World?

    It is just a simple program to test the basic syntax and compiler/interpreter configuration of Python programming language.

    2. Installation of Python is required to run Hello World program?

    Yes. Python installation is required to run Hello World program.

    3. How do I run a Python program without installing it?

    TutorialsPoint developed an online environment where you can run your codes. You can use the Python online compiler to run your Python programs.

    4. First Program Vs Hello World Program in Python?

    There is no difference. The first program of Python is generally known as the Hello World program.

    5. Which is/are the method to print Hello World or any message?

    You can use the following methods –

    • print() method
    • sys.stdout.write() method by importing the sys module
    • Using python-f string
  • Python vs C++

    Python is a general-purpose, high-level programming language. Python is used for web development, Machine Learning, and other cutting-edge software development. Python is suitable for both new and seasoned C++ and Java programmers. Guido Van Rossam has created Python in 1989 at Netherlands’ National Research Institute. Python was released in 1991.

    C++ is a middle-level, case-sensitive, object-oriented programming language. Bjarne Stroustrup created C++ at Bell Labs. C++ is a platform-independent programming language that works on Windows, Mac OS, and Linux. C++ is near to hardware, allowing low-level programming. This provides a developer control over memory, improved performance, and dependable software.

    Read through this article to get an overview of C++ and Python and how these two programming languages are different from each other.

    What is Python?

    Python is currently one of the most widely used programming languages. It is an interpreted programming language that operates at a high level. When compared to other languages, the learning curve for Python is much lower, and it is also quite straightforward to use.

    Python is the programming language of choice for professionals working in fields such as Artificial IntelligenceMachine Learning (ML)Data Science, the Internet of Things (IoT), etc., because it excels at both scripting applications and as standalone programmes.

    In addition to this, Python is the language of choice because it is easy to learn. Because of its excellent syntax and readability, the amount of money spent on maintenance is decreased. The modularity of the programme and the reusability of the code both contribute to its support for a variety of packages and modules.

    Using Python, we can perform

    • Web development
    • Data analysis and machine learning
    • Automation and scripting
    • Software testing and many moreFeatures
      Here is a list of some of the important features of Python
      Easy to learn Python has a simple structure, few keywords, and a clear syntax. This makes it easy for the student to learn quickly. Code written in Python is easier to read and understand.
      Easy to maintain The source code for Python is pretty easy to keep up with.
      A large standard library Most of Python’s library is easy to move around and works on UNIX, Windows, Mac.
      Portable Python can run on a wide range of hardware platforms, and all of them have the same interface.
      Python Example
      Take a look at the following simple Python program
      a = int(input(“Enter value for a”)) b = int(input(“Enter value for b”)) print(“The number you have entered for a is “, a) print(“The number you have entered for b is “, b)
      In our example, we have taken two variables “a” and “b” and assigning some value to those variables. Note that in Python, we don’t need to declare datatype for variables explicitly, as the PVM will assign datatype as per the user’s input.
      The input() function is used to take input from the user through keyboard.
      In Python, the return type of input() is string only, so we have to convert it explicitly to the type of data which we require. In our example, we have converted to int type explicitly through int( ) function.
      print() is used to display the output.
      Output
      On execution, this Python code will produce the following output
      Enter value for a 10 Enter value for b 20 The number you have entered for a is 10 The number you have entered for b is
    • 20
    • What is C++?
      C++ is a statically typed, compiled, multi-paradigm, general-purpose programming language with a steep learning curve. Video games, desktop apps, and embedded systems use it extensively. C++ is so compatible with C that it can build practically all C source code without any changes. Object-oriented programming makes C++ a better-structured and safer language than C.
      Features
      Let’s see some features of C++ and the reason of its popularity.
      Middle-level language It’s a middle-level language since it can be used for both systems development and large-scale consumer applications like Media Players, Photoshop, Game Engines, etc.
      Execution Speed C++ code runs quickly. Because it’s compiled and uses procedures extensively. Garbage collection, dynamic typing, and other modern features impede program execution.
      Object-oriented language Object-oriented programming is flexible and manageable. Large apps are possible. Growing code makes procedural code harder to handle. C++’s key advantage over C.
      Extensive Library Support C++ has a vast library. Third-party libraries are supported for fast development.
      C++ Example
      Let’s understand the syntax of C++ through an example written below.
      #include using namespace std; int main() { int a, b; cout << “Enter The value for variable a \n”; cin >> a; cout << “Enter The value for variable b”; cin >> b; cout << “The value of a is “<< a << “and” << b; return 0; }
      In our example, we are taking input for two variables “a” and “b” from the user through the keyboard and displaying the data on the console.
    • Output
      On execution, it will produce the following output
      Enter The value for variable a 10 Enter The value for variable b 20 The value of a is 10 and 20
      Comparison Between Python and C++ across Various Aspects
      Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this tutorial, we shall take a closure look at their characteristic features which differentiate one from another.
      Compiled vs Interpreted
      Like C, C++ is also a compiler-based language. A compiler translates the entire code in a machine language code specific to the operating system in use and processor architecture.
      Python is interpreter-based language. The interpreter executes the source code line by line.
      Cross platform
      When a C++ source code such as hello.cpp is compiled on Linux, it can be only run on any other computer with Linux operating system. If required to run on other OS, it needs to be compiled.
      Python interpreter doesn’t produce compiled code. Source code is converted to byte code every time it is run on any operating system without any changes or additional steps.
      Portability
      Python code is easily portable from one OS to other. C++ code is not portable as it must be recompiled if the OS changes.
      Speed of Development
      C++ program is compiled to the machine code. Hence, its execution is faster than interpreter based language.
      Python interpreter doesn’t generate the machine code. Conversion of intermediate byte code to machine language is done on each execution of program.
      If a program is to be used frequently, C++ is more efficient than Python.
      Easy to Learn
      Compared to C++, Python has a simpler syntax. Its code is more readable. Writing C++ code seems daunting in the beginning because of complicated syntax rule such as use of curly braces and semicolon for sentence termination.
      Python doesn’t use curly brackets for marking a block of statements. Instead, it uses indents. Statements of similar indent level mark a block. This makes a Python program more readable.
      Static vs Dynamic Typing
      C++ is a statically typed language. The type of variables for storing data need to be declared in the beginning. Undeclared variables can’t be used. Once a variable is declared to be of a certain type, value of only that type can be stored in it.
      Python is a dynamically typed language. It doesn’t require a variable to be declared before assigning it a value. Since, a variable may store any type of data, it is called dynamically typed.
      OOP Concepts
      Both C++ and Python implement object oriented programming concepts. C++ is closer to the theory of OOP than Python. C++ supports the concept of data encapsulation as the visibility of the variables can be defined as public, private and protected.
      Python doesn’t have the provision of defining the visibility. Unlike C++, Python doesn’t support method overloading. Because it is dynamically typed, all the methods are polymorphic in nature by default.
      C++ is in fact an extension of C. One can say that additional keywords are added in C so that it supports OOP. Hence, we can write a C type procedure oriented program in C++.
      Python is completely object oriented language. Python’s data model is such that, even if you can adapt a procedure oriented approach, Python internally uses object-oriented methodology.
      Garbage Collection
      C++ uses the concept of pointers. Unused memory in a C++ program is not cleared automatically. In C++, the process of garbage collection is manual. Hence, a C++ program is likely to face memory related exceptional behavior.
      Python has a mechanism of automatic garbage collection. Hence, Python program is more robust and less prone to memory related issues.
      Application Areas
      Because C++ program compiles directly to machine code, it is more suitable for systems programming, writing device drivers, embedded systems and operating system utilities.
      Python program is suitable for application programming. Its main area of application today is data science, machine learning, API development etc.
      Difference Between Python and C++
      The following table summarizes the differences between Python and C++
      Criteria
      Python
      C++
      Execution
      Python is an interpreted-based programming language. Python programs are interpreted by an interpreter.
      C++ is a compiler-based programming language. C++ programs are compiled by a compiler.
      Typing
      Python is a dynamic-typed language.
      C++ is a static-typed language.
      Portability
      Python is a highly portable language, code written and executed on a system can be easily run on another system.
      C++ is not a portable language, code written and executed on a system cannot be run on another system without making changes.
      Garbage collection
      Python provides a garbage collection feature. You do not need to worry about the memory management. It is automatic in Python.
      C++ does not provide garbage collection. You have to take care of freeing memories. It is manual in C++.
      Syntax
      Python’s syntaxes are very easy to read, write, and understand.
      C++’s syntaxes are tedious.
      Performance
      Python’s execution performance is slower than C++’s.
      C++ codes are faster than Python codes.
      Application areas
      Python’s application areas are machine learning, web applications, and more.
      C++’s application areas are embedded systems, device drivers, and more.
  • Features

    Python – FeaturesPython is a feature-rich, high-level, interpreted, interactive, and object-oriented scripting language. Python is a versatile and very popular programming language due to its features such as readability, simplicity, extensive libraries, and many more. In this tutorial, we will learn about the various features of Python that make it a powerful and versatile programming language.

    Python Important Features

    Python’s most important features are as follows:

    Easy to Learn

    This is one of the most important reasons for the popularity of Python. Python has a limited set of keywords. Its features such as simple syntax, usage of indentation to avoid clutter of curly brackets and dynamic typing that doesn’t necessitate prior declaration of variable help a beginner to learn Python quickly and easily.

    Dynamically Typed

    Python is a dynamically typed programming language. In Python, you don’t need to specify the variable time at the time of the variable declaration. The types are specified at the runtime based on the assigned value due to its dynamically typed feature.

    Interpreter Based

    Instructions in any programming languages must be translated into machine code for the processor to execute them. Programming languages are either compiler based or interpreter based.

    In case of a compiler, a machine language version of the entire source program is generated. The conversion fails even if there is a single erroneous statement. Hence, the development process is tedious for the beginners. The C family languages (including CC++JavaC# etc) are compiler based.

    Python is an interpreter based language. The interpreter takes one instruction from the source code at a time, translates it into machine code and executes it. Instructions before the first occurrence of error are executed. With this feature, it is easier to debug the program and thus proves useful for the beginner level programmer to gain confidence gradually. Python therefore is a beginner-friendly language.

    Interactive

    Standard Python distribution comes with an interactive shell that works on the principle of REPL (Read Evaluate Print Loop). The shell presents a Python prompt >>>. You can type any valid Python expression and press Enter. Python interpreter immediately returns the response and the prompt comes back to read the next expression.

    >>>2*3+17>>>print("Hello World")
    Hello World
    

    The interactive mode is especially useful to get familiar with a library and test out its functionality. You can try out small code snippets in interactive mode before writing a program.

    Multi-paradigm

    Python is a completely object-oriented language. Everything in a Python program is an object. However, Python conveniently encapsulates its object orientation to be used as an imperative or procedural language such as C. Python also provides certain functionality that resembles functional programming. Moreover, certain third-party tools have been developed to support other programming paradigms such as aspect-oriented and logic programming.

    Standard Library

    Even though it has a very few keywords (only Thirty Five), Python software is distributed with a standard library made of large number of modules and packages. Thus Python has out of box support for programming needs such as serialization, data compression, internet data handling, and many more. Python is known for its batteries included approach.

    Some of the Python’s popular modules are:

    Open Source and Cross Platform

    Python’s standard distribution can be downloaded from https://www.python.org/downloads/ without any restrictions. You can download pre-compiled binaries for various operating system platforms. In addition, the source code is also freely available, which is why it comes under open source category.

    Python software (along with the documentation) is distributed under Python Software Foundation License. It is a BSD style permissive software license and compatible to GNU GPL (General Public License).

    Python is a cross-platform language. Pre-compiled binaries are available for use on various operating system platforms such as WindowsLinux, Mac OS, Android OS. The reference implementation of Python is called CPython and is written in C. You can download the source code and compile it for your OS platform.

    A Python program is first compiled to an intermediate platform independent byte code. The virtual machine inside the interpreter then executes the byte code. This behaviour makes Python a cross-platform language, and thus a Python program can be easily ported from one OS platform to other.

    GUI Applications

    Python’s standard distribution has an excellent graphics library called TKinter. It is a Python port for the vastly popular GUI toolkit called TCL/Tk. You can build attractive user-friendly GUI applications in Python. GUI toolkits are generally written in C/C++. Many of them have been ported to Python. Examples are PyQtWxWidgetsPySimpleGUI etc.

    Database Connectivity

    Almost any type of database can be used as a backend with the Python application. DB-API is a set of specifications for database driver software to let Python communicate with a relational database. With many third party libraries, Python can also work with NoSQL databases such as MongoDB.

    Extensible

    The term extensibility implies the ability to add new features or modify existing features. As stated earlier, CPython (which is Python’s reference implementation) is written in C. Hence one can easily write modules/libraries in C and incorporate them in the standard library. There are other implementations of Python such as Jython (written in Java) and IPython (written in C#). Hence, it is possible to write and merge new functionality in these implementations with Java and C# respectively.

    Active Developer Community

    As a result of Python’s popularity and open-source nature, a large number of Python developers often interact with online forums and conferences. Python Software Foundation also has a significant member base, involved in the organization’s mission to “Promote, Protect, and Advance the Python Programming Language

    Python also enjoys a significant institutional support. Major IT companies Google, Microsoft, and Meta contribute immensely by preparing documentation and other resources.

    Apart from the above-mentioned features, Python has another big list of good features, few are listed below −

    • It supports functional and structured programming methods as well as OOP.
    • It can be used as a scripting language or can be compiled to byte-code for building large applications.
    • It provides very high-level dynamic data types and supports dynamic type checking.
    • It supports automatic garbage collection.
    • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
  • History of Python

    Python was developed by Guido van Rossum (a Dutch programmer) in the late 1980s and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

    Python is derived from many other languages, including ABC, Modula-3, CC++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Guido van Rossum wanted Python to be a high-level language that was powerful yet readable and easy to use.

    Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).

    For many uninitiated people, the word Python is related to a species of snake. Rossum though attributes the choice of the name Python to a popular comedy series Monty Python’s Flying Circus on BBC.

    Being the principal architect of Python, the developer community conferred upon him the title of Benevolent Dictator for Life (BDFL). However, in 2018, Rossum relinquished the title. Thereafter, the development and distribution of the reference implementation of Python is handled by a nonprofit organization Python Software Foundation.

    Who Invented Python?

    Python was invented by a Dutch Programmer Guido Van Rossum in the late 1980s. He began working on Python in December 1989 as a hobby project while working at the Centrum Wiskunde & Informatica (CWI) in the Netherlands. Python’s first version (0.9.0) was released in 1991.

    Evolution of Python The Major Python Versions

    Following are the important stages in the history of Python −

    Python 0.9.0

    Python’s first published version is 0.9. It was released in February 1991. It consisted of features such as classes with inheritance, exception handling, and core data types like lists and dictionaries..

    Python 1.0

    In January 1994, version 1.0 was released, armed with functional programming tools, features like support for complex numbers etc and module system which allows a better code organization and reuse.

    Python 2.0

    Next major version − Python 2.0 was launched in October 2000. Many new features such as list comprehension, garbage collection and Unicode support were included with it. Throughout the 2000s, Python 2.x became the dominant version, gaining traction in industries ranging from web development to scientific research. Various useful libraries like like NumPy, SciPy, and Django were also developed.

    Python 3.0

    Python 3.0, a completely revamped version of Python was released in December 2008. The primary objective of this revamp was to remove a lot of discrepancies that had crept in Python 2.x versions. Python 3 was backported to Python 2.6. It also included a utility named as python2to3 to facilitate automatic translation of Python 2 code to Python 3. Python 3 provided new syntax, unicode support and Improved integer division.

    EOL for Python 2.x

    Even after the release of Python 3, Python Software Foundation continued to support the Python 2 branch with incremental micro versions till 2019. However, it decided to discontinue the support by the end of year 2020, at which time Python 2.7.17 was the last version in the branch.

    Current Version of Python

    Meanwhile, more and more features have been incorporated into Python’s 3.x branch. As of date, Python 3.11.2 is the current stable version, released in February 2023.

    What’s New in Python 3.11?

    One of the most important features of Python’s version 3.11 is the significant improvement in speed. According to Python’s official documentation, this version is faster than the previous version (3.10) by up to 60%. It also states that the standard benchmark suite shows a 25% faster execution rate.

    • Python 3.11 has a better exception messaging. Instead of generating a long traceback on the occurrence of an exception, we now get the exact expression causing the error.
    • As per the recommendations of PEP 678, the add_note() method is added to the BaseException class. You can call this method inside the except clause and pass a custom error message.
    • It also adds the cbroot() function in the maths module. It returns the cube root of a given number.
    • A new module tomllib is added in the standard library. TOML (Tom’s Obvious Minimal Language) can be parsed with tomlib module function.

    Python in the Future

    Python is evolving everyday where Python 3.x receiving regular updates. Python’s developers community is focusing on performance improvements making it more efficient while retaining its ease of use.

    Python is being heavily used for machine learning, AI, and data science, so for sure its future remains bright. It’s role in these rapidly growing fields ensures that Python will stay relevant for years.

    Python is also increasingly becoming the first programming language taught in schools and universities worldwide, solidifying its place in the tech landscape.

    Frequently Asked Questions About Python History

    1. Who created Python?

    Python created by Guido Van Rossum, a Dutch Programmer.

    2. Why Python is called Python?

    Python does not have any relation to Snake. The name of the Python programming language was inspired by a British Comedy Group Monty Python.

    3. When was Python’s first version released?

    Python’s first version was released in February 1991.

    4. What was the first version of Python?

    Python’s first version was Python 0.9.0

    5. When was Python 3.0 version released?

    Python 3.0 version was released in December 2008.

  • Higher order functions

    in Python allows you to manipulate functions for increasing the flexibility and re-usability of your code. You can create higher-order functions using nested scopes or callable objects.

    Additionally, the functools module provides utilities for working with higher-order functions, making it easier to create decorators and other function-manipulating constructs. This tutorial will explore the concept of higher-order functions in Python and demonstrate how to create them.

    What is a Higher-Order Function?

    A higher-order function is a function that either, takes one or more functions as arguments or returns a function as its result. Below you can observe the some of the properties of the higher-order function in Python −

    • A function can be stored in a variable.
    • A function can be passed as a parameter to another function.
    • A high order functions can be stored in the form of lists, hash tables, etc.
    • Function can be returned from a function.

    To create higher-order function in Python you can use nested scopes or callable objects. Below we will discuss about them briefly.

    Advertisement

    Creating Higher Order Function with Nested Scopes

    One way to defining a higher-order function in Python is by using nested scopes. This involves defining a function within another function and returns the inner function.

    Example

    Let’s observe following example for creating a higher order function in Python. In this example, the multiplier function takes one argument, a, and returns another function multiply, which calculates the value a * b

    defmultiplier(a):# Nested function with second number   defmultiply(b):# Multiplication of two numbers  return a * b 
       return multiply   
    
    # Assigning nested multiply function to a variable  
    multiply_second_number = multiplier(5)# Using variable as high order function  
    Result = multiply_second_number(10)# Printing result  print("Multiplication of Two numbers is: ", Result)

    Output

    On executing the above program, you will get the following results −

    Multiplication of Two numbers is:  50
    

    Creating Higher-Order Functions with Callable Objects

    Another approach to create higher-order functions is by using callable objects. This involves defining a class with a __call__ method.

    Example

    Here is the another approach to creating higher-order functions is using callable objects.

    classMultiplier:def__init__(self, factor):
    
      self.factor = factor
    def__call__(self, x):return self.factor * x # Create an instance of the Multiplier class multiply_second_number = Multiplier(2)# Call the Multiplier object to computes factor * x Result = multiply_second_number(100)# Printing result print("Multiplication of Two numbers is: ", Result)

    Output

    On executing the above program, you will get the following results −

    Multiplication of Two numbers is:  200
    

    Higher-order functions with the ‘functools’ Module

    The functools module provides higher-order functions that act on or return other functions. Any callable object can be treated as a function for the purposes of this module.

    Working with Higher-order functions using the wraps()

    In this example, my_decorator is a higher-order function that modifies the behavior of invite function using the functools.wraps() function.

    import functools
    
    defmy_decorator(f):@functools.wraps(f)defwrapper(*args,**kwargs):print("Calling", f.__name__)return f(*args,**kwargs)return wrapper
    
    @my_decoratordefinvite(name):print(f"Welcome to, {name}!")
    
    invite("Tutorialspoint")

    Output

    On executing the above program, you will get the following results −

    Calling invite
    Welcome to, Tutorialspoint!
    

    Working with Higher-order functions using the partial()

    The partial() function of the functools module is used to create a callable ‘partial’ object. This object itself behaves like a function. The partial() function receives another function as argument and freezes some portion of a functions arguments resulting in a new object with a simplified signature.

    Example

    In following example, a user defined function myfunction() is used as argument to a partial function by setting default value on one of the arguments of original function.

    import functools
    defmyfunction(a,b):return a*b
    
    partfunction = functools.partial(myfunction,b =10)print(partfunction(10))

    Output

    On executing the above program, you will get the following results −

    100
    

    Working with Higher-order functions using the reduce()

    Similar to the above approach the functools module provides the reduce() function, that receives two arguments, a function and an iterable. And, it returns a single value. The argument function is applied cumulatively two arguments in the list from left to right. Result of the function in first call becomes first argument and third item in list becomes second. This is repeated till list is exhausted.

    Example

    import functools
    defmult(x,y):return x*y
    
    # Define a number to calculate factorial
    n =4
    num = functools.reduce(mult,range(1, n+1))print(f'Factorial of {n}: ',num)

    Output

    On executing the above program, you will get the following results −

    Factorial of 4:  24
  • Reverse an Array in Java

    In this tutorial, we will discuss how one can reverse an array in Java. In the input, an integer array is given, and the task is to reverse the input array. Reversing an array means the last element of the input array should be the first element of the reversed array, the second last element of the input array should be the second element of the reversed array, and so on. Observe the following examples.

    Example 1:

    Input:

    arr[] = {1, 2, 3, 4, 5, 6, 7, 8}

    Output

    arr[] = {8, 7, 6, 5, 4, 3, 2, 1}

    Example 2:

    Input:

    arr[] = {4, 8, 3, 9, 0, 1}

    Output:

    arr[] = {1, 0, 9, 3, 8, 4}

    Approach 1: Using an auxiliary array

    We can traverse the array from end to beginning, i.e., in reverse order, and store the element pointed by the loop index in the auxiliary array. The auxiliary array now contains the elements of the input array in reversed order. After that, we can display the auxiliary array on the console. See the following program.

    FileName: ReverseArr.java

    1. public class ReverseArr  
    2. {  
    3. // method for reversing an array  
    4. public int[]  reverseArray(int arr[])  
    5. {  
    6.     // computing the size of the array arr  
    7.     int size = arr.length;  
    8.       
    9.     // auxiliary array for reversing the   
    10.     // elements of the array arr  
    11.     int temp[] = new int[size];  
    12.       
    13.     int index = 0;  
    14.     for(int i = size – 1; i >= 0; i–)  
    15.     {  
    16.         temp[i] = arr[index];  
    17.         index = index + 1;  
    18.     }  
    19.       
    20.     return temp;  
    21.       
    22. }  
    23.   
    24. // main method  
    25. public static void main(String argvs[])   
    26. {  
    27.   // creating an object of the class ReverseArr  
    28.   ReverseArr obj = new ReverseArr();  
    29.     
    30.   // input array – 1  
    31.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    32.     
    33.   // computing the length  
    34.   int len = arr.length;  
    35.   int ans[] = obj.reverseArray(arr);  
    36.     
    37.   System.out.println(“For the input array: “);  
    38.   for(int  i = 0; i < len; i++)  
    39.   {  
    40.      System.out.print(arr[i] + ” “);  
    41.   }  
    42.     
    43.   System.out.println();  
    44.   System.out.println(“The reversed array is: “);  
    45.   for(int  i = 0; i < len; i++)  
    46.   {  
    47.      System.out.print(ans[i] + ” “);  
    48.   }  
    49.     
    50.   System.out.println(“\n “);  
    51.     
    52.   // input array – 2  
    53.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    54.     
    55.   // computing the length  
    56.   len = arr1.length;  
    57.   int ans1[] = obj.reverseArray(arr1);  
    58.     
    59.   System.out.println(“For the input array: “);  
    60.   for(int  i = 0; i < len; i++)  
    61.   {  
    62.      System.out.print(arr1[i] + ” “);  
    63.   }  
    64.     
    65.   System.out.println();  
    66.   System.out.println(“The reversed array is: “);  
    67.   for(int  i = 0; i < len; i++)  
    68.   {  
    69.      System.out.print(ans1[i] + ” “);  
    70.   }  
    71.         
    72.    
    73. }  
    74. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: A for loop is required to reverse the array, which makes the time complexity of the program O(n). Also, an auxiliary array is required to reverse the array making the space complexity of the program O(n), where n is the total number of elements present in the array.

    Approach 2: Using Two Pointers

    We can also use two pointers to reverse the input array. The first pointer will go to the first element of the array. The second pointer will point to the last element of the input array. Now we will start swapping elements pointed by these two pointers. After swapping, the second pointer will move in the leftward direction, and the first pointer will move in the rightward direction. When these two pointers meet or cross each other, we stop the swapping, and the array we get is the reversed array of the input array.

    FileName: ReverseArr1.java

    1. public class ReverseArr1  
    2. {  
    3. // method for reversing an array  
    4. public int[]  reverseArray(int arr[])  
    5. {  
    6.     // computing the size of the array arr  
    7.     int size = arr.length;  
    8.       
    9.     // two pointers for reversing   
    10.     // the input array  
    11.     int ptr1 = 0;  
    12.     int ptr2 = size – 1;  
    13.       
    14.     // reversing the input array  
    15.     // using a while loop  
    16.     while(ptr1 < ptr2)  
    17.     {  
    18.         int temp = arr[ptr1];  
    19.         arr[ptr1] = arr[ptr2];  
    20.         arr[ptr2] = temp;  
    21.           
    22.         ptr1 = ptr1 + 1;  
    23.         ptr2 = ptr2 – 1;  
    24.     }  
    25.       
    26.     return arr;  
    27.       
    28. }  
    29.   
    30. // main method  
    31. public static void main(String argvs[])   
    32. {  
    33.   // creating an object of the class ReverseArr1  
    34.   ReverseArr1 obj = new ReverseArr1();  
    35.     
    36.   // input array – 1  
    37.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    38.     
    39.   // computing the length  
    40.   int len = arr.length;  
    41.     
    42.     
    43.   System.out.println(“For the input array: “);  
    44.   for(int  i = 0; i < len; i++)  
    45.   {  
    46.      System.out.print(arr[i] + ” “);  
    47.   }  
    48.     
    49.   int ans[] = obj.reverseArray(arr);  
    50.     
    51.   System.out.println();  
    52.   System.out.println(“The reversed array is: “);  
    53.   for(int  i = 0; i < len; i++)  
    54.   {  
    55.      System.out.print(ans[i] + ” “);  
    56.   }  
    57.     
    58.   System.out.println(“\n “);  
    59.     
    60.   // input array – 2  
    61.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    62.     
    63.   // computing the length  
    64.   len = arr1.length;  
    65.     
    66.     
    67.   System.out.println(“For the input array: “);  
    68.   for(int  i = 0; i < len; i++)  
    69.   {  
    70.      System.out.print(arr1[i] + ” “);  
    71.   }  
    72.     
    73.   int ans1[] = obj.reverseArray(arr1);  
    74.     
    75.   System.out.println();  
    76.   System.out.println(“The reversed array is: “);  
    77.   for(int  i = 0; i < len; i++)  
    78.   {  
    79.      System.out.print(ans1[i] + ” “);  
    80.   }  
    81.         
    82.    
    83. }  
    84. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: The time complexity of the program is the same as the previous program. There is no extra space used in the program, making the space complexity of the program O(1).

    Approach 3: Using Stack

    Since a Stack works on the LIFO (Last In First Out) principle, it can be used to reverse the input array. All we have to do is to put all the elements of the input array in the stack, starting from left to right. We will do it using a loop.

    FileName: ReverseArr2.java

    1. // importing Stack  
    2. import java.util.Stack;  
    3.   
    4.   
    5. public class ReverseArr2  
    6. {  
    7. // method for reversing an array  
    8. public int[]  reverseArray(int arr[])  
    9. {  
    10.     // computing the size of the array arr  
    11.     int size = arr.length;  
    12.       
    13.     Stack<Integer> stk = new Stack<Integer>();  
    14.       
    15.     // pusing all the elements into stack  
    16.     // starting from left  
    17.     for(int i = 0; i < size; i++)  
    18.     {  
    19.         stk.push(arr[i]);  
    20.     }  
    21.       
    22.     int i = 0;  
    23.     while(!stk.isEmpty())  
    24.     {  
    25.         int ele = stk.pop();  
    26.         arr[i] = ele;  
    27.         i = i + 1;  
    28.     }  
    29.       
    30.     return arr;  
    31.       
    32. }  
    33.   
    34. // main method  
    35. public static void main(String argvs[])   
    36. {  
    37.   // creating an object of the class ReverseArr2  
    38.   ReverseArr2 obj = new ReverseArr2();  
    39.     
    40.   // input array – 1  
    41.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    42.     
    43.   // computing the length  
    44.   int len = arr.length;  
    45.     
    46.     
    47.   System.out.println(“For the input array: “);  
    48.   for(int  i = 0; i < len; i++)  
    49.   {  
    50.      System.out.print(arr[i] + ” “);  
    51.   }  
    52.     
    53.   int ans[] = obj.reverseArray(arr);  
    54.     
    55.   System.out.println();  
    56.   System.out.println(“The reversed array is: “);  
    57.   for(int  i = 0; i < len; i++)  
    58.   {  
    59.      System.out.print(ans[i] + ” “);  
    60.   }  
    61.     
    62.   System.out.println(“\n “);  
    63.     
    64.   // input array – 2  
    65.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    66.     
    67.   // computing the length  
    68.   len = arr1.length;  
    69.     
    70.     
    71.   System.out.println(“For the input array: “);  
    72.   for(int  i = 0; i < len; i++)  
    73.   {  
    74.      System.out.print(arr1[i] + ” “);  
    75.   }  
    76.     
    77.   int ans1[] = obj.reverseArray(arr1);  
    78.     
    79.   System.out.println();  
    80.   System.out.println(“The reversed array is: “);  
    81.   for(int  i = 0; i < len; i++)  
    82.   {  
    83.      System.out.print(ans1[i] + ” “);  
    84.   }  
    85.         
    86.    
    87. }  
    88. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: The time complexity of the program is the same as the previous program. There is stack used in the program, making the space complexity of the program O(n).

    Using Recursion

    Using recursion also, we can achieve the same result. Observe the following.

    FileName: ReverseArr3.java

    1. // importing ArrayList  
    2. import java.util.ArrayList;  
    3.   
    4.   
    5. public class ReverseArr3  
    6. {  
    7. ArrayList<Integer> reverseArr;  
    8.   
    9. // constructor of the class  
    10. ReverseArr3()  
    11. {  
    12. reverseArr = new  ArrayList<Integer>();  
    13. }  
    14.   
    15. // method for reversing an array  
    16. public void  reverseArray(int arr[], int i, int size)  
    17. {  
    18. // dealing with the base case  
    19. if(i >= size)  
    20. {  
    21.     return;  
    22. }  
    23.   
    24. // recursively calling the method  
    25. reverseArray(arr, i + 1, size);  
    26. reverseArr.add(arr[i]);  
    27.       
    28. }  
    29.   
    30. // main method  
    31. public static void main(String argvs[])   
    32. {  
    33.   // creating an object of the class ReverseArr3  
    34.   ReverseArr3 obj = new ReverseArr3();  
    35.     
    36.   // input array – 1  
    37.   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    38.     
    39.   // computing the length  
    40.   int len = arr.length;  
    41.     
    42.     
    43.   System.out.println(“For the input array: “);  
    44.   for(int  i = 0; i < len; i++)  
    45.   {  
    46.      System.out.print(arr[i] + ” “);  
    47.   }  
    48.     
    49.   obj.reverseArray(arr, 0 , len);  
    50.     
    51.   System.out.println();  
    52.   System.out.println(“The reversed array is: “);  
    53.   for(int  i = 0; i < len; i++)  
    54.   {  
    55.      System.out.print(obj.reverseArr.get(i) + ” “);  
    56.   }  
    57.     
    58.   System.out.println(“\n “);  
    59.     
    60.   obj = new ReverseArr3();  
    61.     
    62.   // input array – 2  
    63.   int arr1[] = {4, 8, 3, 9, 0, 1};  
    64.     
    65.   // computing the length  
    66.   len = arr1.length;  
    67.     
    68.     
    69.   System.out.println(“For the input array: “);  
    70.   for(int  i = 0; i < len; i++)  
    71.   {  
    72.      System.out.print(arr1[i] + ” “);  
    73.   }  
    74.     
    75.   obj.reverseArray(arr1, 0, len);  
    76.     
    77.   System.out.println();  
    78.   System.out.println(“The reversed array is: “);  
    79.   for(int  i = 0; i < len; i++)  
    80.   {  
    81.       System.out.print(obj.reverseArr.get(i) + ” “);  
    82.   }  
    83.         
    84.    
    85. }  
    86. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Explanation: The statement reverseArr.add(arr[i]); is written after the recursive call goes in the stack (note that the stack is implicit in this case). So, when the base case is hit in the recursive call, stack unwinding happens, and whatever is there in the stack pops out. The last element goes into the stack during the last recursive call. Therefore, the last element is popped out first. Then the penultimate element is popped out, and so on. The statement reverseArr.add(arr[i]); stores that popped element. In the end, we are displaying the elements that are stored in the list reverseArr.

    Complexity Analysis: Same as the first program of approach-3.

    Approach 4: Using Collections.reverse() method

    The build method Collections.reverse() can be used to reverse the list. The use of it is shown in the following program.

    FileName: ReverseArr4.java

    1. // importing Collections, Arrays, ArrayList & List  
    2. import java.util.Collections;  
    3. import java.util.Arrays;  
    4. import java.util.List;  
    5. import java.util.ArrayList;  
    6.   
    7. public class ReverseArr4  
    8. {  
    9.   
    10. // method for reversing an array  
    11. public List<Integer>  reverseArray(Integer arr[])  
    12. {  
    13. List<Integer> l = (Arrays.asList(arr));  
    14. Collections.reverse(l);  
    15. return l;  
    16. }  
    17.   
    18. // main method  
    19. public static void main(String argvs[])   
    20. {  
    21.   // creating an object of the class ReverseArr4  
    22.   ReverseArr4 obj = new ReverseArr4();  
    23.     
    24.   // input array – 1  
    25.   Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8};  
    26.     
    27.   // computing the length  
    28.   int len = arr.length;  
    29.     
    30.     
    31.   System.out.println(“For the input array: “);  
    32.   for(int  i = 0; i < len; i++)  
    33.   {  
    34.      System.out.print(arr[i] + ” “);  
    35.   }  
    36.     
    37.   List<Integer> ans = obj.reverseArray(arr);  
    38.     
    39.   System.out.println();  
    40.   System.out.println(“The reversed array is: “);  
    41.   for(int  i = 0; i < len; i++)  
    42.   {  
    43.      System.out.print(ans.get(i) + ” “);  
    44.   }  
    45.     
    46.   System.out.println(“\n “);  
    47.   
    48.   // input array – 2  
    49.   Integer arr1[] = {4, 8, 3, 9, 0, 1};  
    50.     
    51.   // computing the length  
    52.   len = arr1.length;  
    53.     
    54.     
    55.   System.out.println(“For the input array: “);  
    56.   for(int  i = 0; i < len; i++)  
    57.   {  
    58.      System.out.print(arr1[i] + ” “);  
    59.   }  
    60.     
    61.   ans = obj.reverseArray(arr1);  
    62.     
    63.   System.out.println();  
    64.   System.out.println(“The reversed array is: “);  
    65.   for(int  i = 0; i < len; i++)  
    66.   {  
    67.       System.out.print(ans.get(i) + ” “);  
    68.   }  
    69.         
    70.    
    71. }  
    72. }  

    Output:

    For the input array:
    1 2 3 4 5 6 7 8
    The reversed array is:
    8 7 6 5 4 3 2 1
    
    For the input array:
    4 8 3 9 0 1
    The reversed array is:
    1 0 9 3 8 4
    

    Complexity Analysis: The program uses Collections.reverse() method that reverses the list in linear time, making the time complexity of the program O(n). The program uses using list, making the space complexity of the program O(n), where n is the total number of elements present in the array.

    Note 1: Collections.reverse() method is also used to reverse the linked list.

    Note 2: All the approaches discussed above are applicable to different data types too.

    Approach 5: Using StringBuilder.append() method

    It is evident from the heading that this approach is applicable to string arrays. Using the StringBuilder.append() method, we can reverse the string array. All we have to do is to start appending the string elements of the array from the last to the beginning.

    FileName: ReverseArr5.java

    1. import java.util.*;  
    2.   
    3. public class ReverseArr5  
    4. {  
    5.   
    6. // method for reversing an array  
    7. public String[]  reverseArray(String arr[])  
    8. {  
    9. StringBuilder reversedSB = new StringBuilder();  
    10.   
    11. for (int j = arr.length; j > 0; j–)   
    12. {  
    13.   reversedSB.append(arr[j – 1]).append(” “);  
    14. };  
    15.   
    16. String[] reversedArr = reversedSB.toString().split(” “);  
    17. return reversedArr;  
    18. }  
    19.   
    20. // main method  
    21. public static void main(String argvs[])   
    22. {  
    23.   // creating an object of the class ReverseArr5  
    24.   ReverseArr5 obj = new ReverseArr5();  
    25.     
    26.   // input array – 1  
    27.   String arr[] = {“javaTpoint”, “is”, “the”, “best”, “website”};  
    28.     
    29.   // computing the length  
    30.   int len = arr.length;  
    31.     
    32.     
    33.   System.out.println(“For the input array: “);  
    34.   for(int  i = 0; i < len; i++)  
    35.   {  
    36.      System.out.print(arr[i] + ” “);  
    37.   }  
    38.     
    39.   String[] ans = obj.reverseArray(arr);  
    40.     
    41.   System.out.println();  
    42.   System.out.println(“The reversed array is: “);  
    43.   for(int  i = 0; i < len; i++)  
    44.   {  
    45.      System.out.print(ans[i] + ” “);  
    46.   }  
    47.     
    48.   System.out.println(“\n “);  
    49.   
    50.   // input array – 2  
    51.   String arr1[] = {“India”, “is”, “my”, “country”};  
    52.     
    53.   // computing the length  
    54.   len = arr1.length;  
    55.     
    56.     
    57.   System.out.println(“For the input array: “);  
    58.   for(int  i = 0; i < len; i++)  
    59.   {  
    60.      System.out.print(arr1[i] + ” “);  
    61.   }  
    62.     
    63.   String[] ans1 = obj.reverseArray(arr1);  
    64.     
    65.   System.out.println();  
    66.   System.out.println(“The reversed array is: “);  
    67.   for(int  i = 0; i < len; i++)  
    68.   {  
    69.       System.out.print(ans1[i] + ” “);  
    70.   }  
    71.         
    72.    
    73. }  
    74. }  

    Output:

    For the input array:
    javaTpoint is the best website
    The reversed array is:
    website best the is javaTpoint
    
    For the input array:
    India is my country
    The reversed array is:
    country my is India
    
  • String Arrays in Java

    An Array is an essential and most used data structure in Java. It is one of the most used data structure by programmers due to its efficient and productive nature; The Array is a collection of similar data type elements. It uses a contiguous memory location to store the elements.

    What is a String Array?

    A String Array is an Array of a fixed number of String values. A String is a sequence of characters. Generally, a string is an immutable object, which means the value of the string can not be changed. The String Array works similarly to other data types of Array.

    Similar to arrays, in string array only a fixed set of elements can be stored. It is an index-based data structure, which starts from the 0th position. The first element will take place in Index 0, and the 2nd element will take place in Index 1, and so on.

    The main method {Public static void main[ String [] args]; } in Java is also an String Array.

    Consider the below points about the String Array:

    • It is an object of the Array.
    • It can be declared by the two methods; by specifying the size or without specifying the size.
    • It can be initialized either at the time of declaration or by populating the values after the declaration.
    • The elements can be added to a String Array after declaring it.
    • The String Array can be iterated using the for loop.
    • The searching and sorting operation can be performed on the String Array.

    Declaration:

    The Array declaration is of two types, either we can specify the size of the Array or without specifying the size of the Array. A String Array can be declared as follows:

    1. String[] stringArray1   //Declaration of the String Array without specifying the size  
    2. String[] stringArray2 = new String[2];   //Declarartion by specifying the size  

    Another way of declaring the Array is String strArray[], but the above-specified methods are more efficient and recommended.

    Initialization:

    The String Array can be initialized easily. Below is the initialization of the String Array:

    1. 1. String[] strAr1=new String[] {“Ani”, “Sam”, “Joe”}; //inline initialization  
    2. 2. String[] strAr2 = {“Ani”, “Sam”, ” Joe”};  
    3. 3. String[] strAr3= new String[3]; //Initialization after declaration with specific size  
    4.    strAr3[0]= “Ani”;  
    5.    strAr3[1]= “Sam”;  
    6.    strAr3[2]= “Joe”;  

    All of the above three ways are used to initialize the String Array and have the same value.

    The 3rd method is a specific size method. In this, the value of the index can be found using the ( arraylength – 1) formula if we want to access the elements more than the index 2 in the above Array. It will throw the Java.lang.ArrayIndexOutOfBoundsException exception.

    Let’s see an example of String Array to demonstrate it’s behavior:

    Iteration of String Array

    The String Array can be iterated using the for and foreach loop. Consider the below code:

    1. String[] strAr = {“Ani”, “Sam”, “Joe”};  
    2. for (int i=0; i<StrAr.length; i++)  
    3. {  
    4. System.out.println(strAr[i]);  
    5. }  
    6. for ( String str: strAr)  
    7. {  
    8. Sytem.out.println(str);  
    9. }  

    Adding Elements to a String Array

    We can easily add the elements to the String Array just like other data types. It can be done using the following three methods:

    • Using Pre-Allocation of the Array
    • Using the Array List
    • By creating a new Array

    let’s understand the above methods:

    Using Pre-Allocation of the Array:

    In this method, we already have an Array of larger size. For example, if we require to store the 10 elements, then we will create an Array of size 20. It is the easiest way to expand the Array elements.

    Consider the below example to add elements in a pre-allocated array.

    1. // Java Program to add elements in a pre-allocated Array  
    2. import java.util.Arrays;  
    3. public class StringArrayDemo {  
    4.         public static void main(String[] args) {  
    5.             String[] sa = new String[7]; // Creating a new Array of Size 7  
    6.             sa[0] = “A”; // Adding Array elements  
    7.             sa[1] = “B”;  
    8.             sa[2] = “C”;  
    9.             sa[3] = “D”;  
    10.             sa[4] = “E”;  
    11.             System.out.println(“Original Array Elements:” + Arrays.toString(sa));  
    12.             int numberOfItems = 5;  
    13.             String newItem = “F”; // Expanding Array Elements Later  
    14.             String newItem2 =”G”;  
    15.             sa[numberOfItems++] = newItem;  
    16.             sa[numberOfItems++] = newItem2;  
    17.             System.out.println(“Array after adding two elements:” +    
    18.                       Arrays.toString(sa));  
    19.         }  
    20.     }  

    Output:

    Original Array Elements:[A, B, C, D, E, null, null]
    Array after adding two elements:[A, B, C, D, E, F, G]
    

    From the above example, we have added two elements in a pre-allocated Array.

    Using ArrayList:

    The ArrayList is a fascinating data structure of the Java collection framework. We can easily add elements to a String Array using an ArrayList as an intermediate data structure.

    Consider the below example to understand how to add elements to a String Array using ArrayList:

    File Name: StringArrayDemo1.java

    1. import java.util.ArrayList;  
    2. import java.util.Arrays;  
    3. import java.util.List;  
    4.   
    5. public class StringArrayDemo1 {   
    6.         public static void main(String[] args)   
    7.         {   
    8.               // Defining a String Array   
    9.               String sa[] = { “A”, “B”, “C”, “D”, “E”, “F” };  
    10.           //   
    11.             System.out.println(“Initial Array:\n”  
    12.                                + Arrays.toString(sa));   
    13.             String ne = “G”; // Define new element to add  
    14.             List<String>l = new ArrayList<String>(  
    15.                       Arrays.asList(sa)); // Convert Array to ArrayList  
    16.             l.add(ne); // Add new element in ArrayList l  
    17.             sa = l.toArray(sa); // Revert Conversion from ArrayList to Array  
    18.             // printing the new Array  
    19.             System.out.println(“Array with added Value: \n”  
    20.                                + Arrays.toString(sa)) ;   
    21.         }   
    22.     }  

    Output:

    Initial Array:
    [A, B, C, D, E, F]
    Array with added value:
    [A, B, C, D, E, F, G]
    

    By Creating a New Array:

    In this method, we will create a new Array with a larger size than the initial Array and accommodate the elements in it. We will copy all the elements to the newly added Array. Consider the following example:

    File Name: StringArrayDemo2.java

    1. // Java Program to add elements in a String Array by creating a new Array  
    2. import java.util.Arrays;  
    3. public class StringArrayDemo2 {  
    4.         public static void main(String[] args) {  
    5.             //Declaring Initial Array  
    6.             String[] sa = {“A”, “B”, “C” };    
    7.             // Printing the Original Array  
    8.             System.out.println(“Initial Array: ” + Arrays.toString(sa));  
    9.                 int length_Var = sa.length; //Defining the array length variable  
    10.             String newElement = “D”; // Defining new element to add  
    11.             //define new array with extended length           
    12.             String[] newArray = new String[ length_Var + 1 ];  
    13.             //Adding all the elements to initial Array  
    14.             for (int i=0; i <sa.length; i++)  
    15.             {  
    16.                 newArray[i] = sa [i];  
    17.              }  
    18.             //Specifying the position of the added elements ( Last)  
    19.             newArray[newArray.length- 1] = newElement;  
    20.             //make it original and print  
    21.             sa = newArray;     
    22.             System.out.println(“updated Array: ” + Arrays.toString(sa));  
    23.         }  
    24.     }  

    Output:

    Initial Array: [A, B, C]
    updated Array: [A, B, C, D]
    

    This is how we can add elements to a String Array. Let’s understand how to search and sort elements in String Array.

    Searching in String Array

    For searching a String from the String Array, for loop is used. Consider the below example:

    StringArrayExample.java

    1. public class StringArrayExample {  
    2.         public static void main(String[] args) {  
    3.             String[] strArray = { “Ani”, “Sam”, “Joe” };  
    4.             boolean x = false//initializing x to false  
    5.             int in = 0; //declaration of index variable  
    6.             String s = “Sam”;  // String to be searched  
    7.             // Iteration of the String Array  
    8.             for (int i = 0; i < strArray.length; i++) {  
    9.                 if(s.equals(strArray[i])) {  
    10.                     in = i; x = truebreak;  
    11.                 }  
    12.             }  
    13.             if(x)  
    14.                 System.out.println(s +” String is found at index “+in);  
    15.             else  
    16.                 System.out.println(s +” String is not found in the array”);  
    17.         }  
    18. }  

    Output:

    Sam String is found at index 1
    

    In the above example, we have initialized a boolean variable x to false and an index variable to iterate through the string. Also, we have declared a local variable String variable s to be searched. Here, the break keyword will exit the loop as soon as the string is found.

    Sorting in String Array

    The sorting in the String array is quite easy. It is performed like in a traditional array. We use a sort() method to sort the Array elements. Sorting is easier than searching.

    Consider the below example to sort a String Array:

    File Name: StringArraySorting.java

    1. //Java Program to sort elements in a String Array  
    2. import java.util.Arrays;  
    3. public class StringArraySorting {  
    4.        public static void main(String[] args)   
    5.         {   
    6.            // Adding String values  
    7.            String[] colors = {“Cricket”,”Basketball”,”Football”,”Badminton”,”Tennis”};  
    8.            // Print Original values   
    9.            System.out.println(“Entered Sports: “+Arrays.toString(colors));  
    10.             Arrays.sort(colors); // Sorting Elements  
    11.            // Print Sorted Values  
    12.             System.out.println(“Sorted Sports: “+Arrays.toString(colors));  
    13.         }  
    14.     }  

    Output:

    Entered Sports: [Cricket, Basketball, Football, Badminton, Tennis]
    Sorted Sports: [Badminton, Basketball, Cricket, Football, Tennis]
    

    From the above example, we can see the elements from a String Array is sorted using the sort() method.

    We can also convert String Array to other data structures such as List, int Array, ArrayList, and more and vice-versa.

    Manipulating String Arrays

    String arrays support various operations for manipulation, including adding, removing, and modifying elements. However, it’s essential to remember that arrays in Java have a fixed size once initialized. Therefore, to perform dynamic operations, such as adding or removing elements, you may need to resort to other data structures like ArrayList.

  • Array of Objects in Java

    In Java, an array is a collection of the same data type that dynamically creates objects and can have elements of primitive types. Java allows us to store objects in an array.

    An array of objects is a collection of multiple objects stored in a single variable. It stores the references to the objects. It is useful when managing multiple instances of a class efficiently.

    How to Create Array of Objects in Java

    Creating an Array of Objects

    Before creating an array of objects, we must create an instance of the class by using the new keyword. We can use any of the following statements to create an array of objects.

    Syntax:

    1. ClassName obj[]=new ClassName[array_length]; //declare and instantiate an array of objects  

    Or

    1. ClassName[] objArray;  

    Or

    1. ClassName objeArray[];  

    Suppose, we have created a class named Employee. We want to keep records of 20 employees of a company having three departments. In this case, we will not create 20 separate variables. Instead of this, we will create an array of objects, as follows.

    1. Employee department1[20];  
    2. Employee department2[20];  
    3. Employee department3[20];  

    The above statements create an array of objects with 20 elements.

    Example: Creating an Array of Objects

    In the following program, we have created a class named Product and initialized an array of objects using the constructor. We have created a constructor of the class Product that contains the product ID and product name. In the main() function, we have created individual objects of the class Product. After that, we passed initial values to each of the objects using the constructor.

    Example

    1. public class Main  {    
    2.     public static void main(String args[])   {    
    3.         //create an array of product objects     
    4.         Product[] obj = new Product[5] ;    
    5.         //create & initialize actual product objects using constructor    
    6.         obj[0] = new Product(23907,”Dell Laptop”);    
    7.         obj[1] = new Product(91240,”HP 630″);    
    8.         obj[2] = new Product(29823,”LG OLED TV”);    
    9.         obj[3] = new Product(11908,”MI Note Pro Max 9″);    
    10.         obj[4] = new Product(43590,”Kingston USB”);    
    11.         //display the product object data    
    12.         System. out.println(“Product Object 1:”);    
    13.         obj[0].display();    
    14.         System.out.println(“Product Object 2:”);    
    15.         obj[1].display();    
    16.         System.out.println(“Product Object 3:”);    
    17.         obj[2].display();    
    18.         System.out.println(“Product Object 4:”);    
    19.         obj[3].display();    
    20.         System.out.println(“Product Object 5:”);    
    21.         obj[4].display();    
    22.     }    
    23. }    
    24.  //Product class with product ID and product name as attributes    
    25. class Product  {    
    26.     int pro_Id;    
    27.     String pro_name;    
    28.     //Product class constructor    
    29.     Product(int pid, String n)  {    
    30.         pro_Id = pid;    
    31.         pro_name = n;    
    32.     }     
    33.     public void display()  {    
    34.         System.out.print(“Product ID = “+pro_ID + ”  ” + ” Product Name = “+pro_name);    
    35.         System.out.println();    
    36.     }    
    37. }    

    Compile and Run

    Output:

    Product Object 1:
    Product ID = 23907 Product Name = Dell Laptop
    Product Object 2:
    Product ID = 91240 Product Name = HP 630
    Product Object 3:
    Product ID = 29823 Product Name = LG OLED TV
    Product Object 4:
    Product ID = 11908 Product Name = MI Note Pro Max 9
    Product Object 5:
    Product ID = 43590 Product Name = Kingston USB
    

    Initializing an Array of Objects

    After the objects are instantiated, the array has to be initialized with values. In contrast to a variety of primitive types, an array of objects cannot be initialized in the same way. It is necessary to initialize each element or object in an array of objects. An array contains pointers to the real class through its objects.

    Consequently, it is highly recommended to generate actual objects of the class after declaring and instantiating an array of objects. The constructors can set up the array. Actual objects can have their initial values assigned by the application by supplying values to the constructor. A class’s independent member method can also be used to assign data to an object.

    The elements of an array of objects must be initialized after they have been created. Two common approaches are available to perform this:

    1. Using the Constructor
    2. Using Setter Methods

    1. Using the Constructor

    By providing variables to the constructor individually, we can define starting values for each object as the actual objects are being created. Every single real object is made with its unique values.

    Example

    1. // Java program to demonstrate initializing an array of objects using a constructor  
    2. public class Main {  
    3.     public static void main(String args[]) {  
    4.         // Declaring an array of Book  
    5.         Book[] books;  
    6.         // Allocating memory for 3 Book objects  
    7.         books = new Book[3];  
    8.         // Initializing the elements of the array using the constructor  
    9.         books[0] = new Book(101, “Java Basics”);  
    10.         books[1] = new Book(102, “Data Structures”);  
    11.         books[2] = new Book(103, “Operating Systems”);  
    12.         System.out.println(“Book details:”);  
    13.         for (int i = 0; i < books.length; i++) {  
    14.             books[i].display();  
    15.         }  
    16.     }  
    17. }  
    18. // Creating a Book class with id and title as attributes  
    19. class Book {  
    20.     public int bookId;  
    21.     public String title;  
    22.     // Book class constructor  
    23.     Book(int bookId, String title) {  
    24.         this.bookId = bookId;  
    25.         this.title = title;  
    26.     }  
    27.     // display() method to display the book data  
    28.     public void display() {  
    29.         System.out.println(“Book ID: ” + bookId + “, Title: ” + title);  
    30.     }  
    31. }  

    Compile and Run

    Output:

    Book details:
    Book ID: 101, Title: Java Basics
    Book ID: 102, Title: Data Structures
    Book ID: 103, Title: Operating Systems
    

    3. Using Setter Methods

    Using setter methods, we may assign values after creating objects. The initial values of the objects are assigned using a member function of the corresponding class that is formed.

    Example

    1. // Java program to demonstrate initializing an array of objects using setter methods  
    2. public class Main {  
    3.     public static void main(String args[]) {  
    4.         // Declaring an array of Book  
    5.         Book[] books;  
    6.         // Allocating memory for 3 objects of type Book  
    7.         books = new Book[3];  
    8.         // Creating actual Book objects  
    9.         books[0] = new Book();  
    10.         books[1] = new Book();  
    11.         books[2] = new Book();  
    12.         // Assigning data to Book objects using the setter method  
    13.         books[0].setData(201, “Java Programming”);  
    14.         books[1].setData(202, “Algorithms”);  
    15.         books[2].setData(203, “Database Systems”);  
    16.         // Displaying the book data  
    17.         System.out.println(“Book details:”);  
    18.         for (int i = 0; i < books.length; i++) {  
    19.             books[i].display();  
    20.         }  
    21.     }  
    22. }  
    23. // Creating a Book class with id and title as attributes  
    24. class Book {  
    25.     public int bookId;  
    26.     public String title;  
    27.     // Setter method to set the data  
    28.     public void setData(int bookId, String title) {  
    29.         this.bookId = bookId;  
    30.         this.title = title;  
    31.     }  
    32.     // display() method to show book details  
    33.     public void display() {  
    34.         System.out.println(“Book ID: ” + bookId + “, Title: ” + title);  
    35.     }  
    36. }  

    Compile and Run

    Output:

    Book details:
    Book ID: 201, Title: Java Programming
    Book ID: 202, Title: Algorithms
    Book ID: 203, Title: Database Systems