Java Program on How to use Array as a Reference Object

Free Java courses with 37 real-time projects - Learn Java

Program 1

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dataflair;

/**
 *
 * @author admin
 */
public class TestMain5 
{
    public static void main(String[] args) 
    {
        int ar1[]={10,20,30,40,50};  // Array
        int ar2[]=ar1;  //Reference Array
        int i;
        System.out.println("Array 1");
         for(i=0;i<ar2.length;i++)
             System.out.println(ar2[i]);
         
        
         System.out.println("--------------");
         System.out.println("Array 2");
         
         ar2[3]=700;
         for(i=0;i<ar2.length;i++)
             System.out.println(ar2[i]);
         
         System.out.println("--------------");
         
         System.out.println("Array 1");
         for(i=0;i<ar1.length;i++)
             System.out.println(ar1[i]);
         
         ar1[4]=900;
         
         System.out.println("Array 2");
         
         for(i=0;i<ar2.length;i++)
             System.out.println(ar2[i]);
         
    }
    
}

Program 2

package dataflair;

class Test
{
    void sorting(int ar[])
    {
         int i,j,temp;
        for(i=0;i<ar.length;i++)
        {
            for(j=i+1;j<ar.length;j++)
            {
                if(ar[j]<ar[i])
                {
                    temp=ar[i];
                    ar[i]=ar[j];
                    ar[j]=temp;
                }
            }
        }
    }
}

public class TestMain6 
{
    public static void main(String[] args) 
    {
          int myar[]={20,10,30,50,40};
          
          System.out.println("Before Sorting: ");
          for(int m:myar)
              System.out.println(m);
          
          Test T=new Test();
          T.sorting(myar);
        System.out.println("------------------");
        System.out.println("After Sorting: ");
          for(int m:myar)
              System.out.println(m);

          
    }
    
}

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *