Arrays in Java

Suman Barik
0

 Classroom of 500 students - You have to store marks of these 500 students

        You have 2 options:
        1. Create 500 variables
        2. Use Arrays (recommended)
public class MyClass {
    public static void main(String args[]) {
        int [] marks = new int[5];
        marks[0] = 100;
        marks[1] = 60;
        marks[2] = 70;
        marks[3] = 90;
        marks[4] = 86;
        System.out.println(marks[4]);
        //This will print 80
    }
}
public class MyClass {
    public static void main(String args[]) {
        int [] marks = {98, 45, 79, 99, 80};
        System.out.println(marks[4]);
        //This will print 80
    }
}
public class MyClass {
    public static void main(String args[]) {
        int [] arr={1,2,3,4,5};  
     System.out.println(arr.length);  
    }
}
public class MyClass {
    public static void main(String args[]) {
        float [] marks = {98.5f, 45.5f, 79.5f, 99.5f, 80.5f};
        String [] students ={"Harry", "Rohan", "Shubham", "Lovish"};
        System.out.println(students.length);
        System.out.println(students[2]); 
    }
}
public class MyClass {
    public static void main(String args[]) {
        int [] marks = {98, 45, 79, 99, 80};
        // Displaying the Array (for loop)
        System.out.println("Printing using for loop");
        for(int i=0;i<marks.length;i++){
            System.out.println(marks[i]);
        }
    }
}
public class MyClass {
    public static void main(String args[]) {
        int [] marks = {98, 45, 79, 99, 80};
        // Displaying the Array (for loop)
        System.out.println("Printing using for loop in reverse order");
        for(int i=marks.length -1;i>=0;i--){
            System.out.println(marks[i]);
        }
    }
}
public class MyClass {
    public static void main(String args[]) {
        int arr[]={1,2,3,3,4,5};  
   //traversing the array with for-each loop  
   for(int i:arr){  
     System.out.println(i);  
   }  
    }
}
public class MyClass {
    public static void main(String args[]) {
        int [] marks = {98, 45, 79, 99, 80};
        System.out.println("Printing using for-each loop");
        for(int element: marks){
            System.out.println(element);
        }
    }
}
public class MyClass {
    public static void main(String args[]) {
        int [] marks; // A 1-D Array
        int [][] flats; // A 2-D Array
        flats = new int [2][3];
        flats[0][0] = 101;
        flats[0][1] = 102;
        flats[0][2] = 103;
        flats[1][0] = 201;
        flats[1][1] = 202;
        flats[1][2] = 203;

        // Displaying the 2-D Array (for loop)
        System.out.println("Printing a 2-D array using for loop");
        for(int i=0;i<flats.length;i++){
            for(int j=0;j<flats[i].length;j++) {
                System.out.print(flats[i][j]);
                System.out.print(" ");
            }
            System.out.println("");
        }
    }
}

Post a Comment

0Comments
Post a Comment (0)