Array
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.
Syntax:
for(data_type variable:array){
//body of the loop
}
Program:
class Testarray1{
public static void main(String args[]){
int arr[]={1,2,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Java Methods:
• Methods are used to perform certain actions, and they are also known as functions.
• Why use methods? To reuse code: define the code once, and use it many times.
Create a Method:
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:
Example:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained:
Call a Method:
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example:
myMethod();
myMethod();
myMethod();
myMethod();
We can pass the java array to method so that we can reuse the same logic on any array.
Example:
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={1,3,4,5};
min(a); //passing array to method
}
}
Example:
//Java Program to demonstrate the way of passing an anonymous array to method.
class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,20,30,40}); //passing anonymous array to method
}
}