ONE DIMENSIONAL ARRAY BASIC AND EXAMPLES IN JAVA

One Dimensional Array Basic and Examples


Basic Concept of Array:-

  • An array is ordered sequence of finite data items of the same data type that shares a common name. the common name is the array name and each individual data item is known as an element of the array.

  • The variable arr[i][j] represents the element in the ith row and jth column.

  • The subscript for an array must be an integer value of any integer expression.

  • For all arrays, the length is static and the final property stores the length of the array, i.e., number of element in the array.

  • In the declaration of arrays, the size is specified using the new operator.

  • In java, all arrays are created dynamically and not statically.

  • Arrays can be declared as int[] arr; or int arr[]; The allocation of memory is done as arr = new int [5].

  • Java allows the creation of multidimensional array of variant column length.

  • An array is a group of contiguous related data items which are referred to by a common name. The individual data items are called the elements of the array. In java, if n is the size of the array, indexing begins at 0 and extends up to n-1.

  • A one dimensional array is an array with a single index. An array has a variable named length in which the size of the array is stored.

  • A two dimensional array is akin to a table. In a java, it is possible to create a two dimensional array in which each row has a different length. This can be achieved by specifying only the first dimension of the array during it’s creation and then specifying the second dimension separately for each row.

  • There are various techniques to sort the element of an array. Two prominent techniques include the Straight Selection sort and the Bubble sort.

  • In Straight Selection sort, the array is parsed to find smallest element. Once this element is found, it is interchanged with the first number. Then the remaining (n-1) element are scanned for the smallest number which is interchanged with the second number. This goes on till the entire array is arranged in ascending order.

  • The fundamental idea behind bubble sort is to scan the array several times. Each time, the element at position i is interchanged with the element at position i+1 if the element at position I is greater than the element at position i+1. This goes on till the entire array is arranged in ascending order.

  • The linear sequential search and the binary search algorithms can be used to determine whether a particular element is present in an array or not.

  • In the Linear Sequential Search, the element to be searched i.e. the key is compared with every element in the array. If it is found , the index at which it is not found is noted.

How to read an array and display array element (Example 1)

 
                            
             import java.util.Scanner;
             public class ArrayRead
             {
                int a[];
                void ReadArray()
                {
                   a=new int [5];
                   Scanner sc=new Scanner(System.in);
                   System.out.println("Enter the element of an arry:");
                   for (int i = 0; i<5; i++)
                   {
                      a[i]=sc.nextInt();
                   }
                }
                void printarray()
                {
                   System.out.println("Array element are:");
                   for(int i:a)
                   System.out.println(i);
                }
                public static void main(String[] args)
                {
                   ArrayRead ar=new ArrayRead();
                   ar.ReadArray();
                   ar.printarray();
                }
             }                            

Output:

Enter the element of an arry: 1 4 3 2 6 Array element are: 1 4 3 2 6

How to read an array and display array element (Example 2)

 
                            
             import java.io.BufferedReader;
             import java.io.IOException;
             import java.io.InputStreamReader;
             public class Demo 
             {
                public static void main(String[] args) 
                {
                   BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
                   System.out.println("enter the string for test of pelindrome");
                   try 
                   {
                      String name = bf.readLine();
                      char[] ch = name.toCharArray();
                      for(int i=0; i<ch.length; i++)
                      {
                         int ascii = (int)ch[i];
                         //System.out.println(ch[i]+" : "+ascii);
                         StringBuffer sb = new StringBuffer(name);
                         String name1 = sb.reverse().toString();
                         char[] ch1 = name1.toCharArray();
                         for(int j=0; j<ch1.length; j++)
                         {
                            int ascii1 = (int)ch1[i];
                            //System.out.println(ch1[i]+" : "+ascii1);
                         }
                         if(name.equals(name1))
                         {
                            System.out.println("palindrome word is: "+name);
                            break;
                         }
                         else
                         {
                            System.out.println("not palindrome word is : "+name);
                            break;
                         }
                   }
                }
                catch(IOException ex)
                {
                   ex.printStackTrace();
                }   
               }
             }                            

Output:

enter the string for test of pelindrome digambar not palindrome word is : digambar enter the string for test of pelindrome amarama palindrome word is: amarama

Fibonacci series program in java programing using recursion (Example 3)

 
                            
         import java.io.BufferedReader;
         import java.io.IOException;
         import java.io.InputStreamReader;
         public class Demo 
         {
            public static void main(String[] args) 
            {
               BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
               System.out.println("enter the string for test of pelindrome");
               try 
               {
                  String name = bf.readLine();
                  char[] ch = name.toCharArray();
                  for(int i=0; i<ch.length; i++)
                  {
                     int ascii = (int)ch[i];
                     //System.out.println(ch[i]+" : "+ascii);
                     StringBuffer sb = new StringBuffer(name);
                     String name1 = sb.reverse().toString();
                     char[] ch1 = name1.toCharArray();
                     for(int j=0; j<ch1.length; j++)
                     {
                        int ascii1 = (int)ch1[i];
                        //System.out.println(ch1[i]+" : "+ascii1);
                     }
                     if(name.equals(name1))
                     {
                        System.out.println("palindrome word is: "+name);
                        break;
                     }
                     else
                     {
                        System.out.println("not palindrome word is : "+name);
                        break;
                     }
                  }
               }
               catch(IOException ex)
               {
                  ex.printStackTrace();
               }   
              }
         }                            

Output:

Enter the element of an arry: 1 4 3 2 6 Array element are: 1 4 3 2 6

Factorial Program using recursion in java (Example 4)

 
                            
             class Factorial
             {
                static int factorial(int n)
                {
                   if (n == 0)    
                     return 1;    
                   else    
                     return(n * factorial(n-1));    
                }    
                public static void main(String args[])
                {
                   int i,fact=1;  
                   int num=4;   /* It is the number to calculate factorial */    
                   fact = factorial(num);   
                   System.out.println("Factorial of "+num+" is: "+fact);    
                }  
             }                            

Output:

Factorial of 4 is: 24

Armstrong Program in java(Example 5)

 
                            
            import java.util.Scanner;
            class ArmstrExmp
            {
               public static void main(String[] args)
               {
                  int b=0,a,temp; 
                  System.out.println("Enter the number for armstrong check");
                  Scanner sc=new Scanner(System.in);
                  int n=sc.nextInt();//It is the number to check armstrong (take int n=154,n=153)
                  temp=n;  
                  while(n>0)  
                  {
                     a=n%10;
                     n=n/10;
                     b=b+(a*a*a);
                  }  
                  if(temp==b)
                  {
                     System.out.println("armstrong number");
                  }
                  else
                  {
                     System.out.println("Not armstrong number");
                  }
               }  
            }                            

Output:

Enter the number for armstrong check 153 armstrong number Enter the number for armstrong check 154 Not armstrong number

Method overloading by changing the no. of arguments(Example 6)

 
                            
            class Calc
            {
               void sum(int p,int q)
               {
                  System.out.println("The First Output is:"+(p+q));
               }
               void sum(int p,int q,int r)
               {
                  System.out.println("The Second Output is:"+(p+q+r));
               }
            }
            public class MtdOvrLod1
            {
               public static void main(String[] args)
               {
                  Calc cc=new Calc();
                  cc.sum(20, 20);
                  cc.sum(10, 20, 30);
               }
            }                            

Output:

The First Output is:40 The Second Output is:60

Method overloading by changing data type of arguments(Example 7)

 
                            
            class Calc1
            {
               void sum(int p,int q)
               {
                  System.out.println("The First Output is:"+(p+q));
               }
               void sum(double p,double q)
               {
                  System.out.println("The Second Output is:"+(p+q));
               }
            }
            public class MtdOvrLod2
            {
               public static void main(String[] args)
               {
                  Calc1 cc=new Calc1();
                  cc.sum(20.5, 20.5);
                  cc.sum(10, 20);
               }
            }                            

Output:

The Second Output is:41.0 The First Output is:30

Method Overloading with TypePromation if matchin found(Example 8)

 
                            
            class OverlCalc
            {
               void sum(int p,int q)
               {
                  System.out.println("integer argument  method invoked");
               }
               void sum(long p,long q)
               {
                  System.out.println("long argument method invoked");
               }
               public static void main(String args[])
               {
                  OverlCalc obj=new OverlCalc();
                  obj.sum(20,20);   /* now int arg sum() method gets invoked */
               }
            }                            

Output:

integer argument method invoked

Method Overloading with TypePromation in case ambiguoty(Example 9)

 
                            
            class OverCalc
            {
               void sum(int p,long q)
               {
                  System.out.println("a method invoked");
               }
               void sum(long p,int q)
               {
                  System.out.println("b method invoked");
               }
               public static void main(String args[])
               {
                  OverCalc obj=new OverCalc ();
                  obj.sum(30,40);                //now ambiguity occurs
               }
            }                            

Output:

Compile time error

main() method will be overloaded ?(Example 10)

 
                            
            class Overloading
            {
               public static void main(int p)
               {
                  System.out.println(p);
               }
               public static void main(String args[])
               {
                  System.out.println("this is main() method invoked");
                  main(25);
               }
            }                            

Output:

this is main method() invoked 25

Write a Java Program to define a class, define instance methods and overload them and use them for dynamic method invocation(Example 11)

 
                            
            import java.lang.*;
            class Sum
            {
               void display(int p,int q)
               {
               int r=p+q;
               System.out.println("The sum of " + p + " & " + q + " is " + r);
               }
               void display(double p,double q)
               {
                  double r=p+q;
                  System.out.println("The sum of " + p + " & " + q + " is " + r);
               }
            }
            class SumDemo
            {
               public static void main(String arg[])
               {
                  Sum obj=new Sum();
                  obj.display(20,30);
                  obj.display(20.2,30.2);
               }
            }                            

Output:

The sum of 20 & 30 is 50 The sum of 20.2 & 30.2 is 50.4

Write a Java Program to define a class, describe its constructor, overload the Constructors and instantiate its object (Example 12)

 
                            
            import java.lang.*;
            class Person
            {
               String name;
               int regno;
               int marks1,marks2,marks3;
               student()    // null constructor
               {
                  name="Sumit";
                  regno=12345;
                  marks1=56;
                  marks2=47;
                  marks3=78;
               }
               Person (String n,int r,int m1,int m2,int m3)  // parameterized constructor
               {
                  name=n;
                  regno=r;
                  marks1=m1;
                  marks2=m2;
                  marks3=m3;
               }
               Person (Person s)    // copy constructor
               {
                  name=s.name;
                  regno=s.regno;
                  marks1=s.marks1;
                  marks2=s.marks2;
                  marks3=s.marks3;
               }
               void display()
               {
                  System.out.println(name + "\t" +regno+ "\t" +marks1+ "\t" +marks2+ "\t" + marks3);
               }
            }
            class PersonDemo
            {
               public static void main(String arg[])
               {
                  Person s1=new Person ();
                  Person s2=new Person ("Amit",34266,58,96,84);
                  Person s3=new Person (s1);
                  s1.display();
                  s2.display();
                  s3.display();
               }
            }                            

Output:

Sumit 12345 56 47 78 Amit 34266 58 96 84 Sumit 12345 56 47 78

Write a Java Program to define a class, define instance methods for setting and Retrieving values of instance variables and instantiate its object(Example 13)

 
                            
            import java.lang.*;
            class Employee
            {
               String name;
               int id;
               String address;
               void getData(String name,int id,String address)
               {
                  this.name=name;
                  this.id=id;
                  this.address=address;
               }
               void putData()
               {
                  System.out.println("Employee details are :");
                  System.out.println("Name :" +name);
                  System.out.println("ID :" +id);
                  System.out.println("Address :" +address);
               }
            }
            class EmpDemo
            {
               public static void main(String arg[])
               {
                  Employee e=new Employee();
                  e.getData("Sumit",95867,"Darbhanga");
                  e.putData();
               }
            }                            

Output:

Employee details are : Name : Sumit ID :95867 Address : Darbhanga

Write a Java Program to demonstrate use of sub class(Example 14)

 
                            
            import java.lang.*;
            class Parent
            {
               int p;
               void get_p(int p)
               {
                  this.p=p;
               }
               void display_p()
               {
                  System.out.println("This is from parent : p = " +p);
               }
            }
            class Child extends Parent
            {
               int q;
               void get_q(int q)
               {
                  this.q=q;
               }
               void display_q()
               {
                  System.out.println("This is from child : q = " +q);
               }
            }
            class ChildDemo
            {
               public static void main(String arg[])
               {
                  Child r=new Child();
                  r.get_p(20);
                  r.get_q(30);
                  r.display_p();
                  r.display_q();
               }
            }                            

Output:

This is from parent : m = 20 This is from child : n = 30

Write a Java Program to demonstrate use of nested class.(Example 15)

 
                            
            import java.lang.*;
            class Outer
            {
               int m=10;
               class Inner
               {
                  int n=20;
                  void display()
                  {
                     System.out.println("m = "+m);
                     System.out.println("n = "+n);
                  }
               }
            }
            class NestedDemo
            {
               public static void main(String arg[])
               {
                  Outer outobj=new Outer();
                  Outer.Inner inobj=outobj.new Inner();
                  inobj.display();
               }
            }                            

Output:

m = 10 n = 20

Write a Java Program to implement array of objects.(Example 16)

 
                            
            import java.lang.*;
            class Employee
            {
               private String name;
               private double salary;
               public Employee(String n, double s)
               {
                  name = n;
                  salary = s;
               }
               public void print()
               {
                  System.out.println(name + " " + salary);
               }
            }
            public class EmployeeTest
            {
               public static void main(String[] args)
               {
                  Employee[] staff = new Employee[3];
                  staff[0] = new Employee("Digambar Thakur", 300);
                  staff[1] = new Employee("Pawan Kumar", 500);
                  staff[2] = new Employee("Ritesh Deshmukh", 400);
                  for (int i = 0; i < 3; i++)
                  staff[i].print();
               }
            }                            

Output:

Digambar Thakur:300 Pawan Kumar:500 Ritesh Deshmukh:400