Author: Saim Khalid

  • Modules

    A module is like a package where you can keep your functions and subroutines, in case you are writing a very big program, or your functions or subroutines can be used in more than one program.

    Modules provide you a way of splitting your programs between multiple files.

    Modules are used for −

    • Packaging subprograms, data and interface blocks.
    • Defining global data that can be used by more than one routine.
    • Declaring variables that can be made available within any routines you choose.
    • Importing a module entirely, for use, into another program or subroutine.

    Syntax of a Module

    A module consists of two parts −

    • a specification part for statements declaration
    • a contains part for subroutine and function definitions

    The general form of a module is −

    module name     
       

    [contains [subroutine and function definitions] ] end module [name]

    Using a Module into your Program

    You can incorporate a module in a program or subroutine by the use statement −

    use name  
    

    Please note that

    • You can add as many modules as needed, each will be in separate files and compiled separately.
    • A module can be used in various different programs.
    • A module can be used many times in the same program.
    • The variables declared in a module specification part, are global to the module.
    • The variables declared in a module become global variables in any program or routine where the module is used.
    • The use statement can appear in the main program, or any other subroutine or module which uses the routines or variables declared in a particular module.

    Example

    The following example demonstrates the concept −

    Live Demo

    module constants  
    implicit none 
    
       real, parameter :: pi = 3.1415926536  
       real, parameter :: e = 2.7182818285 
       
    contains      
       subroutine show_consts()          
    
      print*, "Pi = ", pi          
      print*,  "e = ", e     
    end subroutine show_consts end module constants program module_example use constants implicit none real :: x, ePowerx, area, radius x = 2.0 radius = 7.0 ePowerx = e ** x area = pi * radius**2 call show_consts() print*, "e raised to the power of 2.0 = ", ePowerx print*, "Area of a circle with radius 7.0 = ", area end program module_example

    When you compile and execute the above program, it produces the following result −

    Pi = 3.14159274    
    e =  2.71828175    
    e raised to the power of 2.0 = 7.38905573    
    Area of a circle with radius 7.0 = 153.938049   
    

    Accessibility of Variables and Subroutines in a Module

    By default, all the variables and subroutines in a module is made available to the program that is using the module code, by the use statement.

    However, you can control the accessibility of module code using the private and public attributes. When you declare some variable or subroutine as private, it is not available outside the module.

    Example

    The following example illustrates the concept −

    In the previous example, we had two module variables, e and pi. Let us make them private and observe the output −

    Live Demo

    module constants  
    implicit none 
    
       real, parameter,private :: pi = 3.1415926536  
       real, parameter, private :: e = 2.7182818285 
       
    contains      
       subroutine show_consts()          
    
      print*, "Pi = ", pi          
      print*, "e = ", e     
    end subroutine show_consts end module constants program module_example use constants implicit none real :: x, ePowerx, area, radius x = 2.0 radius = 7.0 ePowerx = e ** x area = pi * radius**2 call show_consts() print*, "e raised to the power of 2.0 = ", ePowerx print*, "Area of a circle with radius 7.0 = ", area end program module_example

    When you compile and execute the above program, it gives the following error message −

       ePowerx = e ** x
       1
    Error: Symbol 'e' at (1) has no IMPLICIT type
    main.f95:19.13:
    
       area = pi * radius**2     
       1
    Error: Symbol 'pi' at (1) has no IMPLICIT type
    

    Since e and pi, both are declared private, the program module_example cannot access these variables anymore.

    However, other module subroutines can access them −

    Live Demo

    module constants  
    implicit none 
    
       real, parameter,private :: pi = 3.1415926536  
       real, parameter, private :: e = 2.7182818285 
       
    contains      
       subroutine show_consts()          
    
      print*, "Pi = ", pi          
      print*, "e = ", e     
    end subroutine show_consts function ePowerx(x)result(ePx) implicit none
      real::x
      real::ePx
      ePx = e ** x
    end function ePowerx
    function areaCircle(r)result(a) implicit none
      real::r
      real::a
      a = pi * r**2  
    end function areaCircle
    end module constants program module_example use constants implicit none call show_consts() Print*, "e raised to the power of 2.0 = ", ePowerx(2.0) print*, "Area of a circle with radius 7.0 = ", areaCircle(7.0) end program module_example

    When you compile and execute the above program, it produces the following result −

    Pi = 3.14159274    
    e = 2.71828175    
    e raised to the power of 2.0 = 7.38905573    
    Area of a circle with radius 7.0 = 153.938049   
    
  • Environment Setup

    Installing Kotlin command-line compiler

    One of the key features of Kotlin is that it has interoperability with Java i.e. You can write Kotlin and Java code in the same application. Like Java, Kotlin also runs on JVM therefore to install Kotlin on Windows directly and work with it using the command line You need to make sure you have JDK installed in your system.

    Verifying the Java installation

    To verify Java installation −

    • Open command prompt and verify the current version of Java using the javac version command −
    C:\Users\TP>javac -version
    javac 1.8.0_261
    

    If you doesn’t have Java installed in your system it generates the following error

    C:\Users\Krishna Kasyap>javac -v
    'javac' is not recognized as an internal or external command,
    operable program or batch file.
    

    You can install JDK by following the steps given below

    Installing JDK8

    • Open the following Oracle Java Downloads page.
    • Click on the JDK Download link under Java SE 8 section.
    JDK Kotlin
    • This will redirect to the page that contains JDK software for various platforms, select the desired version (.exe) and download it.
    Software
    • After downloading the file JDK file (assume we have downloaded jdk_windows-x64_bin.exe), start the installation by running it.
    JDK File
    • By default, Java will be installed in the path C:\Program Files\Java\jdk1.8.0_301\ you can change the path by clicking on the Change… button.
    Java Development
    • After the completion of the installation click on the Close button.
    Java Development

    Kotlin Command line compiler

    Kotlin command line compiler is available at the JetBrains Kotlin GitHub releases page.

    • Download the latest version.
    • Unzip the downloaded file and place it in the desired folder.
    • The Bin directory of the downloaded folder contains all the binary files to run Kotlin.
    Bin
    • Now, set Path environment variable to this folder.

    Setting the Path variable

    • Right click on My computer or This PC, select Properties.
    Path Variable
    • Click on Advanced System Settings.
    Advanced System Settings
    • Then, click on the Environment Variables… button.
    Environment Variables
    • In the Environment Variables window, under System Variables select the Path variable and edit the variables using the Edit… button.
    System Variables
    • Click on the New button and add the path of the bin folder of installed JDK and Kotlin folders.
    Edit

    To verify the installation, open command prompt and type java or javac command, if your installation is successful, you can see the output as shown below:

    Command Prompt

    Setting Kotlin environment using IntelliJ IDEA

    Kotlin is developed by the JetBrains that develops IDEs like AppCode, CLion, DataGrip, DataSpell, GoLand, IntelliJ IDEA etc.

    The IntelliJ IDEA internally have Kotlin plugin bundled with it. To develop Kotlin download and install IntelliJ.

    To install a recent version of IntelliJ IDEA:

    • Open JetBrains Downloads page, you can download the free community edition.
    IntelliJ Idea
    • If you run the downloaded file, it starts the installation process.
    IntelliJ Installation
    • Proceed with the installation by providing the required details and finally complete the installation.
    JetBrains
    • The Plugins tab of IntelliJ displays all the available plugins. By default, Kotlin plugin is activated, in any case if it is not activated. Open the plugin tab, search for Kotlin and install it.
    Plugin Tabs

    Creating first application

    • To create first application, click on NewProject.
    First Application
    • Select Kotlin/JVM and click Next.
    JVM
    • Name the project and select the desired location.
    Sample Application
    • Now, create a new Kotlin file under the source(src) folder and let’s name it as Test.
    Test
    • You can create a sample function as shown below. You can run this by pressing Ctrl + Shift + F10.
    Sample Function

    Setting Kotlin environment using Eclipse

    You can also execute Kotlin programs in eclipse to do so, you need to have “Eclipse IDE for Java developers” installed in your system. To do so, follow the steps given below.

    • Download the latest version of eclipse installer from the page: https://www.eclipse.org/downloads/
    Eclipse
    • Run the downloaded file and click on the Eclipse IDE for Java developers.
    Eclipse Installation
    • Select the installation directory and click on install.
    Directory
    • Open eclipse in the Help menu select Eclipse Marketplace.
    WorkSpace
    • Search for Kotlin and check all the matches and when you find Kotlin click on Install.
    Marketplace

    Creating a Kotlin application in eclipse

    Once you have installed Kotlin plugin in your eclipse to create your first application.

    • In the File menu click on Project.
    Project
    • This will take you to Select a wizard. Under Kotlin (dropdown menu), click on select “Kotlin Project” and click on the “Next” button.
    New Project
    • Then, enter the desired name for the application and click on Next.
    New Project1
    • Right click on the src folder of the created project click on other.
    Source
    • Select the Kotlin File wizard click on Next and name the file as Hello.kt.
    Kotlin File

    Your development environment is ready now. Go ahead and add the following piece of code in the “Hello.kt” file.

    fun main(args: Array) {
       println("Hello, World!")
    }

    Run it as a Kotlin application and see the output in the console as shown in the following screenshot. For better understanding and availability, we will be using our coding ground tool.

    Application
  • Procedures

    procedure is a group of statements that perform a well-defined task and can be invoked from your program. Information (or data) is passed to the calling program, to the procedure as arguments.

    There are two types of procedures −

    • Functions
    • Subroutines

    Function

    A function is a procedure that returns a single quantity. A function should not modify its arguments.

    The returned quantity is known as function value, and it is denoted by the function name.

    Syntax

    Syntax for a function is as follows −

    function name(arg1, arg2, ....)  
       

    end function [name]

    The following example demonstrates a function named area_of_circle. It calculates the area of a circle with radius r.

    program calling_func
    
       real :: a
       a = area_of_circle(2.0) 
       
       Print *, "The area of a circle with radius 2.0 is"
       Print *, a
       
    end program calling_func
    
    
    ! this function computes the area of a circle with radius r  
    function area_of_circle (r)  
    
    ! function result     
    implicit none      
    
       ! dummy arguments        
       real :: area_of_circle   
       
       ! local variables 
       real :: r     
       real :: pi
       
       pi = 4 * atan (1.0)     
       area_of_circle = pi * r**2  
       
    end function area_of_circle

    When you compile and execute the above program, it produces the following result −

    The area of a circle with radius 2.0 is
       12.5663710   
    

    Please note that −

    • You must specify implicit none in both the main program as well as the procedure.
    • The argument r in the called function is called dummy argument.

    The result Option

    If you want the returned value to be stored in some other name than the function name, you can use the result option.

    You can specify the return variable name as −

    function name(arg1, arg2, ....) result (return_var_name)  
       

    Subroutine

    A subroutine does not return a value, however it can modify its arguments.

    Syntax

    subroutine name(arg1, arg2, ....)    
       

    end subroutine [name]

    Calling a Subroutine

    You need to invoke a subroutine using the call statement.

    The following example demonstrates the definition and use of a subroutine swap, that changes the values of its arguments.

    Live Demo

    program calling_func
    implicit none
    
       real :: a, b
       a = 2.0
       b = 3.0
       
       Print *, "Before calling swap"
       Print *, "a = ", a
       Print *, "b = ", b
       
       call swap(a, b)
       
       Print *, "After calling swap"
       Print *, "a = ", a
       Print *, "b = ", b
       
    end program calling_func
    
    
    subroutine swap(x, y) 
    implicit none
    
       real :: x, y, temp   
       
       temp = x  
       x = y 
       y = temp  
       
    end subroutine swap

    When you compile and execute the above program, it produces the following result −

    Before calling swap
    a = 2.00000000    
    b = 3.00000000    
    After calling swap
    a = 3.00000000    
    b = 2.00000000   
    

    Specifying the Intent of the Arguments

    The intent attribute allows you to specify the intention with which arguments are used in the procedure. The following table provides the values of the intent attribute −

    ValueUsed asExplanation
    inintent(in)Used as input values, not changed in the function
    outintent(out)Used as output value, they are overwritten
    inoutintent(inout)Arguments are both used and overwritten

    The following example demonstrates the concept −

    Live Demo

    program calling_func
    implicit none
    
       real :: x, y, z, disc
       
       x = 1.0
       y = 5.0
       z = 2.0
       
       call intent_example(x, y, z, disc)
       
       Print *, "The value of the discriminant is"
       Print *, disc
       
    end program calling_func
    
    
    subroutine intent_example (a, b, c, d)     
    implicit none     
    
       ! dummy arguments      
       real, intent (in) :: a     
       real, intent (in) :: b      
       real, intent (in) :: c    
       real, intent (out) :: d   
       
       d = b * b - 4.0 * a * c 
       
    end subroutine intent_example

    When you compile and execute the above program, it produces the following result −

    The value of the discriminant is
       17.0000000    
    

    Recursive Procedures

    Recursion occurs when a programming languages allows you to call a function inside the same function. It is called recursive call of the function.

    When a procedure calls itself, directly or indirectly, is called a recursive procedure. You should declare this type of procedures by preceding the word recursive before its declaration.

    When a function is used recursively, the result option has to be used.

    Following is an example, which calculates factorial for a given number using a recursive procedure −

    program calling_func
    implicit none
    
       integer :: i, f
       i = 15
       
       Print *, "The value of factorial 15 is"
       f = myfactorial(15)
       Print *, f
       
    end program calling_func
    
    ! computes the factorial of n (n!)      
    recursive function myfactorial (n) result (fac)  
    ! function result     
    implicit none     
    
       ! dummy arguments     
       integer :: fac     
       integer, intent (in) :: n     
       
       select case (n)         
    
      case (0:1)         
         fac = 1         
      case default    
         fac = n * myfactorial (n-1)  
    end select end function myfactorial

    Internal Procedures

    When a procedure is contained within a program, it is called the internal procedure of the program. The syntax for containing an internal procedure is as follows −

    program program_name     
       implicit none         
       ! type declaration statements         
       ! executable statements    
       . . .     
       contains         
       ! internal procedures      
       . . .  
    end program program_name
    

    The following example demonstrates the concept −

    program mainprog  
    implicit none 
    
       real :: a, b 
       a = 2.0
       b = 3.0
       
       Print *, "Before calling swap"
       Print *, "a = ", a
       Print *, "b = ", b
       
       call swap(a, b)
       
       Print *, "After calling swap"
       Print *, "a = ", a
       Print *, "b = ", b
     
    contains   
       subroutine swap(x, y)     
    
      real :: x, y, temp      
      temp = x 
      x = y  
      y = temp   
    end subroutine swap end program mainprog

    When you compile and execute the above program, it produces the following result −

    Before calling swap
    a = 2.00000000    
    b = 3.00000000    
    After calling swap
    a = 3.00000000    
    b = 2.00000000   
    
  • Overview

    What is Kotlin?

    Kotlin is a new open source programming language like Java, JavaScript, Python etc. It is a high level strongly statically typed language that combines functional and technical part in a same place. Currently, Kotlin mainly targets the Java Virtual Machine (JVM), but also compiles to JavaScript.

    Kotlin is influenced by other popular programming languages such as Java, C#, JavaScript, Scala and Groovy. The syntax of Kotlin may not be exactly similar to Java Programming Language, however, internally Kotlin is reliant on the existing Java Class library to produce wonderful results for the programmers. Kotlin provides interoperability, code safety, and clarity to the developers around the world.

    Kotlin was developed and released by JetBrains in 2016. Kotlin is free, has been free and will remain free. It is developed under the Apache 2.0 license and the source code is available on GitHub

    Why Kotlin?

    Kotlin is getting high popularity among all level of programmers and it is used for:

    • Cross-platform Mobile applications.
    • Android Application Development.
    • Web Application Development
    • Server Side Applications
    • Desktop Application Development
    • Data science based applications

    Kotlin works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) and it’s 100% compatible with Java.

    Kotlin is used by many large companies like Google, Netflix, Slack, Uber etc to develop their Android based applications.

    The most importantly, there are many companies actively looking for Kotlin developers, especially in the Android development space.

    Kotlin Version?

    At the time of writing this tutorial on Aug 3, 2021, The current Kotlin released version is 1.5.21

    Kotlin Advantages

    Following are some of the advantages of using Kotlin for your application development.

    1. Easy Language − Kotlin supports object-oriented and functional constructs and very easy to learn. The syntax is pretty much similar to Java, hence for any Java programmer it is very easy to remember any Kotlin Syntax.

    2. Very Concise − Kotlin is based on Java Virtual Machine (JVM) and it is a functional language. Thus, it reduce lots of boiler plate code used in other programming languages.

    3. Runtime and Performance − Kotlin gives a better performance and small runtime for any application.

    4. Interoperability − Kotlin is mature enough to build an interoperable application in a less complex manner.

    5. Brand New − Kotlin is a brand new language that gives developers a fresh start. It is not a replacement of Java, though it is developed over JVM. Kotlin has been accepted as the first official language of Android Application Development. Kotlin can also be defined as – Kotlin = Java + Extra updated new features.

    Kotlin Drawbacks

    Following are some of the disadvantages of using Kotlin.

    1. Namespace declaration − Kotlin allows developers to declare the functions at the top level. However, whenever the same function is declared in many places of your application, then it is hard to understand which function is being called.

    2. No Static Declaration − Kotlin does not have usual static handling modifier like Java, which can cause some problem to the conventional Java developer.

  • File Input Output

    In the last chapter, you have seen how to read data from, and write data to the terminal. In this chapter you will study file input and output functionalities provided by Fortran.

    You can read and write to one or more files. The OPEN, WRITE, READ and CLOSE statements allow you to achieve this.

    Opening and Closing Files

    Before using a file you must open the file. The open command is used to open files for reading or writing. The simplest form of the command is −

    open (unit = number, file = "name").
    

    However, the open statement may have a general form −

    open (list-of-specifiers)
    

    The following table describes the most commonly used specifiers −

    Sr.NoSpecifier & Description
    1[UNIT=] uThe unit number u could be any number in the range 9-99 and it indicates the file, you may choose any number but every open file in the program must have a unique number
    2IOSTAT= iosIt is the I/O status identifier and should be an integer variable. If the open statement is successful then the ios value returned is zero else a non-zero value.
    3ERR = errIt is a label to which the control jumps in case of any error.
    4FILE = fnameFile name, a character string.
    5STATUS = staIt shows the prior status of the file. A character string and can have one of the three values NEW, OLD or SCRATCH. A scratch file is created and deleted when closed or the program ends.
    6ACCESS = accIt is the file access mode. Can have either of the two values, SEQUENTIAL or DIRECT. The default is SEQUENTIAL.
    7FORM = frmIt gives the formatting status of the file. Can have either of the two values FORMATTED or UNFORMATTED. The default is UNFORMATTED
    8RECL = rlIt specifies the length of each record in a direct access file.

    After the file has been opened, it is accessed by read and write statements. Once done, it should be closed using the close statement.

    The close statement has the following syntax −

    close ([UNIT = ]u[,IOSTAT = ios,ERR = err,STATUS = sta])
    

    Please note that the parameters in brackets are optional.

    Example

    This example demonstrates opening a new file for writing some data into the file.

    program outputdata   
    implicit none
    
       real, dimension(100) :: x, y  
       real, dimension(100) :: p, q
       integer :: i  
       
       ! data  
       do i=1,100  
    
      x(i) = i * 0.1 
      y(i) = sin(x(i)) * (1-cos(x(i)/3.0))  
    end do ! output data into a file open(1, file = 'data1.dat', status = 'new') do i=1,100
      write(1,*) x(i), y(i)   
    end do close(1) end program outputdata

    When the above code is compiled and executed, it creates the file data1.dat and writes the x and y array values into it. And then closes the file.

    Reading from and Writing into the File

    The read and write statements respectively are used for reading from and writing into a file respectively.

    They have the following syntax −

    read ([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s)
    write([UNIT = ]u, [FMT = ]fmt, IOSTAT = ios, ERR = err, END = s)
    

    Most of the specifiers have already been discussed in the above table.

    The END = s specifier is a statement label where the program jumps, when it reaches end-of-file.

    Example

    This example demonstrates reading from and writing into a file.

    In this program we read from the file, we created in the last example, data1.dat, and display it on screen.

    Live Demo

    program outputdata   
    implicit none   
    
       real, dimension(100) :: x, y  
       real, dimension(100) :: p, q
       integer :: i  
       
       ! data  
       do i = 1,100  
    
      x(i) = i * 0.1 
      y(i) = sin(x(i)) * (1-cos(x(i)/3.0))  
    end do ! output data into a file open(1, file = 'data1.dat', status='new') do i = 1,100
      write(1,*) x(i), y(i)   
    end do close(1) ! opening the file for reading open (2, file = 'data1.dat', status = 'old') do i = 1,100
      read(2,*) p(i), q(i)
    end do close(2) do i = 1,100
      write(*,*) p(i), q(i)
    end do end program outputdata

    When the above code is compiled and executed, it produces the following result −

    0.100000001  5.54589933E-05
    0.200000003  4.41325130E-04
    0.300000012  1.47636665E-03
    0.400000006  3.45637114E-03
    0.500000000  6.64328877E-03
    0.600000024  1.12552457E-02
    0.699999988  1.74576249E-02
    0.800000012  2.53552198E-02
    0.900000036  3.49861123E-02
    1.00000000   4.63171229E-02
    1.10000002   5.92407547E-02
    1.20000005   7.35742599E-02
    1.30000007   8.90605897E-02
    1.39999998   0.105371222    
    1.50000000   0.122110792    
    1.60000002   0.138823599    
    1.70000005   0.155002072    
    1.80000007   0.170096487    
    1.89999998   0.183526158    
    2.00000000   0.194692180    
    2.10000014   0.202990443    
    2.20000005   0.207826138    
    2.29999995   0.208628103    
    2.40000010   0.204863414    
    2.50000000   0.196052119    
    2.60000014   0.181780845    
    2.70000005   0.161716297    
    2.79999995   0.135617107    
    2.90000010   0.103344671    
    3.00000000   6.48725405E-02
    3.10000014   2.02930309E-02
    3.20000005  -3.01767997E-02
    3.29999995  -8.61928314E-02
    3.40000010  -0.147283033    
    3.50000000  -0.212848678    
    3.60000014  -0.282169819    
    3.70000005  -0.354410470    
    3.79999995  -0.428629100    
    3.90000010  -0.503789663    
    4.00000000  -0.578774154    
    4.09999990  -0.652400017    
    4.20000029  -0.723436713    
    4.30000019  -0.790623367    
    4.40000010  -0.852691114    
    4.50000000  -0.908382416    
    4.59999990  -0.956472993    
    4.70000029  -0.995793998    
    4.80000019  -1.02525222    
    4.90000010  -1.04385209    
    5.00000000  -1.05071592    
    5.09999990  -1.04510069    
    5.20000029  -1.02641726    
    5.30000019  -0.994243503    
    5.40000010  -0.948338211    
    5.50000000  -0.888650239    
    5.59999990  -0.815326691    
    5.70000029  -0.728716135    
    5.80000019  -0.629372001    
    5.90000010  -0.518047631    
    6.00000000  -0.395693362    
    6.09999990  -0.263447165    
    6.20000029  -0.122622721    
    6.30000019   2.53026206E-02
    6.40000010   0.178709000    
    6.50000000   0.335851669    
    6.59999990   0.494883657    
    6.70000029   0.653881252    
    6.80000019   0.810866773    
    6.90000010   0.963840425    
    7.00000000   1.11080539    
    7.09999990   1.24979746    
    7.20000029   1.37891412    
    7.30000019   1.49633956    
    7.40000010   1.60037732    
    7.50000000   1.68947268    
    7.59999990   1.76223695    
    7.70000029   1.81747139    
    7.80000019   1.85418403    
    7.90000010   1.87160957    
    8.00000000   1.86922085    
    8.10000038   1.84674001    
    8.19999981   1.80414569    
    8.30000019   1.74167395    
    8.40000057   1.65982044    
    8.50000000   1.55933595    
    8.60000038   1.44121361    
    8.69999981   1.30668485    
    8.80000019   1.15719533    
    8.90000057   0.994394958    
    9.00000000   0.820112705    
    9.10000038   0.636327863    
    9.19999981   0.445154816    
    9.30000019   0.248800844    
    9.40000057   4.95488606E-02
    9.50000000  -0.150278628    
    9.60000038  -0.348357052    
    9.69999981  -0.542378068    
    9.80000019  -0.730095863    
    9.90000057  -0.909344316    
    10.0000000  -1.07807255    
    
  • Comments

    Java Comments

    Java comments are text notes written in the code to provide an explanation about the source code. The comments can be used to explain the logic or for documentation purposes. The compiler does not compile the comments. In Java, comments are very similar to C and C++.

    In Java, there are three types of comments:

    • Single-line comments
    • Multiline comments
    • Documentation comments

    Let’s discuss each type of comment in detail.

    1. Single Line Comment

    The single-line comment is used to add a comment on only one line and can be written by using the two forward slashes (//). These comments are the most used commenting way.

    The single line comments are the most used commenting way to explain the purpose (or to add a text note) of the line.

    Syntax

    Consider the below syntax to write a single line comment in Java:

    // comment

    Example 1: Java Single Line Comment

    // if divisor is 0 throw an exceptionif(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}

    Example 2: Java Single Line Comment

    Following code shows the usage of single line comments in a simple program. We’ve added comments to code lines to explain their purpose.

    packagecom.tutorialspoint;publicclassMyFirstJavaProgram{publicstaticvoidmain(String[] args){MyFirstJavaProgram program =newMyFirstJavaProgram();double result = program.divide(100,10);System.out.println(result);}privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{// if divisor is 0 throw an exceptionif(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}return(double) dividend / divisor;// returns the result of the division as double}}

    Output

    Compile and run MyFirstJavaProgram. This will produce the following result −

    10.0
    

    2. Multiline Comment

    The multiline (or, multiple-line) comments start with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/) and they are used to add comment on multiple lines.

    The multiline comments are very useful when we want to put a long comment spreading across multiple lines or to comment out the complete code.

    Syntax:

    Consider the below syntax to write multiline comment in Java:

    /*
    Comment (line 1)
    Comment (line 2)
    ...
    */

    Example 1: Java Multiline Comment

    /* This is an example 
    of 
    multi line comment. *//* if (dividend == 0) {
       throw new IllegalArgumentException("dividend cannot be zero");
    } */

    Example 2: Java Multiline Comment

    Following code shows the usage of multiple comments in a simple program. We’ve commented out extra code from a method using Multiline comments.

    packagecom.tutorialspoint;publicclassMyFirstJavaProgram{publicstaticvoidmain(String[] args){MyFirstJavaProgram program =newMyFirstJavaProgram();double result = program.divide(100,10);System.out.println(result);}privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{if(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}/* if (dividend == 0) {
    
         throw new IllegalArgumentException("dividend cannot be zero");
      } */return(double) dividend / divisor;}}</code></pre>

    Output

    Compile and run MyFirstJavaProgram. This will produce the following result −

    10.0
    

    3. Documentation Comment

    The documentation comments are used for writing the documentation of the source code. The documentation comments start with a forward slash followed by the two asterisks (/**), end with an asterisk followed by a backward slash (*/), and all lines between the start and end must start with an asterisk (*).

    The documentation comments are understood by the Javadoc tool and can be used to create HTML-based documentation.

    Syntax

    Consider the below syntax to write documentation comment in Java:

    /**
    * line 1
    * line 2
    ...
    */

    Example 1: Java Documentation Comment

    /**
     * This is a documentation comment.
     * This is my first Java program.
     * This will print 'Hello World' as the output
     * This is an example of multi-line comments.
    */publicclassMyFirstJavaProgram{}

    The above commenting style is known as documentation comments. It is used by Javadoc tool while creating the documentation for the program code. We can give details of arguments, exception and return type as well using following annotation in documentation comments.

    /**
     * @param dividend
     * @param divisor
     * @return quotient
     * @throws IllegalArgumentException if divisor is zero
     */privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{}

    Example 2: Java Documentation Comment

    Following code shows the usage of documentation comments in a simple program. We've defined a comments on the class declaration to give details of the class. In case of method, we're adding details of parameters, return value and exception raised in documentation block of the method comments section.

    packagecom.tutorialspoint;/**
     * This is a documentation comment. 
     * This is my first Java program.
     * This is an example of multi-line comments.
     * We're printing result of divison of two numbers in this program
     */publicclassMyFirstJavaProgram{publicstaticvoidmain(String[] args){MyFirstJavaProgram program =newMyFirstJavaProgram();double result = program.divide(100,10);System.out.println(result);}/**
    
    * @param dividend
    * @param divisor
    * @return quotient
    * @throws IllegalArgumentException if divisor is zero
    */privatedoubledivide(int dividend,int divisor)throwsIllegalArgumentException{if(divisor ==0){thrownewIllegalArgumentException("divisor cannot be zero");}return(double) dividend / divisor;}}</code></pre>

    Output

    Compile and run MyFirstJavaProgram. This will produce the following result −

    10.0
    
  • Pointers

    In most programming languages, a pointer variable stores the memory address of an object. However, in Fortran, a pointer is a data object that has more functionalities than just storing the memory address. It contains more information about a particular object, like type, rank, extents, and memory address.

    A pointer is associated with a target by allocation or pointer assignment.

    Declaring a Pointer Variable

    A pointer variable is declared with the pointer attribute.

    The following examples shows declaration of pointer variables −

    integer, pointer :: p1 ! pointer to integer  
    real, pointer, dimension (:) :: pra ! pointer to 1-dim real array  
    real, pointer, dimension (:,:) :: pra2 ! pointer to 2-dim real array

    A pointer can point to −

    • An area of dynamically allocated memory.
    • A data object of the same type as the pointer, with the target attribute.

    Allocating Space for a Pointer

    The allocate statement allows you to allocate space for a pointer object. For example −

    program pointerExample
    implicit none
    
       integer, pointer :: p1
       allocate(p1)
       
       p1 = 1
       Print *, p1
       
       p1 = p1 + 4
       Print *, p1
       
    end program pointerExample

    When the above code is compiled and executed, it produces the following result −

    1
    5
    

    You should empty the allocated storage space by the deallocate statement when it is no longer required and avoid accumulation of unused and unusable memory space.

    Targets and Association

    A target is another normal variable, with space set aside for it. A target variable must be declared with the target attribute.

    You associate a pointer variable with a target variable using the association operator (=>).

    Let us rewrite the previous example, to demonstrate the concept −

    Live Demo

    program pointerExample
    implicit none
    
       integer, pointer :: p1
       integer, target :: t1 
       
       p1=>t1
       p1 = 1
       
       Print *, p1
       Print *, t1
       
       p1 = p1 + 4
       
       Print *, p1
       Print *, t1
       
       t1 = 8
       
       Print *, p1
       Print *, t1
       
    end program pointerExample

    When the above code is compiled and executed, it produces the following result −

    1
    1
    5
    5
    8
    8
    

    A pointer can be −

    • Undefined
    • Associated
    • Disassociated

    In the above program, we have associated the pointer p1, with the target t1, using the => operator. The function associated, tests a pointer’s association status.

    The nullify statement disassociates a pointer from a target.

    Nullify does not empty the targets as there could be more than one pointer pointing to the same target. However, emptying the pointer implies nullification also.

    Example 1

    The following example demonstrates the concepts −

    Live Demo

    program pointerExample
    implicit none
    
       integer, pointer :: p1
       integer, target :: t1 
       integer, target :: t2
       
       p1=>t1
       p1 = 1
       
       Print *, p1
       Print *, t1
       
       p1 = p1 + 4
       Print *, p1
       Print *, t1
       
       t1 = 8
       Print *, p1
       Print *, t1
       
       nullify(p1)
       Print *, t1
       
       p1=>t2
       Print *, associated(p1)
       Print*, associated(p1, t1)
       Print*, associated(p1, t2)
       
       !what is the value of p1 at present
       Print *, p1
       Print *, t2
       
       p1 = 10
       Print *, p1
       Print *, t2
       
    end program pointerExample

    When the above code is compiled and executed, it produces the following result −

    1
    1
    5
    5
    8
    8
    8
    T
    F
    T
    0
    0
    10
    10
    

    Please note that each time you run the code, the memory addresses will be different.

    Example 2

    Live Demo

    program pointerExample
    implicit none
    
       integer, pointer :: a, b
       integer, target :: t
       integer :: n
       
       t = 1
       a => t
       t = 2
       b => t
       n = a + b
       
       Print *, a, b, t, n 
       
    end program pointerExample

    When the above code is compiled and executed, it produces the following result −

    2  2  2  4
    
  • Basic Operators

    Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −

    • Arithmetic Operators
    • Relational Operators
    • Bitwise Operators
    • Logical Operators
    • Assignment Operators
    • Misc Operators

    The Arithmetic Operators

    Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −

    Assume integer variable A holds 10 and variable B holds 20, then −

    OperatorDescriptionExample
    + (Addition)Adds values on either side of the operator.A + B will give 30
    – (Subtraction)Subtracts right-hand operand from left-hand operand.A – B will give -10
    * (Multiplication)Multiplies values on either side of the operator.A * B will give 200
    / (Division)Divides left-hand operand by right-hand operand.B / A will give 2
    % (Modulus)Divides left-hand operand by right-hand operand and returns remainder.B % A will give 0
    ++ (Increment)Increases the value of operand by 1.B++ gives 21
    — (Decrement)Decreases the value of operand by 1.B– gives 19

    The Relational Operators

    There are following relational operators supported by Java language.

    Assume variable A holds 10 and variable B holds 20, then −

    OperatorDescriptionExample
    == (equal to)Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
    != (not equal to)Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
    > (greater than)Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
    < (less than)Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
    >= (greater than or equal to)Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
    <= (less than or equal to)Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

    The Bitwise Operators

    Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

    Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

    a =00111100
    b =00001101
    a&b =00001100
    a|b =00111101
    a^b =00110001~a  =11000011

    The following table lists the bitwise operators −

    Assume integer variable A holds 60 and variable B holds 13 then −

    OperatorDescriptionExample
    & (bitwise and)Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
    | (bitwise or)Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
    ^ (bitwise XOR)Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
    ⁓ (bitwise compliment)Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.(⁓A ) will give -61 which is 1100 0011 in 2’s complement form due to a signed binary number.
    << (left shift)Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
    >> (right shift)Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 1111
    >>> (zero fill right shift)Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.A >>>2 will give 15 which is 0000 1111

    The Logical Operators

    The following table lists the logical operators −

    Assume Boolean variables A holds true and variable B holds false, then −

    OperatorDescriptionExample
    && (logical and)Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.(A && B) is false
    || (logical or)Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.(A || B) is true
    ! (logical not)Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true

    The Assignment Operators

    Following are the assignment operators supported by Java language −

    OperatorDescriptionExample
    =Simple assignment operator. Assigns values from right side operands to left side operand.C = A + B will assign value of A + B into C
    +=Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.C += A is equivalent to C = C + A
    -=Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.C -= A is equivalent to C = C − A
    *=Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand.C *= A is equivalent to C = C * A
    /=Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand.C /= A is equivalent to C = C / A
    %=Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand.C %= A is equivalent to C = C % A
    <<=Left shift AND assignment operator.C <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operator.C >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operator.C &= 2 is same as C = C & 2
    ^=bitwise exclusive OR and assignment operator.C ^= 2 is same as C = C ^ 2
    |=bitwise inclusive OR and assignment operator.C |= 2 is same as C = C | 2

    Miscellaneous Operators

    There are few other operators supported by Java Language.

    Conditional Operator ( ? : )

    Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as −

    variable x = (expression) ? value if true : value if false
    

    Following is an example −

    Example

    In this example, we’re creating two variables a and b and using ternary operator we’ve decided the values of b and printed it.

    publicclassTest{publicstaticvoidmain(String args[]){int a, b;
    
      a =10;
      b =(a ==1)?20:30;System.out.println("Value of b is : "+  b );
      b =(a ==10)?20:30;System.out.println("Value of b is : "+ b );}}</code></pre>

    Output

    Value of b is : 30
    Value of b is : 20
    

    instanceof Operator

    This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type). instanceof operator is written as −

    ( Object reference variable ) instanceof  (class/interface type)
    

    If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is an example −

    Example

    In this example, we're creating a String variable name and then using instanceof operator we've checking the name is of String or not.

    publicclassTest{publicstaticvoidmain(String args[]){String name ="James";// following will return true since name is type of Stringboolean result = name instanceofString;System.out.println( result );}}

    Output

    true
    

    This operator will still return true, if the object being compared is the assignment compatible with the type on the right. Following is one more example −

    Example

    In this example, we're creating a variable a of class Vehicle and then using instanceof operator we've checking the name is of type Car or not.

    classVehicle{}publicclassCarextendsVehicle{publicstaticvoidmain(String args[]){Vehicle a =newCar();boolean result =  a instanceofCar;System.out.println( result );}}

    Output

    true
    

    Precedence of Java Operators

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

    For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.

    Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    CategoryOperatorAssociativity
    Postfixexpression++ expression--Left to right
    Unary++expression --expression +expression -expression ⁓ !Right to left
    Multiplicative* / %Left to right
    Additive+ -Left to right
    Shift<< >> >>>Left to right
    Relational< > <= >= instanceofLeft to right
    Equality== !=Left to right
    Bitwise AND&Left to right
    Bitwise XOR^Left to right
    Bitwise OR|Left to right
    Logical AND&&Left to right
    Logical OR||Left to right
    Conditional?:Right to left
    Assignment= += -= *= /= %= ^= |= <<= >>= >>>=Right to left
  • Derived Data Types

    Fortran allows you to define derived data types. A derived data type is also called a structure, and it can consist of data objects of different types.

    Derived data types are used to represent a record. E.g. you want to keep track of your books in a library, you might want to track the following attributes about each book −

    • Title
    • Author
    • Subject
    • Book ID

    Defining a Derived data type

    To define a derived data type, the type and end type statements are used. . The type statement defines a new data type, with more than one member for your program. The format of the type statement is this −

    type type_name      
       declarations
    end type 

    Here is the way you would declare the Book structure −

    type Books
       character(len = 50) :: title
       character(len = 50) :: author
       character(len = 150) :: subject
       integer :: book_id
    end type Books
    

    Accessing Structure Members

    An object of a derived data type is called a structure.

    A structure of type Books can be created in a type declaration statement like −

    type(Books) :: book1 
    

    The components of the structure can be accessed using the component selector character (%) −

    book1%title = "C Programming"
    book1%author = "Nuha Ali"
    book1%subject = "C Programming Tutorial"
    book1%book_id = 6495407
    

    Note that there are no spaces before and after the % symbol.

    Example

    The following program illustrates the above concepts −

    Live Demo

    program deriveDataType
    
       !type declaration
       type Books
    
      character(len = 50) :: title
      character(len = 50) :: author
      character(len = 150) :: subject
      integer :: book_id
    end type Books !declaring type variables type(Books) :: book1 type(Books) :: book2 !accessing the components of the structure book1%title = "C Programming" book1%author = "Nuha Ali" book1%subject = "C Programming Tutorial" book1%book_id = 6495407 book2%title = "Telecom Billing" book2%author = "Zara Ali" book2%subject = "Telecom Billing Tutorial" book2%book_id = 6495700 !display book info Print *, book1%title Print *, book1%author Print *, book1%subject Print *, book1%book_id Print *, book2%title Print *, book2%author Print *, book2%subject Print *, book2%book_id end program deriveDataType

    When the above code is compiled and executed, it produces the following result −

     C Programming                                     
     Nuha Ali                                          
     C Programming Tutorial            
       6495407
     Telecom Billing                                   
     Zara Ali                                          
     Telecom Billing Tutorial            
       6495700
    

    Array of Structures

    You can also create arrays of a derived type −

    type(Books), dimension(2) :: list
    

    Individual elements of the array could be accessed as −

    list(1)%title = "C Programming"
    list(1)%author = "Nuha Ali"
    list(1)%subject = "C Programming Tutorial"
    list(1)%book_id = 6495407
    

    The following program illustrates the concept −

    Live Demo

    program deriveDataType
    
       !type declaration
       type Books
    
      character(len = 50) :: title
      character(len = 50) :: author
      character(len = 150) :: subject
      integer :: book_id
    end type Books !declaring array of books type(Books), dimension(2) :: list
    !accessing the components of the structure list(1)%title = "C Programming" list(1)%author = "Nuha Ali" list(1)%subject = "C Programming Tutorial" list(1)%book_id = 6495407 list(2)%title = "Telecom Billing" list(2)%author = "Zara Ali" list(2)%subject = "Telecom Billing Tutorial" list(2)%book_id = 6495700 !display book info Print *, list(1)%title Print *, list(1)%author Print *, list(1)%subject Print *, list(1)%book_id Print *, list(1)%title Print *, list(2)%author Print *, list(2)%subject Print *, list(2)%book_id end program deriveDataType

    When the above code is compiled and executed, it produces the following result −

    C Programming                                     
    Nuha Ali                                          
    C Programming Tutorial               
       6495407
    C Programming                                     
    Zara Ali                                          
    Telecom Billing Tutorial                                      
       6495700
    
  • Unicode System

    Unicode is an international character set that encompasses a vast range of characters, symbols, and scripts from many languages across the globe.

    Unicode System in Java

    Java programming language, being platform-independent, has built-in support for Unicode characters, allowing developers to create applications that can work seamlessly with diverse languages and scripts.

    Before Unicode, there were multiple standards to represent character encoding −

    • ASCII − for the United States.
    • ISO 8859-1 − for Western European Language.
    • KOI-8 − for Russian.
    • GB18030 and BIG-5 − for Chinese.

    So to support multinational application codes, some character was using single byte, some two. An even same code may represent a different character in one language and may represent other characters in another language.

    To overcome above shortcoming, the Unicode system was developed where each character is represented by 2 bytes. As Java was developed for multilingual languages it adopted the Unicode system. The lowest value is represented by \u0000 and the highest value is represented by \uFFFF.

    Approaches: Working with Unicode Characters & Values

    There are two approaches for working with Unicode characters in Java: Using Unicode Escape Sequences and Directly Storing Unicode Characters.

    The first approach involves representing Unicode characters using escape sequences and is useful when the characters cannot be directly typed or displayed in the Java code. The second approach involves directly storing Unicode characters in variables and is more convenient when the characters can be directly typed or displayed.

    The choice of approach depends on the specific requirements of the program. However, in general, Approach 2 is simpler and more convenient when the characters can be directly typed or displayed, while Approach 1 is necessary when they cannot.

    1. Using Unicode Escape Sequences

    One way to store Unicode characters in Java is by using Unicode escape sequences. An escape sequence is a series of characters that represent a special character. In Java, a Unicode escape sequence starts with the characters ‘\u’ followed by four hexadecimal digits that represent the Unicode code point of the desired character.

    Example: Use of Unicode Escape Sequences

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoid main (String[]args){//Unicode escape sequencechar unicodeChar ='\u0041';// point for 'A'System.out.println("Stored Unicode Character: "+ unicodeChar);}}

    Compile and run above program. This will produce the following result −

    Output

    Stored Unicode Character: A
    

    In the above code snippet, the Unicode escape sequence ‘\u0041’ represents the character ‘A.’ The escape sequence is assigned to the char variable unicodeChar, and the stored character is then printed to the console.

    2. Storing Unicode Values Directly

    Alternatively, you can directly store a Unicode character in a char variable by enclosing the character in single quotes. However, this approach may not be feasible for characters that cannot be typed directly using a keyboard or are not visible, such as control characters.

    Example 1: Assigning Unicode Character to Variable

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoidmain(String[] args){// Storing Unicode character directlychar unicodeChar ='A';// Directly storing the character 'A'System.out.println("Stored Unicode Character: "+ unicodeChar);}}

    Compile and run above program. This will produce the following result −

    Output

    Stored Unicode Character: A
    

    In this example, the character ‘A’ is directly enclosed in single quotes and assigned to the char variable unicodeChar. The stored character is then printed to the console.

    Example 2: Assigning Unicode Values to Variables

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoidmain(String[] args){// Storing Unicode characters using escape sequenceschar letterA ='\u0041';char letterSigma ='\u03A3';char copyrightSymbol ='\u00A9';// Storing Unicode characters directlychar letterZ ='Z';char letterOmega ='Ω';char registeredSymbol ='®';// Printing the stored Unicode charactersSystem.out.println("Stored Unicode Characters using Escape Sequences:");System.out.println("Letter A: "+ letterA);System.out.println("Greek Capital Letter Sigma: "+ letterSigma);System.out.println("Copyright Symbol: "+ copyrightSymbol);System.out.println("\nStored Unicode Characters Directly:");System.out.println("Letter Z: "+ letterZ);System.out.println("Greek Capital Letter Omega: "+ letterOmega);System.out.println("Registered Symbol: "+ registeredSymbol);}}

    Compile and run above program. This will produce the following result −

    Output

    Stored Unicode Characters using Escape Sequences:
    Letter A: A
    Greek Capital Letter Sigma: Σ
    Copyright Symbol: ©
    
    Stored Unicode Characters Directly:
    Letter Z: Z
    Greek Capital Letter Omega: Ω
    Registered Symbol: ®
    

    Example 3: Assigning Unicode Characters and Values to Variables

    This example demonstrates how to manipulate the stored Unicode characters. It calculates the difference between the capital letter ‘A’ and the small letter ‘a’ and uses that difference to calculate the capital letter ‘C.’ It then calculates the small letter ‘c’ by adding 32 to the Unicode code point of the capital letter ‘C.’ The manipulated Unicode characters are printed to the console.

    packagecom.tutorialspoint;publicclassUnicodeCharacterDemo{publicstaticvoidmain(String[] args){// Storing Unicode characters using escape sequenceschar letterA ='\u0041';char letterSmallA ='\u0061';// Storing Unicode characters directlychar letterB ='B';// Manipulating the stored Unicode charactersint difference = letterA - letterSmallA;char letterC =(char)(letterB + difference);char letterSmallC =(char)(letterC +32);// Printing the manipulated Unicode charactersSystem.out.println("Manipulated Unicode Characters:");System.out.println("Difference between A and a: "+ difference);System.out.println("Calculated Letter C: "+ letterC);System.out.println("Calculated Letter c: "+ letterSmallC);}}

    Compile and run above program. This will produce the following result −

    Output

    Manipulated Unicode Characters:
    Difference between A and a: -32
    Calculated Letter C: "
    Calculated Letter c: B