Saturday, July 20, 2019


                                   ARRAY IN JAVA


Normally, array is a collection of similar type of elements that have contiguous memory location. Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array

  Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
  Random access: We can get any data located at any index position. 

Disadvantage of Java Array 

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

Types of Array in java

 There are two types of array. 

 Single Dimensional Array

  Multidimensional Array 

Single Dimensional Array in java

 Syntax to Declare an Array in java

 1. dataType[] arr; (or) 
  2. dataType []arr; (or) 
  3. dataType arr[]; 

  Instantiation of an Array in java 

1. arrayRefVar=new datatype[size];

   Example of single dimensional java array 

Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array. 

   
class Testarray{
        public static void main(String args[]){     
  int a[]=new int[5];//declaration and instantiation
   a[0]=10;//initialization
   a[1]=20;
   a[2]=70;
   a[3]=40; 
  a[4]=50;     
 //printing array 
  for(int i=0;i<a.length;i++)//length is the property of array   System.out.println(a[i]);     
 }}   

 Output: 10  
               20 
               70  
               40 
               50   
     

Declaration, Instantiation and Initialization of Java Array 

We can declare, instantiate and initialize the java array together by:
 1. int a[]={33,3,4,5};//declaration, instantiation and initialization 
  Let's see the simple example to print this array. 
         class Testarray1{  
                 public static void main(String args[]){ 
                        int a[]={33,3,4,5};//declaration, instantiation and initialization    
          //printing array  
              for(int i=0;i<a.length;i++)//length is the property of array   System.out.println(a[i]);     
        }}  
 Test it Now  Output: 33      
                                   3      
                                   4      
                                   5     
Passing Array to method in java 

We can pass the java array to method so that we can reuse the same logic on any array.
 Let's see the simple example to get minimum number of an array using method.
       class Testarray2{  
              static void min(int arr[]){
                 int min=arr[0];   
                   for(int i=1;i<arr.length;i++) 
                       if(min>arr[i])    
                               min=arr[i];  
                 System.out.println(min);  
       }     
         public static void main(String args[]){  
         int a[]={33,3,4,5}; 
     min(a);//passing array to method    
     }}   
Test it Now  Output:3


Multidimensional array in java 

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java 

  1. dataType[][] arrayRefVar; (or) 
  2. dataType [][]arrayRefVar; (or) 
  3. dataType arrayRefVar[][]; (or)  
  4. dataType []arrayRefVar[];  
Example to instantiate Multidimensional Array in java
 1. int[][] arr=new int[3][3];//3 row and 3 column   
Example to initialize Multidimensional Array in java
 arr[0][0]=1;   
arr[0][1]=2;   
arr[0][2]=3;   
arr[1][0]=4;   
arr[1][1]=5;   
arr[1][2]=6;   
arr[2][0]=7;   
arr[2][1]=8;   
arr[2][2]=9;  
 Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

            class Testarray3{  
                          public static void main(String args[]){     
            //declaring and initializing 2D array  
                      int arr[][]={{1,2,3},{2,4,5},{4,4,5}};   
           //printing 2D array 
                   for(int i=0;i<3;i++)
          {   
               for(int j=0;j<3;j++)
                   {      
                          System.out.print(arr[i][j]+" ");    
                   }   
                             System.out.println(); 
                    }     
 }} 
    Output:1 2 3       
                                   2 4 5        
                                   4 4 5 

What is the class name of java array?  


In java, array is an object. For array object, an proxy class is created whose name can be obtained by getClass().getName() method on the object. 

        class Testarray4{  
                 public static void main(String args[]){      
             int arr[]={4,4,5};     
          Class c=arr.getClass();   
                          String name=c.getName();    
                 System.out.println(name);   
   }}   

  Output:I 


Copying a java array


We can copy an array to another by the arraycopy method of System class.
 Syntax of arraycopy method 
          public static void arraycopy(   
         Object src, int srcPos,Object dest, int destPos, int length   )  
 Example of arraycopy method
    class TestArrayCopyDemo { 
               public static void main(String[] args) { 
                     char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd' };   
                        char[] copyTo = new char[7];             
                   System.arraycopy(copyFrom, 2, copyTo, 0, 7);        
                                  System.out.println(new String(copyTo));      
 }   }  
  Output:caffein 


Addition of 2 matrices in java

 Let's see a simple example that adds two matrices. 
                    class Testarray5{  
                           public static void main(String args[]){ 
                //creating two matrices   
                                 int a[][]={{1,3,4},{3,4,5}};   
                                      int b[][]={{1,3,4},{3,4,5}};   
                //creating another matrix to store the sum of two matrices  
                                      int c[][]=new int[2][3];  
               //adding and printing addition of 2 matrices  
                                   for(int i=0;i<2;i++)
                                {   
                                        for(int j=0;j<3;j++)
                                           {  
                                                    c[i][j]=a[i][j]+b[i][j]; 
                                                       System.out.print(c[i][j]+" ");  
                                                 }   
                                                            System.out.println();//new line  
                                                   }   
                                    }}   
  Output:2 6 8       
             6 8 10 

Thursday, July 11, 2019

Looping In Java


            Conditional and Lopping Construct



There may be a situation when you need to execute a block of code several number of times. In general, statement are executed sequentially: the first statement in a function  executed first, followed by the second, and so on.
Programming languages provide various control structure that allow for more complicated execution path.
Loop statement allow us to execute a statement or group of statement multiple and following in the general form of a loop statement in most of programming languages 


Java programming language provides the following type of loop to handle looping requirement.
While Loop 
 Repeat  a statement or group of statements while a given condition is true. It test the condition before executing the loop body.

Syntax of while loop

while(Boolean_expression){
//statement
}
here, statement may be a single statement or a block of  statement. The condition may be any expression, and true is any non zero value.
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
When the condition become false, program control passes to the line immediately following the loop.

Flow Chart of while loop


Here, key point of the while loop is that the loop might not ever run. When the expression is tested and result false, the loop body will be skipped and the first statement after the while loop will be executed.

Example  of while loop 

public class test {
  public static void main(String args[]){
       int x=10;

     while(x<20){
      System.out.println("value of x :" +x);
      x++;
System.out.print("\n");
            }
       }
}
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

For Loop

Execute a sequence of statements multiple times and abbreviates the code that manage the loop of variable.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to be executed specific number of times.

Syntax of for loop

for (initialization;Boolean_expression;update){
  //statements
}

Here .....
  • The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semicolon(;).
  • Next, the Boolean_expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of loop will not executed and controls jumps to the next statement past for the loop.
  • After the body of the loop gets executed, the control jumps back up to update statement. This statement allows to update any loop control variables. This statement can be left blank with a semicolon at the end.
  • The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeat(body of loop, then update step, then Boolean_expression).After Boolean_expression is false, the for loop terminates.

Flow Chart of for loop




Example of for loop

public class Test{

public static void main(String args[]){
   for(int x=10; x<20; x=x+1){
      System.out.println("value of x :" +x);
       System.out.print("\n");
                            }
              }
      }
Output :
value of  x : 10
value of  x : 11
value of  x : 12
value of  x : 13
value of  x : 14
value of  x : 15
value of  x : 16
value of  x : 17
value of  x : 18
 value of  x : 19

Do While Loop

Like a while statement, expect that it tests the condition at the end of the loop body.
Syntax oh do while loop

do{
    //statements
}while(Boolean_expression)


  • Notice that the Boolean expression appear at the end of the loop, so the statements in the loop execute once before the Boolean is tested.
  • If the Boolean expression is true, the control jumps back up to do statement, and the statements int the loop execute again. This process repeats until the Boolean expression is false.

Flow  Chart of do while loop



Example of do while loop:

public class test{
public static void main(String args[]){
int x=10;
do{
     System.out.println("value of  x :" +x);
       x++;
     System.out.print("\n");
       }while(x<20);
    }

}
Output :
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Variables And Datatype







Variable

Variable is name of reserved area allocated in memory. In other words , it name of memory location. It is a combination of "very+able" that means its value can be changed.
Example:
int data=10;
here data is variable.

There are three types of variables in java:
  • Local Variable
                   A variable which is declare inside the method is              called local variable.
  • Instance Variable
                   A variable which is declared inside the class but outside the method, is called instance variable. It is not declared as static.
  • Static Variable  
                  A Variable that is declared as static is called static variable. It cannot be local. 
Example for better understanding variables
Class A{
  int data=50;//instance variable
static int m=20;//static variable
void method(){
int n=90;//local variable
}
}//end of class

        Data Type in Java
Datatype represents the different values to be stored in the variable. In java, there are two types of datatypes:
  • Primitive data type 
  • Non-primitive data type  
 
Data type          Default Value           Default Size

Boolean                             false                                      1 bit
Char                                  '\u000'                                    2 byte
Byte                                   0                                            1 byte
Short                                  0                                            2 byte
Int                                      0                                            4 byte
Long                                  0L                                          8 byte
Float                                  0.0f                                        4 byte
Double                              0.0d                                        8 byte

Why char uses 2 byte in Java and what is \u0000? 
It is because java uses Unicode system than ASCII code system. The \u000 is the lowest range of Unicode system. 

Java variable example: Add Two Numbers

          class add {
          public static void main(String [] args){
          int a=10;
          int b=10;
          int c=a+b;
         System.out.println(c);
         } 
      }
Output: 20

Java variable example : Narrowing (Typecasting)
            class Type{
             public static void main(String [] args){
             float f=10.5f;
            //int a=f;//compile time error
            int a=(int)f;
            System.out.println(f);
            System.out.println(a);
             }
           }
Output:
10.5
10


Tuesday, July 2, 2019

The Java Virtual Machine

JVM  (Java Virtual Machine) is an abstract machine. It is a specification that provide runtime environment in which java bytecode can be executed.
JVM are available for many hardware and software platforms(i.e. JVM is platform dependent.


What is JVM 

  • It is a specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
  • It is an implementation its implementation is known as JRE(Java Runtime Environment.
  • It is runtime instance whenever you write java command on the command prompt to run the java class, an instance of JVM is created.     

JVM provide definition for the:

  • Memory area .
  • Class file format
  • Resister set.
  • Garbage-collected heap.
  • Fatal error reporting etc.


Internal Architecture of JVM





Classloder is a subsystem of JVM that is used to load class file.

Class Area

Class Area stores per-class structure such as the runtime constant pool,field and method data, the code for methods.

Heap 

It is runtime data area in which objects are allocated.

Stack

Java Stack stores frames. It holds local variable and partial result, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.  

Program Counter Register

PC(Program Counter) resister. It contain the address of java virtual machine instruction currently being executed .

Native Method Stack 

It contains all native methods used in application.

Execution Engine

It contains:
  1. A virtual processor 
  2. Interpreter 
  3. Just-In-Time(JIT) Compiler.





                                    ARRAY IN JAVA Normally, array is a collection of similar type of elements that have contiguous memo...