1-D Array in Java Program

In this blog, we introduce two types of declaration process of 1-D array, length function and foreach loop.

Two Types of Declaration

  1. Simple Declaration

int x[] = {10,20,30,40,50};                      // Simple Dec

  1. Using new keyword

int y[] = new int[5];          // y[] = must be empty , int[5] must put array size

 

length

length is one method, which is give size of array.

Foreach Loop

We already know for, while, do while, nested, pattern loop. Now we introduce forach loop in java program.

This loop is maximum use with array, collection and wrapper classes.

Example on 1-D Array in Java Program

class arr1

{

            public static void main(String args[])

            {

                        int x[] = {10,20,30,40,50};          // Simple Dec and Def of simple 1-D Array

 

                        // 1st step Simple for loop

                        System.out.println(“[ 1st Type ]”);

 

                        for(int i=0;i<x.length;i++)

                        {

                                    System.out.println(x[i]);

                        }

 

                        System.out.println(“[ 2nd Type ]”);

                        // 2nd Type – Foreach Loop in java

 

                        int y[] = new int[5]; // Dec of array in java

 

                        y[0] = 1;

                        y[1] = 2;

                        y[2] = 3;

                        y[3] = 4;

                        y[4] = 5;

 

                        int sum=0;

                        for(int N : y)

                        {

                                    sum = sum + N;

                                    System.out.println(N);

                        }

                        System.out.println(“Sum = ” + sum);

            }

}

 

Output:

[1st Type]

10

20

30

40

50

[2nd Type]

1

2

3

4

5

Sum = 15

 

 

This video also listed in YouTube Website.

 

 

1106total visits,10visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

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

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image