0% found this document useful (0 votes)
26 views17 pages

Java Methods and Arrays Overview

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
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)
26 views17 pages

Java Methods and Arrays Overview

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
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

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
[Link](), 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() {
[Link]("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() {


[Link]("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) {
[Link]("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) {


[Link](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);
[Link]("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

[Link](checkEvenOdd(number1));
C

[Link](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);
[Link]("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
[Link](num1 + " is positive: " + isPositive(num1));

R
[Link](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

[Link]("Square of " + num1 + " is: " +


IN

square(num1));
E

[Link]("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
[Link]("* ");
}

AD
[Link]();
}

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
[Link](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";
[Link](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"};


[Link]([Link]);
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 < [Link]; i++) {
[Link](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 < [Link]; i++) { // length is the property of the array
[Link](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) {
[Link](i);
}
Insert elements into an array via User Input:
import [Link];

public class InsertElementsToArray {


public static void main(String[] args) {

Y
Scanner scanner = new Scanner([Link]);

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

AD
[Link]("Enter the size of the array: ");
int size = [Link]();

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
[Link]("Enter " + size + " elements:");
M
for (int i = 0; i < size; i++) {
[Link]("Enter element at index " + i + ": ");
O

arr[i] = [Link]();
C

}
N
O

// Close the Scanner to release resources


TI

[Link]();
VA

// Display the elements in the array


O

[Link]("-----:Elements in the array:-----");


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

[Link]("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<[Link]; i++) {
sum += array[i]; // sum = sum + array[i];

R
}

TE
[Link]("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<[Link]; i++) {


sum = sum + array[i];
E

}
TH

// calculate the average value


avg = sum/[Link];

[Link]("Average: " + avg );


}
}
3. Find the span of an array.
import [Link].*;

public class SpanOfArray {

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

EM
Scanner scn = new Scanner([Link]);
[Link]("Enter length of the array: ");

AD
int n = [Link]();
int[] arr = new int[n];

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

R
arr[i] = [Link]();
}

TE
int min = arr[0];
int max = arr[0]; PU
M
for (int i = 1; i < [Link]; 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;


[Link](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 < [Link]; 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;
[Link](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 [Link];

TE
class Searching {

PU
public static int binarySearch(int[] arr, int key) {
int left = 0, right = [Link] - 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};


[Link](arr);
int key = 13;
[Link](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 < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 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
[Link]("Before sorting: ");
O

for (int i = 0; i < [Link]; i++) {


C

[Link](a[i] + " ");


N

}
O

[Link]();
TI

bubbleSort(a);
VA
O

// After sorting
[Link]("After sorting: ");
N

for (int i = 0; i < [Link]; i++) {


IN

[Link](a[i] + " ");


E

}
TH

}
}

Common questions

Powered by AI

In Java, "for" loops and "for-each" loops serve different purposes when interacting with arrays. A standard "for" loop uses an index variable to iterate over elements, offering more control over the iteration process. This allows for tasks like accessing array indices to modify elements: ```java for (int i = 0; i < cars.length; i++) { System.out.println(cars[i]); } ``` "For-each" loops, meanwhile, iterate over the elements themselves without explicit access to indices, simplifying and enhancing readability for situations where you merely need to process each element: ```java for (String car : cars) { System.out.println(car); } ``` The "for-each" loop is less error-prone for simple traversals as it abstracts the index management, but it's not suitable if you need to modify the array elements directly using their indices .

To initialize an array in Java and populate it with user-entered values, you can use a Scanner for input and a loop to assign values to the array. Here's an example: ```java import java.util.Scanner; public class InsertElementsToArray { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the size of the array: "); int size = scanner.nextInt(); int[] arr = new int[size]; System.out.println("Enter " + size + " elements:"); for (int i = 0; i < size; i++) { System.out.print("Enter element at index " + i + ": "); arr[i] = scanner.nextInt(); } scanner.close(); } } ``` This code snippet prompts the user to input the size of the array and each element, demonstrating how user input can be used to dynamically fill arrays .

Arrays in Java are used to store multiple values of the same type in a single variable, which allows for organized data management and efficient memory usage. An array has contiguous memory locations, providing constant time complexity O(1) for accessing elements by index. For example: ```java int[] myNum = {10, 20, 30, 40}; ``` This array holds four integers and allows easy looping through elements, making data manipulation straightforward. Arrays help manage data efficiently by permitting indexed access, which is faster than other data structures when individual elements need to be accessed frequently .

Method overloading in Java occurs when multiple methods have the same name but different parameter lists (different type, number, or both). This allows developers to create clean code with a unified interface for different types or amounts of input, making the code easier to read and maintain. For example, you can overload a method to take either two or three arguments: ```java class Main { static int add(int a, int b) { return a + b; } static int add(int a, int b, int c) { return a + b + c; } public static void main(String[] args) { System.out.println(add(3, 4)); // Output: 7 System.out.println(add(3, 4, 5)); // Output: 12 } } ``` This approach simplifies the code and avoids needing to create uniquely named methods for similar operations .

The main advantage of using methods in Java is to promote code reusability. Methods allow you to define a block of code once and use it multiple times, which helps in maintaining cleaner and more organized code. Java provides predefined methods like System.out.println(), but you can also create your own methods to perform specific actions. This approach reduces redundancy and potential for errors when the same code is needed in multiple places in an application .

Using the void keyword in Java methods indicates that the method does not return a value. The benefit of using void is that it simplifies methods used exclusively for performing tasks, such as printing messages or altering class variables, without dealing with return data management. However, the constraint is that methods declared with void cannot be used to directly retrieve or calculate values needed elsewhere in the code. This limitation necessitates alternative approaches for passing information back to the method caller, such as by using parameters or altering object states .

Algorithms are essential in programming because they provide a clear set of instructions or rules to solve specific problems efficiently. They enhance problem-solving by breaking down complex problems into simpler, manageable steps, allowing for systematic and repeatable solutions. For instance, a binary search algorithm is much more efficient than a linear search when dealing with a large, sorted dataset because it divides the search space in half each step, leading to significantly faster searches than linearly checking each element. Algorithms improve performance and resource management and can be essential when optimizing code for speed and efficiency .

Return values in Java methods are significant because they allow methods to output a value back to the caller, enabling further operations based on the method's result. Methods that return values use the return keyword and a specific data type instead of void. For instance, if a method calculates the sum of two numbers and returns an int, it allows this sum to be used later: ```java static int addNumbers(int num1, int num2) { return num1 + num2; } ``` In contrast, methods with no return value (void) are typically used for operations or side-effects without providing data back to the method caller. Return values are essential for tasks such as calculations where results need to be stored, compared, or printed .

To define a method in Java that takes multiple parameters and returns a result, you specify the data types of the parameters within the parentheses after the method's name, and use a return type instead of void. An example is: ```java public class ParametersAndArguments { // Method with multiple parameters that returns an integer static int addNumbers(int num1, int num2) { return num1 + num2; } public static void main(String[] args) { // Method call with arguments 5 and 10 int result = addNumbers(5, 10); System.out.println("Sum: " + result); } } ``` This method `addNumbers` takes two integers as parameters and returns their sum .

Bubble Sort works by repeatedly stepping through a list of elements, comparing adjacent pairs, and swapping them if they are in the wrong order. This process continues until no more swaps are needed, indicating that the list is sorted. The detailed steps include: 1. Start from the first element and compare with the second. 2. Swap if the first element is greater. 3. Move to the next element and repeat step 2. 4. At the end of the list, start again until no swaps are needed. The algorithm checks each pair multiple times, which can make it inefficient for large datasets due to its O(n^2) complexity. The simplest implementation may perform poorly compared to more sophisticated algorithms like quicksort or mergesort, particularly as data size grows .

You might also like