0% found this document useful (0 votes)
4 views2 pages

Part 19

Uploaded by

Up ka sher king
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Part 19

Uploaded by

Up ka sher king
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Declara on, Instan a on and Ini aliza on of Java Array

In Java, you can declare, instan ate, and ini alize an array in a single line, as demonstrated below:

1. int a[]={33,3,4,5};//declara on, instan a on and ini aliza on

Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declara on, instan a on

2. //and ini aliza on of Java array in a single line

3. class Testarray1{

4. public sta c void main(String args[]){

5. int a[]={33,3,4,5};//declara on, instan a on and ini aliza on

6. //prin ng array

7. for(int i=0;i<a.length;i++)//length is the property of array

8. System.out.println(a[i]);

9. }}

Output:

33

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array elements
one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){

2. //body of the loop

3. }

Let's see the example of prin ng the elements of the Java array using the for-each loop.

AD

Testarray1.java

1. //Java Program to print the array elements using for-each loop

2. class Testarray1{

3. public sta c void main(String args[]){


4. int arr[]={33,3,4,5};

5. //prin ng array using for-each loop

6. for(int i:arr)

7. System.out.println(i);

8. }}

Output:

33

AD

Passing Array to a Method in Java

We can pass the Java array to the method so that we can reuse the same logic on any array. When
we pass an array to a method in Java, we are essen ally passing a reference to the array. It means
that the method will have access to the same array data as the calling code, and any modifica ons
made to the array within the method will affect the original array.

Let's see the simple example to get the minimum number of an array using a method.

You might also like