JAVA Methods & Arrays
JAVA Methods & Arrays
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
// code to be executed
N
}
O
}
TI
VA
Main class. You will learn more about objects and how to access methods
N
● void means that this method does not have a return value. You will learn more
E
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
}
TI
VA
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
When a parameter is passed to the method, it is called an argument. So, from the
VA
Multiple Parameters
IN
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
}
E
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
num3) {
return (num1 + num2 + num3) / 3;
E
}
TH
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
}
TI
int num1 = 5;
O
square(num1));
E
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
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
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
// Outputs 4
O
N
IN
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
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;
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
scanner.close();
VA
}
E
}
TH
}
More Programs on Arrays:
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
}
TH
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
min = arr[i];
N
}
O
max = arr[i];
}
VA
}
O
}
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
if (a[i] == key) {
VA
return i;
}
O
}
N
return -1;
IN
}
E
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
right = mid - 1;
TI
} else {
left = mid + 1;
VA
}
O
}
return -1;
N
}
IN
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 same process goes on for the remaining iterations. After each iteration, the
TI
● 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
}
O
System.out.println();
TI
bubbleSort(a);
VA
O
// After sorting
System.out.print("After sorting: ");
N
}
TH
}
}