Blog

  • 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
    
  • 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.