0% found this document useful (0 votes)
39 views

JAVA Methods & Arrays

Methods or functions are blocks of code that perform specific tasks. They can be reused by calling the method multiple times, passing in parameters. To define a method, specify its name, parameters, and code block within a class. When calling a method, provide arguments corresponding to the parameters. Methods can return values using the return keyword or void if no value is returned. Examples show checking even/odd numbers, calculating averages, and other tasks using methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

JAVA Methods & Arrays

Methods or functions are blocks of code that perform specific tasks. They can be reused by calling the method multiple times, passing in parameters. To define a method, specify its name, parameters, and code block within a class. When calling a method, provide arguments corresponding to the parameters. Methods can return values using the return keyword or void if no value is returned. Examples show checking even/odd numbers, calculating averages, and other tasks using methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Methods or (Functions):

A method is a block of code which only runs when it is called. You can pass data, known
as parameters, into a method.

Y
EM
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.

AD
Create a Method:

AC
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

R
System.out.println(), but you can also create your own methods to perform certain

TE
actions:

Syntax:
PU
M
public class Main {
O

static void myMethod() {


C

// code to be executed
N

}
O

}
TI
VA

● myMethod() is the name of the method


● static means that the method belongs to the Main class and not an object of the
O

Main class. You will learn more about objects and how to access methods
N

through objects later in this tutorial.


IN

● void means that this method does not have a return value. You will learn more
E

about return values later in this chapter.


TH

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:

Y
public class Main {

EM
static void myMethod() {
System.out.println("Hello, Java!");
}

AD
public static void main(String[] args) {

AC
myMethod();
}

R
}

TE
// Outputs "Hello, Java!"
PU
M
A method can also be called multiple times:
O
C

public class Main {


N

static void myMethod() {


System.out.println("Hello, Java!");
O

}
TI
VA

public static void main(String[] args) {


myMethod();
O

myMethod();
N

myMethod();
IN

}
}
E
TH

// Hello, Java!
// Hello, Java!
// Hello, Java!
Parameters and Arguments:
Information can be passed to methods as parameter. Parameters act as variables
inside the method. Parameters are specified after the method name, inside the
parentheses. You can add as many parameters as you want, just separate them with a

Y
comma.

EM
public class ParametersAndArguments {
// Method with parameters

AD
static void greetUser(String name) {
System.out.println("Hello, " + name + "! How are you?");

AC
}

R
public static void main(String[] args) {

TE
// Method call with an argument "Alice"
greetUser("Alice");

}
}
PU
M
O

The Above example has a method that takes a String called name as parameter. When
C

the method is called, we pass along a first name, which is used inside the method to
N

print the whole text.


O
TI

When a parameter is passed to the method, it is called an argument. So, from the
VA

example above: name is a parameter, while Alice is an argument.


O
N

Multiple Parameters
IN

You can have as many parameters as you like:


E

public class Main {


TH

static void myMethod(String name, int age) {


System.out.println(name + " is " + age + "Year old");
}

public static void main(String[] args) {


myMethod("Alice", 5);
myMethod("Jenny", 8);
}
}

Y
// Alice is 5 Year old

EM
// Jenny is 8 Year old

AD
AC
Note that when you are working with multiple parameters, the method call must have
the same number of arguments as there are parameters, and the arguments must be

R
passed in the same order.

TE
PU
M
Return Values
O

The void keyword, used in the examples above, indicates that the method should not
C

return a value. If you want the method to return a value, you can use a primitive data
N

type (such as int, char, etc.) instead of void, and use the return keyword inside the
O

method:
TI
VA

public class ParametersAndArguments {


// Method with multiple parameters
O

static int addNumbers(int num1, int num2) {


N

return num1 + num2;


IN

}
E

public static void main(String[] args) {


TH

// Method call with arguments 5 and 10


int result = addNumbers(5, 10);
System.out.println("Sum: " + result);
}
}
More Examples:

1. Check even odd using methods.


public class ConditionalMethods {

Y
// Method that checks if a number is even or odd and returns a

EM
message
static String checkEvenOdd(int num) {

AD
if (num % 2 == 0) {
return num + " is even.";
} else {

AC
return num + " is odd.";
}

R
}

TE
public static void main(String[] args) {
int number1 = 10;
int number2 = 15;
PU
M
O

System.out.println(checkEvenOdd(number1));
C

System.out.println(checkEvenOdd(number2));
}
N

}
O
TI

2. Calculate the average of three numbers using methods.


VA

public class MultipleParameters {


O

// Method that calculates the average of three numbers


N

static double calculateAverage(double num1, double num2, double


IN

num3) {
return (num1 + num2 + num3) / 3;
E

}
TH

public static void main(String[] args) {


double result = calculateAverage(10.5, 7.2, 5.8);
System.out.println("Average: " + result);
}
}
3. Check if a number is positive.
public class PositiveNumber {
// Method to check if a number is positive
static boolean isPositive(int number) {
return number > 0;

Y
}

EM
public static void main(String[] args) {

AD
int num1 = 5;
int num2 = -10;

AC
System.out.println(num1 + " is positive: " + isPositive(num1));

R
System.out.println(num2 + " is positive: " + isPositive(num2));
}

TE
}

PU
4. Method to Calculate the Square of a Number.
M
public class SquareNumber {
O

// Method to calculate the square of a number


C

static int square(int number) {


N

return number * number;


O

}
TI

public static void main(String[] args) {


VA

int num1 = 5;
O

int num2 = -3;


N

System.out.println("Square of " + num1 + " is: " +


IN

square(num1));
E

System.out.println("Square of " + num2 + " is: " +


TH

square(num2));
}
}
5. Method to Print a half pyramid.
public class Triangle {
// Method to print a triangle of stars
static void printTriangle(int n) {
for (int i = 1; i <= n; i++) {

Y
for (int j = 1; j <= i; j++) {

EM
System.out.print("* ");
}

AD
System.out.println();
}

AC
}

R
public static void main(String[] args) {
int rows = 5;

TE
printTriangle(rows);

}
}
PU
M
O
C
N
O
TI
VA
O
N
IN
E
TH
Arrays:
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value. An array is a collection of similar type of elements
which has contiguous memory location.

Y
EM
AD
AC
R
TE
PU
M
To declare an array, define the variable type with square brackets:
O

String[] cars;
C
N

Syntax of declaring arrays-


O

dataType[] arr; (or)


TI

dataType []arr; (or)


VA

dataType arr[];
O

We have now declared a variable that holds an array of strings. To insert values to it,
N
IN

you can place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Lambo"};
E
TH

To create an array of integers, you could write:


int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array:
You can access an array element by referring to the index number.
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Lambo"};

Y
System.out.println(cars[0]);

EM
}
}

AD
AC
Change an Array Element:
To change the value of a specific element, refer to the index number:

R
TE
String[] cars = {"Volvo", "BMW", "Ford", "Lambo"};
cars[0] = "Bugati";
System.out.println(cars[0]); PU
// Now outputs Bugati instead of Volvo
M
O
C

Array Length
N

To find out how many elements an array has, use the length property:
O
TI

String[] cars = {"Volvo", "BMW", "Ford", "Lambo"};


System.out.println(cars.length);
VA

// Outputs 4
O
N
IN

Loop Through an Array


You can loop through the array elements with the for loop, and use the length
E

property to specify how many times the loop should run.


TH

String[] cars = {"Volvo", "BMW", "Ford", "Lambo"};


for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Another way to initialize an array:
Initialization is a process of allocating memory to an array. At the time of
initialization, we specify the size of array to reserve memory area.

Y
Syntax:

EM
Datatype[] arrayName = new datatype[size]

AD
Example:
class Demo {

AC
public static void main(String args[]) {
int a[] = new int[5]; // declaration and instantiation

R
a[0] = 10; // initialization

TE
a[1] = 20;
a[2] = 70;
a[3] = 40;
a[4] = 50;
PU
M
O

// traversing the array


C

for (int i = 0; i < a.length; i++) { // length is the property of the array
System.out.println(a[i]);
N

}
O

}
TI

}
VA
O
N

For-Each-Loop:
IN

There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays.
E
TH

Example:
String[] cars = {"Volvo", "BMW", "Ford", "Lambo"};
for (String i : cars) {
System.out.println(i);
}
Insert elements into an array via User Input:
import java.util.Scanner;

public class InsertElementsToArray {


public static void main(String[] args) {

Y
Scanner scanner = new Scanner(System.in);

EM
// Step 3: Ask the user to input the size of the array

AD
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

AC
// Step 4: Create an array with the given size

R
int[] arr = new int[size];

TE
// Step 5: Use a loop to take user input for each element and
store it in the array
PU
System.out.println("Enter " + size + " elements:");
M
for (int i = 0; i < size; i++) {
System.out.print("Enter element at index " + i + ": ");
O

arr[i] = scanner.nextInt();
C

}
N
O

// Close the Scanner to release resources


TI

scanner.close();
VA

// Display the elements in the array


O

System.out.println("-----:Elements in the array:-----");


for (int i = 0; i < size; i++) {
N

System.out.println("Element at index " + i + ": " + arr[i]);


IN

}
E

}
TH

}
More Programs on Arrays:

1. Java program to calculate the sum of array elements.


public class ArraySum {
public static void main(String[] args) {

Y
EM
int array[] = {10, 20, 30, 40, 50};
int sum = 0;

AD
// add array elements

AC
for (int i=0; i<array.length; i++) {
sum += array[i]; // sum = sum + array[i];

R
}

TE
System.out.println("Sum of array elements= " + sum);

}
PU
M
}
O
C

2. Java program to calculate the average of an array.


N

public class ArrayAverage {


O

public static void main(String[] args) {


TI
VA

double array[] = {10, 20, 30, 40, 50};


double sum = 0.0;
O

double avg = 0.0;


N
IN

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


sum = sum + array[i];
E

}
TH

// calculate the average value


avg = sum/array.length;

System.out.println("Average: " + avg );


}
}
3. Find the span of an array.
import java.util.*;

public class SpanOfArray {

Y
public static void main(String[] args){

EM
Scanner scn = new Scanner(System.in);
System.out.println("Enter length of the array: ");

AD
int n = scn.nextInt();
int[] arr = new int[n];

AC
for (int i = 0; i < n; i++) {

R
arr[i] = scn.nextInt();
}

TE
int min = arr[0];
int max = arr[0]; PU
M
for (int i = 1; i < arr.length; i++) {
O

if (arr[i] < min) {


C

min = arr[i];
N

}
O

if (arr[i] > max) {


TI

max = arr[i];
}
VA

}
O

int span = max - min;


System.out.println(span);
N

}
IN

}
E
TH

Solution Explained:
Determine the maximum and minimum values: Traverse through the array and keep
track of the maximum and minimum values encountered.
Calculate the span: Subtract the minimum value from the maximum value. The result
will be the span of the array, representing the range of values covered by the array.
Algorithms

"Algorithms are sets of clear, precise, and ordered instructions or rules that are
carefully designed to perform a specific task or solve a particular problem efficiently.

Y
They act as systematic guides that take input data and transform it through a series

EM
of well-defined steps, ultimately producing the desired output or solution.“

AD
For example- Sorting Algorithm, Search Algorithm, Encryption Algorithm, Pathfinding
Algorithm etc.

AC
Search Algorithms: A process of finding a specific item in a collection of data.

R
TE
Example: Binary Search, Linear Search.

1. Linear Search: PU
It compares each and every element with the value that we are searching for. If both
M
are matched, the element is found, if not it will return ‘-1’.
O
C

class Searching {
N

public static int linearSearch(int[] a, int key) {


O

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


TI

if (a[i] == key) {
VA

return i;
}
O

}
N

return -1;
IN

}
E

public static void main(String[] args) {


TH

int[] a = { 50, 10, 33, 40, 26 };


int key = 50;
System.out.println(linearSearch(a, key));
}
}
2. Binary Search:
This search algorithm takes advantage of a collection of elements that is already
sorted by ignoring half of the array after just one comparison.

Algo:

Y
a. Compare Key with the middle element. If Key matches with the middle element,

EM
return the mid index.

AD
b. Else if Key is smaller, the target Key must lie in the left half.
c. Else if Key is greater than the mid element then Key can only lie in the right half

AC
subarray after the mid element.

R
import java.util.Arrays;

TE
class Searching {

PU
public static int binarySearch(int[] arr, int key) {
int left = 0, right = arr.length - 1, mid = 0;
while (left <= right) {
M
mid = (left + right) / 2;
O

if (key == arr[mid]) {
C

return mid;
N

} else if (key < arr[mid]) {


O

right = mid - 1;
TI

} else {
left = mid + 1;
VA

}
O

}
return -1;
N

}
IN

public static void main(String[] args) {


E
TH

int[] arr = {3, 5, 6, 8, 12, 15, 16, 19, 21};


Arrays.sort(arr);
int key = 13;
System.out.println(binarySearch(arr, key));
}
}
Sorting Algorithms: Sorting is the process of arranging the elements of an array so
that they can be placed either in ascending or descending order. For example,

Consider an array;
int A[10] = { 5, 4, 10, 2, 30, 45, 34, 14, 18, 9 }

Y
EM
The Array sorted in ascending order will be given as;

AD
A[] = { 2, 4, 5, 9, 10, 14, 18, 30, 34, 45 }

AC
1. Bubble Sort:
Bubble sort is an algorithm that compares the adjacent elements and swaps their

R
TE
positions if they are not in the intended order. The order can be ascending or
descending.
Algo: PU
● Starting from the first index, compare the first and the second elements. If
M
the firstelement is greater than the second element, they are swapped.
O

● Now, compare the second and third elements. Swap them if they are not in
C

order.
N

● The above process goes on until the last element.


O

● The same process goes on for the remaining iterations. After each iteration, the
TI

largest element among the unsorted elements is placed at the end.


VA

● In each iteration, the comparison takes place up to the last unsorted element.
O

● The array is sorted when all the unsorted elements are placed at their correct
N

positions.
IN
E
TH
Code:
public class Sorting {
static void bubbleSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - i - 1; j++) {

Y
if (a[j] > a[j + 1]) {

EM
int temp = a[j];
a[j] = a[j + 1];

AD
a[j + 1] = temp;
}

AC
}
}

R
}

TE
public static void main(String[] args) {

PU
int[] a = { 3, 2, 9, 5, 7 };
M
// Before sorting
System.out.print("Before sorting: ");
O

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


C

System.out.print(a[i] + " ");


N

}
O

System.out.println();
TI

bubbleSort(a);
VA
O

// After sorting
System.out.print("After sorting: ");
N

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


IN

System.out.print(a[i] + " ");


E

}
TH

}
}

You might also like