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

OOP1 Unit3

Uploaded by

makkakuldip
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOP1 Unit3

Uploaded by

makkakuldip
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

3140705 - Object Oriented Programming 1

Unit -3
Methods and Arrays
Array in Java
• Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for
each value.

• Normally, an array is a collection of similar type of


elements which has contiguous memory location.

• We can store only a fixed set of elements in a Java


array.

• Array in Java is index-based, the first element of the


array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
Advantages
• Code Optimization: It makes the code optimized, we
can retrieve or sort the data efficiently.

• Random access: We can get any data located at an


index position.

Disadvantages
• Size Limit: We can store only the fixed size of
elements in the array. It doesn't grow its size at
runtime.

• To solve this problem, collection framework is used in


Java which grows automatically.
Types of Array in java
There are two types of array.
– Single Dimensional Array
– Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];
Example of Java Array
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.

class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};

for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
For-each Loop for Java Array
• It is recommended to use the Java for-each loop
for traversing the elements of array.
• The syntax of Java for-each loop consists of
data_type with the variable followed by a colon
(:), then array.

for(data_type variable : array)


{
//body of for-each loop
}
For-each loop Example: Traversing the array elements

class ForEachExample1
{
public static void main(String args[])
{
//declaring an array
int arr[]={12,13,14,44};

for(int i:arr)
{
System.out.println(i);
}
}
}
Let us see another of Java for-each loop where we are going to
total the elements.

class ForEachExample1
{
public static void main(String args[])
{
int arr[]={12,13,14,44};
int total=0;
for(int i:arr)
{
total=total+i;
}
System.out.println("Total: "+total);
}
}
Multidimensional Array in Java
• data is stored in row and column based index (also
known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column


Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
• Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.

class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Java Methods

• A method is a block of code which only runs when it is called.

• You can pass data, known as parameters, into a method.

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

• 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:
Call a Method

• To call a method in Java, write the method's name followed by


two parentheses () and a semicolon;

class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
}
A method can also be called multiple times:

class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
myMethod();
myMethod();
}
}
Java Method Parameters

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

class Main
{
static void myMethod(String fname)
{
System.out.println(fname + " Lee");
}
public static void main(String[] args)
{
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}

Output
Liam Lee
Jenny Lee
Anja Lee
Multiple Parameters : You can have as many parameters as you like:

class Main
{
static void myMethod(String fname, int age)
{
System.out.println(fname + " is " + age);
}
public static void main(String[] args)
{
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}

Liam is 5
Jenny is 8
Anja is 31

• Note 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 passed
in the same order.
Return Values
• The void keyword, used in the examples above, indicates that the method
should not return a value.
• If you want the method to return a value, you can use a primitive data type
(such as int, char, etc.) instead of void, and use the return keyword inside the
method:

class Main
{
static int myMethod(int x)
{
return 5 + x;
}
public static void main(String[] args)
{
System.out.println(myMethod(3));
}
}

Outputs
8
This example returns the sum of a method's two parameters:

public class Main


{
static int myMethod(int x, int y)
{
return x + y;
}
public static void main(String[] args)
{
System.out.println(myMethod(5, 3));
}
}

Outputs
8
• You can also store the result in a variable (recommended, as it is easier
to read and maintain):

class Main
{
static int myMethod(int x, int y)
{
return x + y;
}
public static void main(String[] args)
{
int z = myMethod(5, 3);
System.out.println(z);
}
}

Outputs
8
Method Overloading
• With method overloading, multiple methods can
have the same name with different parameters:

Example

• int myMethod(int x)
• float myMethod(float x)
• double myMethod(double x, double y)
• Consider the following example, which have two methods that add numbers of different type:

class Main
{
static int plusMethodInt(int x, int y)
{
return x + y;
}
static double plusMethodDouble(double x, double y)
{
return x + y;
}
public static void main(String[] args)
{
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
}

int: 13
double: 10.559999999999999
Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:

public class Main


{
static int plusMethod(int x, int y)
{
return x + y;
}
static double plusMethod(double x, double y)
{
return x + y;
}
public static void main(String[] args)
{
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
}

int: 13
double: 10.559999999999999

Note: Multiple methods can have the same name as long as the number and/or type of parameters are
different.
Searching Array
• Linear search is used to search a key element from
multiple elements.

Algorithm:
Step 1: Traverse the array

Step 2: Match the key element with array element

Step 3: If key element is found, return the index


position of the array element

Step 4: If key element is not found, return -1


public class LinearSearchExample
{
public static int linearSearch(int[] arr, int key)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i] == key)
{
return i;
}
}
return -1;
}
public static void main(String a[])
{
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
Output:

50 is found at index: 3
Java Program to Sort an Array in Ascending Order
Using the sort() Method
• In Java, Arrays is the class defined in the java.util package that provides sort() method to
sort an array in ascending order.

import java.util.Arrays;
public class SortArrayExample1
{
public static void main(String[] args)
{
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};

//invoking sort() method of the Arrays class


Arrays.sort(array);

System.out.println("Elements of array sorted in ascending order: ");

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


{
System.out.println(array[i]);
}
}
}
Sortig Array Without Using the sort()Method
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int size, temp;
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");

size = scan.nextInt();
int num[] = new int[size];
System.out.println("Enter array elements:");
for (int i = 0; i < size; i++)
{
num[i] = scan.nextInt();
}
scan.close();
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < size - 1; i++)
{
System.out.print(num[i] + ", ");
}
System.out.print(num[size - 1]);
}
}
Thank You

You might also like