Author: Saim Khalid

  • Dynamic Arrays

    dynamic array is an array, the size of which is not known at compile time, but will be known at execution time.

    Dynamic arrays are declared with the attribute allocatable.

    For example,

    real, dimension (:,:), allocatable :: darray    

    The rank of the array, i.e., the dimensions has to be mentioned however, to allocate memory to such an array, you use the allocate function.

    allocate ( darray(s1,s2) )      

    After the array is used, in the program, the memory created should be freed using the deallocate function

    deallocate (darray)  

    Example

    The following example demonstrates the concepts discussed above.

    program dynamic_array 
    implicit none 
    
       !rank is 2, but size not known   
       real, dimension (:,:), allocatable :: darray    
       integer :: s1, s2     
       integer :: i, j     
       
       print*, "Enter the size of the array:"     
       read*, s1, s2      
       
       ! allocate memory      
       allocate ( darray(s1,s2) )      
       
       do i = 1, s1           
    
      do j = 1, s2                
         darray(i,j) = i*j               
         print*, "darray(",i,",",j,") = ", darray(i,j)           
      end do      
    end do deallocate (darray) end program dynamic_array

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

    Enter the size of the array: 3,4
    darray( 1 , 1 ) = 1.00000000    
    darray( 1 , 2 ) = 2.00000000    
    darray( 1 , 3 ) = 3.00000000    
    darray( 1 , 4 ) = 4.00000000    
    darray( 2 , 1 ) = 2.00000000    
    darray( 2 , 2 ) = 4.00000000    
    darray( 2 , 3 ) = 6.00000000    
    darray( 2 , 4 ) = 8.00000000    
    darray( 3 , 1 ) = 3.00000000    
    darray( 3 , 2 ) = 6.00000000    
    darray( 3 , 3 ) = 9.00000000    
    darray( 3 , 4 ) = 12.0000000   
    

    Use of Data Statement

    The data statement can be used for initialising more than one array, or for array section initialisation.

    The syntax of data statement is −

    data variable / list / ...
    

    Example

    The following example demonstrates the concept −

    program dataStatement
    implicit none
    
       integer :: a(5), b(3,3), c(10),i, j
       data a /7,8,9,10,11/ 
       
       data b(1,:) /1,1,1/ 
       data b(2,:)/2,2,2/ 
       data b(3,:)/3,3,3/ 
       data (c(i),i = 1,10,2) /4,5,6,7,8/ 
       data (c(i),i = 2,10,2)/5*2/
       
       Print *, 'The A array:'
       do j = 1, 5                
    
      print*, a(j)           
    end do Print *, 'The B array:' do i = lbound(b,1), ubound(b,1)
      write(*,*) (b(i,j), j = lbound(b,2), ubound(b,2))
    end do Print *, 'The C array:' do j = 1, 10
      print*, c(j)           
    end do end program dataStatement

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

     The A array:
    
           7
           8
           9
          10
          11
    The B array:
           1           1           1
           2           2           2
           3           3           3
    The C array:
           4
           2
           5
           2
           6
           2
           7
           2
           8
           2

    Use of Where Statement

    The where statement allows you to use some elements of an array in an expression, depending on the outcome of some logical condition. It allows the execution of the expression, on an element, if the given condition is true.

    Example

    The following example demonstrates the concept −

    program whereStatement
    implicit none
    
       integer :: a(3,5), i , j
       
       do i = 1,3
    
      do j = 1, 5                
         a(i,j) = j-i          
      end do 
    end do Print *, 'The A array:' do i = lbound(a,1), ubound(a,1)
      write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
    end do where( a<0 )
      a = 1 
    elsewhere
      a = 5
    end where Print *, 'The A array:' do i = lbound(a,1), ubound(a,1)
      write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2))
    end do end program whereStatement

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

     The A array:
    
           0           1           2           3           4
          -1           0           1           2           3
          -2          -1           0           1           2
    The A array:
           5           5           5           5           5
           1           5           5           5           5
           1           1           5           5           5
  • Type Casting

    Java Type Casting (Type Conversion)

    Type casting is a technique that is used either by the compiler or a programmer to convert one data type to another. For example, converting int to double, double to int, short to int, etc. Type typing is also known as Type conversion.

    There are two types of cast typing allowed in Java programming:

    • Widening type casting
    • Narrowing type casting

    Widening Type Casting

    Widening Type Casting is also known as implicit type casting in which a smaller type is converted into a larger type, it is done by the compiler automatically.

    Here is the hierarchy of widening type casting in Java:

    byte>short>char>int>long>float>double

    The compiler plays a role in the type conversion but not the programmers. It changes the type of the variables at the compile time. Also, type conversion occurs from the small data type to large data type only.

    Example 1: Widening Type Casting

    In the example below, we demonstrated that we can get an error when the compiler tries to convert a large data type to a small data type. Here, we created the num1 integer and num2 double variable. The sum of num1 and num2 will be double, and when we try to store it to the sum of the int type, the compiler gives an error.

    packagecom.tutorialspoint;publicclassTester{// Main driver methodpublicstaticvoidmain(String[] args){// Define int variablesint num1 =5004;double num2 =2.5;int sum = num1 + num2;// show outputSystem.out.println("The sum of "+ num1 +" and "+ num2 +" is "+ sum);}}

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

    Output

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    	Type mismatch: cannot convert from double to int
    
    	at com.tutorialspoint.Tester.main(Tester.java:9)
    

    Example 2: Widening Type Casting

    In the example below, we created the num1 and num2 variables as same in the first example. We store the sum of both numbers in the sum variable of double type. In the output, we can observe the sum of double type.

    packagecom.tutorialspoint;publicclassTester{// Main driver methodpublicstaticvoidmain(String[] args){// Define int variablesint num1 =5004;double num2 =2.5;double sum = num1 + num2;// show outputSystem.out.println("The sum of "+ num1 +" and "+ num2 +" is "+ sum);}}

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

    Output

    The sum of 5004 and 2.5 is 5006.5
    

    Narrowing Type Casting

    Narrowing type casting is also known as explicit type casting or explicit type conversion which is done by the programmer manually. In the narrowing type casting a larger type can be converted into a smaller type.

    When a programmer changes the variable type while writing the code. We can use the cast operator to change the type of the variable. For example, double to int or int to double.

    Syntax

    Below is the syntax for narrowing type casting i.e., to manually type conversion:

    double doubleNum =(double) num;

    The above code statement will convert the variable to double type.

    Example: Narrowing Type Casting

    In the example below, we define the num variable of integer type and initialize it with the value. Also, we define the doubleNum variable of double type and store the num variable’s value after converting it to the double.

    Next, We created the ‘convertedInt’ integer type variable and stored the double value after type casting to int. In the output, we can observe the value of the double and int variables.

    packagecom.tutorialspoint;publicclassTester{// Main driver methodpublicstaticvoidmain(String[] args){// Define int variableint num =5004;// Type casting int to doubledouble doubleNum =(double) num;// show outputSystem.out.println("The value of "+ num +" after converting to the double is "+ doubleNum);// Type casting double to intint convertedInt =(int) doubleNum;// show outputSystem.out.println("The value of "+ doubleNum +" after converting to the int again is "+ convertedInt);}}

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

    Output

    The value of 5004 after converting to the double is 5004.0
    The value of 5004.0 after converting to the int again is 5004
    
  • Data Types

    Data types define the type and value range of the data for the different types of variables, constants, method parameters, returns type, etc. The data type tells the compiler about the type of data to be stored and the required memory. To store and manipulate different types of data, all variables must have specified data types.

    Java data types are categorized into two parts −

    • Primitive Data Types
    • Reference/Object Data Types

    Java Primitive Data Types

    Primitive data types are predefined by the language and named by a keyword. There are eight primitive data types supported by Java. Below is the list of the primitive data types:

    • byte
    • short
    • int
    • long
    • float
    • double
    • boolean

    Java byte Data Type

    • Byte data type is an 8-bit signed two’s complement integer
    • Minimum value is -128 (-2^7)
    • Maximum value is 127 (inclusive)(2^7 -1)
    • Default value is 0
    • Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.
    • Example − byte a = 100, byte b = -50

    Java short Data Type

    • Short data type is a 16-bit signed two’s complement integer
    • Minimum value is -32,768 (-2^15)
    • Maximum value is 32,767 (inclusive) (2^15 -1)
    • Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer
    • Default value is 0.
    • Example − short s = 10000, short r = -20000

    Java int Data Type

    • Int data type is a 32-bit signed two’s complement integer.
    • Minimum value is – 2,147,483,648 (-2^31)
    • Maximum value is 2,147,483,647(inclusive) (2^31 -1)
    • Integer is generally used as the default data type for integral values unless there is a concern about memory.
    • The default value is 0
    • Example − int a = 100000, int b = -200000

    Java long Data Type

    • Long data type is a 64-bit signed two’s complement integer
    • Minimum value is -9,223,372,036,854,775,808(-2^63)
    • Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
    • This type is used when a wider range than int is needed
    • Default value is 0L
    • Example − long a = 100000L, long b = -200000L

    Java float Data Type

    • Float data type is a single-precision 32-bit IEEE 754 floating point
    • Float is mainly used to save memory in large arrays of floating point numbers
    • Default value is 0.0f
    • Float data type is never used for precise values such as currency
    • Example − float f1 = 234.5f

    Java double Data Type

    • double data type is a double-precision 64-bit IEEE 754 floating point
    • This data type is generally used as the default data type for decimal values, generally the default choice
    • Double data type should never be used for precise values such as currency
    • Default value is 0.0d
    • Example − double d1 = 123.4

    Java boolean Data Type

    • boolean data type represents one bit of information
    • There are only two possible values: true and false
    • This data type is used for simple flags that track true/false conditions
    • Default value is false
    • Example − boolean one = true

    Java char Data Type

    • char data type is a single 16-bit Unicode character
    • Minimum value is ‘\u0000’ (or 0)
    • Maximum value is ‘\uffff’ (or 65,535 inclusive)
    • Char data type is used to store any character
    • Example − char letterA = ‘A’

    Example: Demonstrating Different Primitive Data Types

    Following examples shows the usage of variour primitive data types we’ve discussed above. We’ve used add operations on numeric data types whereas boolean and char variables are printed as such.

    publicclassJavaTester{publicstaticvoidmain(String args[]){byte byteValue1 =2;byte byteValue2 =4;byte byteResult =(byte)(byteValue1 + byteValue2);System.out.println("Byte: "+ byteResult);short shortValue1 =2;short shortValue2 =4;short shortResult =(short)(shortValue1 + shortValue2);System.out.println("Short: "+ shortResult);int intValue1 =2;int intValue2 =4;int intResult = intValue1 + intValue2;System.out.println("Int: "+ intResult);long longValue1 =2L;long longValue2 =4L;long longResult = longValue1 + longValue2;System.out.println("Long: "+ longResult);float floatValue1 =2.0f;float floatValue2 =4.0f;float floatResult = floatValue1 + floatValue2;System.out.println("Float: "+ floatResult);double doubleValue1 =2.0;double doubleValue2 =4.0;double doubleResult = doubleValue1 + doubleValue2;System.out.println("Double: "+ doubleResult);boolean booleanValue =true;System.out.println("Boolean: "+ booleanValue);char charValue ='A';System.out.println("Char: "+ charValue);}}

    Output

    Byte: 6
    Short: 6
    Int: 6
    Long: 6
    Float: 6.0
    Double: 6.0
    Boolean: true
    Char: A
    

    Java Reference/Object Data Type

    The reference data types are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc.

    Class objects and various types of array variables come under reference datatype. The default value of any reference variable is null. A reference variable can be used to refer to any object of the declared type or any compatible type.

    Example

    The following example demonstrates the reference (or, object) data types.

    // Creating an object of 'Animal' classAnimal animal =newAnimal("giraffe");// Creating an object of 'String' classString myString =newString("Hello, World!");
  • Arrays

    Arrays can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

    All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

    Numbers(1)Numbers(2)Numbers(3)Numbers(4)

    Arrays can be one- dimensional (like vectors), two-dimensional (like matrices) and Fortran allows you to create up to 7-dimensional arrays.

    Declaring Arrays

    Arrays are declared with the dimension attribute.

    For example, to declare a one-dimensional array named number, of real numbers containing 5 elements, you write,

    real, dimension(5) :: numbers

    The individual elements of arrays are referenced by specifying their subscripts. The first element of an array has a subscript of one. The array numbers contains five real variables –numbers(1), numbers(2), numbers(3), numbers(4), and numbers(5).

    To create a 5 x 5 two-dimensional array of integers named matrix, you write −

    integer, dimension (5,5) :: matrix  

    You can also declare an array with some explicit lower bound, for example −

    real, dimension(2:6) :: numbers
    integer, dimension (-3:2,0:4) :: matrix  

    Assigning Values

    You can either assign values to individual members, like,

    numbers(1) = 2.0
    or, you can use a loop,
    do i  =1,5
       numbers(i) = i * 2.0
    end do

    One-dimensional array elements can be directly assigned values using a short hand symbol, called array constructor, like,

    numbers = (/1.5, 3.2,4.5,0.9,7.2 /)
    

    please note that there are no spaces allowed between the brackets ‘( ‘and the back slash ‘/’

    Example

    The following example demonstrates the concepts discussed above.

    Live Demo

    program arrayProg
    
       real :: numbers(5) !one dimensional integer array
       integer :: matrix(3,3), i , j !two dimensional real array
       
       !assigning some values to the array numbers
       do i=1,5
    
      numbers(i) = i * 2.0
    end do !display the values do i = 1, 5
      Print *, numbers(i)
    end do !assigning some values to the array matrix do i=1,3
      do j = 1, 3
         matrix(i, j) = i+j
      end do
    end do !display the values do i=1,3
      do j = 1, 3
         Print *, matrix(i,j)
      end do
    end do !short hand assignment numbers = (/1.5, 3.2,4.5,0.9,7.2 /) !display the values do i = 1, 5
      Print *, numbers(i)
    end do end program arrayProg

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

     2.00000000    
     4.00000000    
     6.00000000    
     8.00000000    
     10.0000000    
    
         2
         3
         4
         3
         4
         5
         4
         5
         6
    1.50000000 3.20000005 4.50000000 0.899999976 7.19999981

    Some Array Related Terms

    The following table gives some array related terms −

    TermMeaning
    RankIt is the number of dimensions an array has. For example, for the array named matrix, rank is 2, and for the array named numbers, rank is 1.
    ExtentIt is the number of elements along a dimension. For example, the array numbers has extent 5 and the array named matrix has extent 3 in both dimensions.
    ShapeThe shape of an array is a one-dimensional integer array, containing the number of elements (the extent) in each dimension. For example, for the array matrix, shape is (3, 3) and the array numbers it is (5).
    SizeIt is the number of elements an array contains. For the array matrix, it is 9, and for the array numbers, it is 5.

    Passing Arrays to Procedures

    You can pass an array to a procedure as an argument. The following example demonstrates the concept −

    program arrayToProcedure      
    implicit none      
    
       integer, dimension (5) :: myArray  
       integer :: i
       
       call fillArray (myArray)      
       call printArray(myArray)
       
    end program arrayToProcedure
    
    
    subroutine fillArray (a)      
    implicit none      
    
       integer, dimension (5), intent (out) :: a
       
       ! local variables     
       integer :: i     
       do i = 1, 5         
    
      a(i) = i      
    end do end subroutine fillArray subroutine printArray(a) integer, dimension (5) :: a integer::i do i = 1, 5
      Print *, a(i)
    end do end subroutine printArray

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

    1
    2
    3
    4
    5
    

    In the above example, the subroutine fillArray and printArray can only be called with arrays with dimension 5. However, to write subroutines that can be used for arrays of any size, you can rewrite it using the following technique −

    Live Demo

    program arrayToProcedure      
    implicit  none    
    
       integer, dimension (10) :: myArray  
       integer :: i
       
       interface 
    
      subroutine fillArray (a)
         integer, dimension(:), intent (out) :: a 
         integer :: i         
      end subroutine fillArray      
      subroutine printArray (a)
         integer, dimension(:) :: a 
         integer :: i         
      end subroutine printArray   
    end interface call fillArray (myArray) call printArray(myArray) end program arrayToProcedure subroutine fillArray (a) implicit none integer,dimension (:), intent (out) :: a ! local variables integer :: i, arraySize arraySize = size(a) do i = 1, arraySize
      a(i) = i      
    end do end subroutine fillArray subroutine printArray(a) implicit none integer,dimension (:) :: a integer::i, arraySize arraySize = size(a) do i = 1, arraySize
     Print *, a(i)
    end do end subroutine printArray

    Please note that the program is using the size function to get the size of the array.

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    Array Sections

    So far we have referred to the whole array, Fortran provides an easy way to refer several elements, or a section of an array, using a single statement.

    To access an array section, you need to provide the lower and the upper bound of the section, as well as a stride (increment), for all the dimensions. This notation is called a subscript triplet:

    array ([lower]:[upper][:stride], ...)

    When no lower and upper bounds are mentioned, it defaults to the extents you declared, and stride value defaults to 1.

    The following example demonstrates the concept −

    Live Demo

    program arraySubsection
    
       real, dimension(10) :: a, b
       integer:: i, asize, bsize
       
       a(1:7) = 5.0 ! a(1) to a(7) assigned 5.0
       a(8:) = 0.0  ! rest are 0.0 
       b(2:10:2) = 3.9
       b(1:9:2) = 2.5
       
       !display
       asize = size(a)
       bsize = size(b)
       
       do i = 1, asize
    
      Print *, a(i)
    end do do i = 1, bsize
      Print *, b(i)
    end do end program arraySubsection

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

    5.00000000    
    5.00000000    
    5.00000000    
    5.00000000    
    5.00000000    
    5.00000000    
    5.00000000    
    0.00000000E+00
    0.00000000E+00
    0.00000000E+00
    2.50000000    
    3.90000010    
    2.50000000    
    3.90000010    
    2.50000000    
    3.90000010    
    2.50000000    
    3.90000010    
    2.50000000    
    3.90000010 
    

    Array Intrinsic Functions

    Fortran 90/95 provides several intrinsic procedures. They can be divided into 7 categories.

  • Variable Types

    What is a Java Variable?

    A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

    Variable Declaration and Initialization

    You must declare all variables before they can be used. Following is the basic form of a variable declaration −

    data type variable [= value][, variable [= value]...];

    Here data type is one of Java’s data types and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.

    Example of Valid Variables Declarations and Initializations

    Following are valid examples of variable declaration and initialization in Java −

    int a, b, c;// Declares three ints, a, b, and c.int a =10, b =10;// Example of initializationbyteB=22;// initializes a byte type variable B.double pi =3.14159;// declares and assigns a value of PI.char a ='a';// the char variable a iis initialized with value 'a'

    Java Variables Types

    The following are the three types of Java variables:

    • Local variables
    • Instance variables
    • Class/Static variables

    1. Java Local Variables

    • Local variables are declared in methods, constructors, or blocks.
    • Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
    • Access modifiers cannot be used for local variables.
    • Local variables are visible only within the declared method, constructor, or block.
    • Local variables are implemented at stack level internally.
    • There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.

    Example 1: Variable’s local scope with initialization

    Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method.

    publicclassTest{publicvoidpupAge(){int age =0;
    
      age = age +7;System.out.println("Puppy age is : "+ age);}publicstaticvoidmain(String args&#91;]){Test test =newTest();
      test.pupAge();}}</code></pre>

    Output

    Puppy age is: 7
    

    Example 2: Variable's local scope without initialization

    Following example uses age without initializing it, so it would give an error at the time of compilation.

    publicclassTest{publicvoidpupAge(){int age;
    
      age = age +7;System.out.println("Puppy age is : "+ age);}publicstaticvoidmain(String args&#91;]){Test test =newTest();
      test.pupAge();}}</code></pre>

    Output

    Test.java:4:variable number might not have been initialized
    age = age + 7;
    
         ^
    1 error

    2. Java Instance Variables

    • Instance variables are declared in a class, but outside a method, constructor or any block.
    • When a space is allocated for an object in the heap, a slot for each instance variable value is created.
    • Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.
    • Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
    • Instance variables can be declared in class level before or after use.
    • Access modifiers can be given for instance variables.
    • The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers.
    • Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor.
    • Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.

    Example of Java Instance Variables

    importjava.io.*;publicclassEmployee{// this instance variable is visible for any child class.publicString name;// salary  variable is visible in Employee class only.privatedouble salary;// The name variable is assigned in the constructor.publicEmployee(String empName){
    
      name = empName;}// The salary variable is assigned a value.publicvoidsetSalary(double empSal){
      salary = empSal;}// This method prints the employee details.publicvoidprintEmp(){System.out.println("name  : "+ name );System.out.println("salary :"+ salary);}publicstaticvoidmain(String args&#91;]){Employee empOne =newEmployee("Ransika");
      empOne.setSalary(1000);
      empOne.printEmp();}}</code></pre>

    Output

    name  : Ransika
    salary :1000.0
    

    3. Java Class/Static Variables

    • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
    • There would only be one copy of each class variable per class, regardless of how many objects are created from it.
    • Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
    • Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
    • Static variables are created when the program starts and destroyed when the program stops.
    • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
    • Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.
    • Static variables can be accessed by calling with the class name ClassName.VariableName.
    • When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

    Example of Java Class/Static Variables

    importjava.io.*;publicclassEmployee{// salary  variable is a private static variableprivatestaticdouble salary;// DEPARTMENT is a constantpublicstaticfinalStringDEPARTMENT="Development ";publicstaticvoidmain(String args[]){
    
      salary =1000;System.out.println(DEPARTMENT+"average salary:"+ salary);}}</code></pre>

    Output

    Development average salary:1000
    
  • Strings

    The Fortran language can treat characters as single character or contiguous strings.

    A character string may be only one character in length, or it could even be of zero length. In Fortran, character constants are given between a pair of double or single quotes.

    The intrinsic data type character stores characters and strings. The length of the string can be specified by len specifier. If no length is specified, it is 1. You can refer individual characters within a string referring by position; the left most character is at position 1.

    String Declaration

    Declaring a string is same as other variables −

    type-specifier :: variable_name
    

    For example,

    Character(len = 20) :: firstname, surname
    you can assign a value like,
    character (len = 40) :: name  
    name = “Zara Ali”

    The following example demonstrates declaration and use of character data type −

    program hello
    implicit none
    
       character(len = 15) :: surname, firstname 
       character(len = 6) :: title 
       character(len = 25)::greetings
       
       title = 'Mr.' 
       firstname = 'Rowan' 
       surname = 'Atkinson'
       greetings = 'A big hello from Mr. Beans'
       
       print *, 'Here is', title, firstname, surname
       print *, greetings
       
    end program hello

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

    Here isMr.   Rowan          Atkinson       
    A big hello from Mr. Bean
    

    String Concatenation

    The concatenation operator //, concatenates strings.

    The following example demonstrates this −

    program hello
    implicit none
    
       character(len = 15) :: surname, firstname 
       character(len = 6) :: title 
       character(len = 40):: name
       character(len = 25)::greetings
       
       title = 'Mr.' 
       firstname = 'Rowan' 
       surname = 'Atkinson'
       
       name = title//firstname//surname
       greetings = 'A big hello from Mr. Beans'
       
       print *, 'Here is', name
       print *, greetings
       
    end program hello

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

    Here is Mr. Rowan Atkinson       
    A big hello from Mr. Bean
    

    Extracting Substrings

    In Fortran, you can extract a substring from a string by indexing the string, giving the start and the end index of the substring in a pair of brackets. This is called extent specifier.

    The following example shows how to extract the substring ‘world’ from the string ‘hello world’ −

    Live Demo

    program subString
    
       character(len = 11)::hello
       hello = "Hello World"
       print*, hello(7:11)
       
    end program subString 

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

    World
    

    Example

    The following example uses the date_and_time function to give the date and time string. We use extent specifiers to extract the year, date, month, hour, minutes and second information separately.

    Live Demo

    program  datetime
    implicit none
    
       character(len = 8) :: dateinfo ! ccyymmdd
       character(len = 4) :: year, month*2, day*2
    
       character(len = 10) :: timeinfo ! hhmmss.sss
       character(len = 2)  :: hour, minute, second*6
    
       call  date_and_time(dateinfo, timeinfo)
    
       !  let’s break dateinfo into year, month and day.
       !  dateinfo has a form of ccyymmdd, where cc = century, yy = year
       !  mm = month and dd = day
    
       year  = dateinfo(1:4)
       month = dateinfo(5:6)
       day   = dateinfo(7:8)
    
       print*, 'Date String:', dateinfo
       print*, 'Year:', year
       print *,'Month:', month
       print *,'Day:', day
    
       !  let’s break timeinfo into hour, minute and second.
       !  timeinfo has a form of hhmmss.sss, where h = hour, m = minute
       !  and s = second
    
       hour   = timeinfo(1:2)
       minute = timeinfo(3:4)
       second = timeinfo(5:10)
    
       print*, 'Time String:', timeinfo
       print*, 'Hour:', hour
       print*, 'Minute:', minute
       print*, 'Second:', second   
       
    end program  datetime

    When you compile and execute the above program, it gives the detailed date and time information −

    Date String: 20140803
    Year: 2014
    Month: 08
    Day: 03
    Time String: 075835.466
    Hour: 07
    Minute: 58
    Second: 35.466
    

    Trimming Strings

    The trim function takes a string, and returns the input string after removing all trailing blanks.

    Example

    Live Demo

    program trimString
    implicit none
    
       character (len = *), parameter :: fname="Susanne", sname="Rizwan"
       character (len = 20) :: fullname 
       
       fullname = fname//" "//sname !concatenating the strings
       
       print*,fullname,", the beautiful dancer from the east!"
       print*,trim(fullname),", the beautiful dancer from the east!"
       
    end program trimString

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

    Susanne Rizwan      , the beautiful dancer from the east!
     Susanne Rizwan, the beautiful dancer from the east!
    

    Left and Right Adjustment of Strings

    The function adjustl takes a string and returns it by removing the leading blanks and appending them as trailing blanks.

    The function adjustr takes a string and returns it by removing the trailing blanks and appending them as leading blanks.

    Example

    Live Demo

    program hello
    implicit none
    
       character(len = 15) :: surname, firstname 
       character(len = 6) :: title 
       character(len = 40):: name
       character(len = 25):: greetings
       
       title = 'Mr. ' 
       firstname = 'Rowan' 
       surname = 'Atkinson'
       greetings = 'A big hello from Mr. Beans'
       
       name = adjustl(title)//adjustl(firstname)//adjustl(surname)
       print *, 'Here is', name
       print *, greetings
       
       name = adjustr(title)//adjustr(firstname)//adjustr(surname)
       print *, 'Here is', name
       print *, greetings
       
       name = trim(title)//trim(firstname)//trim(surname)
       print *, 'Here is', name
       print *, greetings
       
    end program hello

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

    Here is Mr. Rowan  Atkinson           
    A big hello from Mr. Bean
    Here is Mr. Rowan Atkinson    
    A big hello from Mr. Bean
    Here is Mr.RowanAtkinson                        
    A big hello from Mr. Bean
    

    Searching for a Substring in a String

    The index function takes two strings and checks if the second string is a substring of the first string. If the second argument is a substring of the first argument, then it returns an integer which is the starting index of the second string in the first string, else it returns zero.

    Example

    Live Demo

    program hello
    implicit none
    
       character(len=30) :: myString
       character(len=10) :: testString
       
       myString = 'This is a test'
       testString = 'test'
       
       if(index(myString, testString) == 0)then
    
      print *, 'test is not found'
    else
      print *, 'test is found at index: ', index(myString, testString)
    end if end program hello

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

    test is found at index: 11
    
  • Basic Syntax

    When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods, and instance variables mean.

    • Object − Objects have states and behaviors. Example: A dog has states – color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.
    • Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
    • Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
    • Instance Variables − Each object has its unique set of instance variables. An object’s state is created by the values assigned to these instance variables.

    First Java Program

    Let us look at a simple code that will print the words Hello World.

    Example

    publicclassMyFirstJavaProgram{/* This is my first java program.
    
    * This will print 'Hello World' as the output
    */publicstaticvoidmain(String&#91;]args){System.out.println("Hello World");// prints Hello World}}</code></pre>

    Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −

    • Open notepad and add the code as above.
    • Save the file as: MyFirstJavaProgram.java.
    • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
    • Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).
    • Now, type ' java MyFirstJavaProgram ' to run your program.
    • You will be able to see ' Hello World ' printed on the window.

    Output

    C:\> javac MyFirstJavaProgram.java
    C:\> java MyFirstJavaProgram 
    Hello World
    

    Basic Syntax

    About Java programs, it is very important to keep in mind the following points.

    • Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
    • Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.Example − class MyFirstJavaClass
    • Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.Example − public void myMethodName()
    • Program File Name − Name of the program file should exactly match the class name.When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file.Example − Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
    • public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.

    Java Identifiers

    All Java components require names. Names used for classes, variables, and methods are called identifiers.

    In Java, there are several points to remember about identifiers. They are as follows −

    • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
    • After the first character, identifiers can have any combination of characters.
    • A key word cannot be used as an identifier.
    • Most importantly, identifiers are case sensitive.
    • Examples of legal identifiers: age, $salary, _value, __1_value.
    • Examples of illegal identifiers: 123abc, -salary.

    Java Modifiers

    Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −

    • Access Modifiers − default, public , protected, private
    • Non-access Modifiers − final, abstract, strictfp

    We will be looking into more details about modifiers in the next section.

    Java Variables

    Following are the types of variables in Java −

    • Local Variables
    • Class Variables (Static Variables)
    • Instance Variables (Non-static Variables)

    Java Arrays

    Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters.

    Java Enums

    Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.

    With the use of enums it is possible to reduce the number of bugs in your code.

    For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.

    Example

    classFreshJuice{enumFreshJuiceSize{SMALL,MEDIUM,LARGE}FreshJuiceSize size;}publicclassFreshJuiceTest{publicstaticvoidmain(String args[]){FreshJuice juice =newFreshJuice();
    
      juice.size =FreshJuice.FreshJuiceSize.MEDIUM;System.out.println("Size: "+ juice.size);}}</code></pre>

    Output

    The above example will produce the following result −

    Size: MEDIUM
    

    Note − Enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

    Java Keywords

    The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

    Sr.NoReserved Words & Description
    1abstractAs per dictionary, abstraction is the quality of dealing with ideas rather than events.
    2assertassert keyword is used in Java to define assertion. An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program.
    3booleanboolean datatype is one of the eight primitive datatype supported by Java. It provides means to create boolean type variables which can accept a boolean value as true or false.
    4breakThe break statement in Java programming language has the following two usages −When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.It can be used to terminate a case in the switch statement.
    5bytebyte datatype is one of the eight primitive datatype supported by Java. It provides means to create byte type variables which can accept a byte value.
    6casecase keyword is part of switch statement which allows a variable to be tested for equality against a list of values.
    7catchAn exception (or exceptional event) is a problem that arises during the execution of a program.
    8charchar datatype is one of the eight primitive datatype supported by Java.
    9classJava is an Object-Oriented Language. As a language that has the Object-Oriented feature.
    10constfinal keyword is used to define constant value or final methods/classes in Java.
    11continueThe continue keyword can be used in any of the loop control structures.
    12defaultdefault keyword is part of switch statement which allows a variable to be tested for equality against a list of values.
    13doA do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
    14doubledouble datatype is one of the eight primitive datatype supported by Java.
    15ifAn if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
    16enumThe Java Enum class is the common base class of all Java language enumeration types.
    17extendsextends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.
    18finalfinal keyword is used to define constant value or final methods/classes in Java.
    19finallyfinally keyword is used to define a finally block. The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
    20floatfloat datatype is one of the eight primitive datatype supported by Java. It provides means to create float type variables which can accept a float value.
    21forA for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.
    22gotogoto statement is not supported by Java currrenly. It is kept as a reserved keyword for future. As an alternative, Java supports labels with break and continue statement.
    23ifAn if statement consists of a Boolean expression followed by one or more statements.
    24implementsGenerally, the implements keyword is used with classes to inherit the properties of an interface.
    25importimport keyboard is used in context of packages.
    26instanceofinstanceof keyword is an operator which is used only for object reference variables.
    27intint datatype is one of the eight primitive datatype supported by Java.
    28interfaceAn interface is a reference type in Java. It is similar to class. It is a collection of abstract methods.
    29longlong datatype is one of the eight primitive datatype supported by Java.
    30native
    31new
    32packagePackages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
    33privateMethods, variables, and constructors that are declared private can only be accessed within the declared class itself.
    34protectedThe protected access modifier cannot be applied to class and interfaces.
    35publicA class, method, constructor, interface, etc. declared public can be accessed from any other class.
    36return
    37shortBy assigning different data types to variables, you can store integers, decimals, or characters in these variables.
    38staticThe static keyword is used to create variables that will exist independently of any instances created for the class.
    39strictfp
    40superThe super keyword is similar to this keyword.
    41switchA switch statement allows a variable to be tested for equality against a list of values.
    42synchronized
    43thisthis keyword is a very important keyword to identify an object. Following are the usage of this keyword.
    44throwIf a method does not handle a checked exception, the method must declare it using the throws keyword.
    45transientSerialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI).
    46tryA method catches an exception using a combination of the try and catch keywords.
    47void
    48volatile
    49whileA while loop statement in Java programming language repeatedly executes a target statement as long as a given condition is true.

    Comments in Java

    Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.

    Example

    publicclassMyFirstJavaProgram{/* This is my first java program.
    
    * This will print 'Hello World' as the output
    * This is an example of multi-line comments.
    */publicstaticvoidmain(String&#91;]args){// This is an example of single line comment/* This is also an example of single line comment. */System.out.println("Hello World");}}</code></pre>

    Output

    Hello World
    

    Using Blank Lines

    A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.

    Inheritance

    In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.

    This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.

    Interfaces

    In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.

    An interface defines the methods, a deriving class (subclass) should use. But the implementation of the methods is totally up to the subclass.

  • Numbers

    Numbers in Fortran are represented by three intrinsic data types −

    • Integer type
    • Real type
    • Complex type

    Integer Type

    The integer types can hold only integer values. The following example extracts the largest value that could be hold in a usual four byte integer −

    program testingInt
    implicit none
    
       integer :: largeval
       print *, huge(largeval)
       
    end program testingInt

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

    2147483647
    

    Please note that the huge() function gives the largest number that can be held by the specific integer data type. You can also specify the number of bytes using the kind specifier. The following example demonstrates this −

    program testingInt
    implicit none
    
       !two byte integer
       integer(kind = 2) :: shortval
       
       !four byte integer
       integer(kind = 4) :: longval
       
       !eight byte integer
       integer(kind = 8) :: verylongval
       
       !sixteen byte integer
       integer(kind = 16) :: veryverylongval
       
       !default integer 
       integer :: defval
    
        
    print *, huge(shortval) print *, huge(longval) print *, huge(verylongval) print *, huge(veryverylongval) print *, huge(defval) end program testingInt

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

    32767
    2147483647
    9223372036854775807
    170141183460469231731687303715884105727
    2147483647
    

    Real Type

    It stores the floating point numbers, such as 2.0, 3.1415, -100.876, etc.

    Traditionally there were two different real types : the default real type and double precision type.

    However, Fortran 90/95 provides more control over the precision of real and integer data types through the kind specifier, which we will study shortly.

    The following example shows the use of real data type −

    program division   
    implicit none
    
       ! Define real variables   
       real :: p, q, realRes 
       
       ! Define integer variables  
       integer :: i, j, intRes  
       
       ! Assigning  values   
       p = 2.0 
       q = 3.0    
       i = 2 
       j = 3  
       
       ! floating point division
       realRes = p/q  
       intRes = i/j
       
       print *, realRes
       print *, intRes
       
    end program division  

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

    0.666666687    
    0
    

    Complex Type

    This is used for storing complex numbers. A complex number has two parts : the real part and the imaginary part. Two consecutive numeric storage units store these two parts.

    For example, the complex number (3.0, -5.0) is equal to 3.0 – 5.0i

    The generic function cmplx() creates a complex number. It produces a result who’s real and imaginary parts are single precision, irrespective of the type of the input arguments.

    program createComplex
    implicit none
    
       integer :: i = 10
       real :: x = 5.17
       print *, cmplx(i, x)
       
    end program createComplex

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

    (10.0000000, 5.17000008)
    

    The following program demonstrates complex number arithmetic −

    program ComplexArithmatic
    implicit none
    
       complex, parameter :: i = (0, 1)   ! sqrt(-1)   
       complex :: x, y, z 
       
       x = (7, 8); 
       y = (5, -7)   
       write(*,*) i * x * y
       
       z = x + y
       print *, "z = x + y = ", z
       
       z = x - y
       print *, "z = x - y = ", z 
       
       z = x * y
       print *, "z = x * y = ", z 
       
       z = x / y
       print *, "z = x / y = ", z 
       
    end program ComplexArithmatic

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

    (9.00000000, 91.0000000)
    z = x + y = (12.0000000, 1.00000000)
    z = x - y = (2.00000000, 15.0000000)
    z = x * y = (91.0000000, -9.00000000)
    z = x / y = (-0.283783793, 1.20270276)
    

    The Range, Precision and Size of Numbers

    The range on integer numbers, the precision and the size of floating point numbers depends on the number of bits allocated to the specific data type.

    The following table displays the number of bits and range for integers −

    Number of bitsMaximum valueReason
    649,223,372,036,854,774,807(2**63)–1
    322,147,483,647(2**31)–1

    The following table displays the number of bits, smallest and largest value, and the precision for real numbers.

    Number of bitsLargest valueSmallest valuePrecision
    640.8E+3080.5E–30815–18
    321.7E+380.3E–386-9

    The following examples demonstrate this −

    program rangePrecision
    implicit none
    
       real:: x, y, z
       x = 1.5e+40
       y = 3.73e+40
       z = x * y 
       print *, z
       
    end program rangePrecision

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

    x = 1.5e+40
    
          1
    Error : Real constant overflows its kind at (1) main.f95:5.12: y = 3.73e+40
           1
    Error : Real constant overflows its kind at (1)

    Now let us use a smaller number −

    program rangePrecision
    implicit none
    
       real:: x, y, z
       x = 1.5e+20
       y = 3.73e+20
       z = x * y 
       print *, z
       
       z = x/y
       print *, z
       
    end program rangePrecision

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

    Infinity
    0.402144760   
    

    Now let’s watch underflow −

    Live Demo

    program rangePrecision
    implicit none
    
       real:: x, y, z
       x = 1.5e-30
       y = 3.73e-60
       z = x * y 
       print *, z
       
       z = x/y
       print *, z
    
    end program rangePrecision

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

    y = 3.73e-60
    
           1
    Warning : Real constant underflows its kind at (1) Executing the program.... $demo  0.00000000E+00 Infinity

    The Kind Specifier

    In scientific programming, one often needs to know the range and precision of data of the hardware platform on which the work is being done.

    The intrinsic function kind() allows you to query the details of the hardware’s data representations before running a program.

    program kindCheck
    implicit none
       
       integer :: i 
       real :: r 
       complex :: cp 
       print *,' Integer ', kind(i) 
       print *,' Real ', kind(r) 
       print *,' Complex ', kind(cp) 
       
    end program kindCheck

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

    Integer 4
    Real 4
    Complex 4
    

    You can also check the kind of all data types −

    Live Demo

    program checkKind
    implicit none
    
       integer :: i 
       real :: r 
       character :: c 
       logical :: lg 
       complex :: cp 
       
       print *,' Integer ', kind(i) 
       print *,' Real ', kind(r) 
       print *,' Complex ', kind(cp)
       print *,' Character ', kind(c) 
       print *,' Logical ', kind(lg)
       
    end program checkKind

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

    Integer 4
    Real 4
    Complex 4
    Character 1
    Logical 4
    
  • Environment Setup

    Set Up Your Java Development Environment

    If you want to set up your own environment for Java programming language, then this tutorial guides you through the whole process. Please follow the steps given below to set up your Java environment.

    Java SE is available for download for free. To download click here, please download a version compatible with your operating system.

    Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

    Setting Up the Environment Path for Windows 2000/XP

    Assuming you have installed Java in c:\Program Files\java\jdk directory. Below are the steps to set up the Java environment path for Windows 2000/XP:

    • Right-click on ‘My Computer’ and select ‘Properties’.
    • Click on the ‘Environment variables’ button under the ‘Advanced’ tab.
    • Now, edit the ‘Path’ variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
      C:\Windows\System32;c:\Program Files\java\jdk\bin.

    Setting Up the Environment Path for Windows 95/98/ME

    Assuming you have installed Java in c:\Program Files\java\jdk directory. Below are the steps to set up the Java environment path for Windows 95/98/ME:

    • Edit the ‘C:\autoexec.bat’ file and add the following line at the end −
      SET PATH=%PATH%;C:\Program Files\java\jdk\bin

    Setting Up the Environment Path for Linux, UNIX, Solaris, FreeBSD

    Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

    For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −

    export PATH=/path/to/java:$PATH’

    Online Java Compiler

    We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

    Try the following example using Run & Edit button available at the top right corner of the above sample code box −

    publicclassMyFirstJavaProgram{publicstaticvoidmain(String[]args){System.out.println("Hello World");}}

    For most of the examples given in this tutorial, you will find a Run & Edit option in our website code sections at the top right corner that will take you to the Online Java Compiler. So just make use of it and enjoy your learning.

    Popular Java Editors

    To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −

    • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
    • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
    • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org.

    IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.

  • Hello World Program

    Printing “Hello World” on the output screen (console) is the first program in Java and other programming languages. This tutorial will teach you how you can write your first program (print “Hello World” program) in Java programming.

    Java program to print “Hello World”

    Java program to print “Hello World” is given below:

    publicclassMyFirstJavaProgram{/* This is my first java program.
    
    * This will print 'Hello World' as the output
    */publicstaticvoidmain(String&#91;]args){System.out.println("Hello World");// prints Hello World}}</code></pre>

    Steps to Write, Save, and Run Hello World Program

    Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −

    • Open notepad and add the code as above.
    • Save the file as − "MyFirstJavaProgram.java".
    • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
    • Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there is no error in your code, the command prompt will take you to the next line (Assumption − The path variable is set. Learn: Java Envionment Setup).
    • Now, type 'java MyFirstJavaProgram' to run your program.
    • You will be able to see "Hello World" printed on the screen.

    Output

    C:\> javac MyFirstJavaProgram.java
    C:\> java MyFirstJavaProgram
    Hello World
    

    Explanation of Hello World Program

    As we've successfully printed Hello World on the output screen. Let's understand the code line by line.

    1. Public Main Class

    publicclassMyFirstJavaProgram{

    This line is creating a new class MyFirstJavaProgram and being public, this class is to be defined in the same name file as MyFirstJavaProgram.java. This convention helps Java compiler to identify the name of public class to be created before reading the file content.

    2. Comment Section

    /* This is my first java program.
    * This will print 'Hello World' as the output
    */

    These lines being in /* */ block are not considered by Java compiler and are comments. A comment helps to understand program in a better way and makes code readable and understandable.

    3. Public Static Void Main

    publicstaticvoidmain(String[]args){

    This line represents the main method that JVM calls when this program is loaded into memory. This method is used to execute the program. Once this method is finished, program is finished in single threaded environment.

    4. Keywords Used

    Let's check the purpose of each keyword in this line.

    • public − defines the scope of the main method. Being public, this method can be called by external program like JVM.
    • static − defines the state of the main method. Being static, this method can be called by external program like JVM without first creating the object of the class.
    • void − defines the return type of the main method. Being void, this method is not returning any value.
    • main − name of the method
    • String []args − arguments passed on command line while executing the java command.

    5. System.out.println() Method

    System.out.println("Hello World");// prints Hello World

    System.out represents the primary console and its println() method is taking "Hello World" as input and it prints the same to the console output.