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

Arrays

The document provides an overview of Java programming concepts related to methods and arrays, focusing on single-dimensional and multi-dimensional arrays. It covers array declaration, initialization, and various operations such as copying, searching, sorting, and passing arrays to methods. Additionally, it includes practical examples and exercises for implementing these concepts in Java.

Uploaded by

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

Arrays

The document provides an overview of Java programming concepts related to methods and arrays, focusing on single-dimensional and multi-dimensional arrays. It covers array declaration, initialization, and various operations such as copying, searching, sorting, and passing arrays to methods. Additionally, it includes practical examples and exercises for implementing these concepts in Java.

Uploaded by

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

Java Programming

Methods and Arrays

Dr. G. Sudhakaran
School of Electronics Engineering
Vellore Institute of Technology, Chennai
 Looping
What we will learn OOP Java i s the easiest, scoring and my favorite subject

✓ Single Dimensional arrays


✓ Copying arrays
✓ Passing and returning array from method
✓ Searching and sorting arrays and the Array class
✓ Two-Dimensional array and its processing
✓ Passing Two-dimensional Array to methods
✓ Multidimensional Arrays

Module-3
OOP Java i s the easiest, scoring and my favorite subject

Introduction
Large Data Handling
Why Array?
 Very often we need to deal with relatively large set of data.
 E.g. OOP Java i s the easiest, scoring and my favorite subject

 Percentage of all the students of the college. (May be in thousands)


 Age of all the citizens of the city. (May be lakhs)
 We need to declare thousands or lakhs of the variable to store the
data which is practically not possible.
 We need a solution to store more data in a single variable.
 Array is the most appropriate way to handle such data.
 As per English Dictionary, “Array means collection or group or
arrangement in a specific order.”

Methods and Arrays 4


Array
 An array is a fixed size sequential collection of elements of same data type grouped under
single variable name. OOP Java i s the easiest, scoring and my favorite subject

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
int percentage[10];

Fixed Size Sequential Same Data type Single Variable Name


The size of an array is All the elements of an Data type of all the All the elements of an
fixed at the time of array are stored in a elements of an array is array will be referred
declaration which cannot consecutive blocks in a same which is defined at through common name.
be changed later on. memory. the time of declaration.
Here array name is
Here array size is 10. 10 (0 to 9) Here data type is int percentage

Methods and Arrays 5


Array declaration
 Normal Variable Declaration: int a;
OOP Java i s the easiest, scoring and my favorite subject

 Array Variable Declaration: int b[10];


 Individual value or data stored in an array is known as an
element of an array.
 Positioning / indexing of an elements in an array always
starts with 0 not 1.
 If 10 elements in an array then index is 0 to 9
 If 100 elements in an array then index is 0 to 99
 If 35 elements in an array then index is 0 to 34
 Variable a stores 1 integer number where as variable b
stores 10 integer numbers which can be accessed as b[0],
b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8] and b[9]

Methods and Arrays 6


Array
 Important point about Java array.
 An array is derived datatype. OOP Java i s the easiest, scoring and my favorite subject

 An array is dynamically allocated.


 The individual elements of an array is refereed by their index/subscript value.
 The subscript for an array always begins with 0.

35 13 28 106 35
a 42 5 83 97 14
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

Methods and Arrays 7


One-Dimensional Array
 An array using one subscript to represent the list of elements is called one dimensional array.
OOP Java i s the easiest, scoring and my favorite subject

 A One-dimensional array is essentially a list of like-typed variables.


 Array declaration: type var-name[];
Example: int student_marks[];
 Above example will represent array with no value (null).
 To link student_marks with actual array of integers, we must allocate one using new
keyword.
Example: int student_marks[] = new int[20];

Methods and Arrays 8


Example (Array)
public class ArrayDemo{ OOP Java i s the easiest, scoring and my favorite subject
public static void main(String[] args) {
int a[]; // or int[] a
// till now it is null as it does not assigned any memory

a = new int[5]; // here we actually create an array


a[0] = 5;
a[1] = 8;
a[2] = 15;
a[3] = 84;
a[4] = 53;

/* in java we use length property to determine the length


* of an array, unlike c where we used sizeof function */
for (int i = 0; i < a.length; i++) {
System.out.println("a["+i+"]="+a[i]);
}
}
}

Methods and Arrays 9


WAP to store 5 numbers in an array and print them
OOP Java i s the easiest, scoring and my favorite subject
1. import java.util.*;
2. class ArrayDemo1{
3. public static void main (String[] args){
4. int i, n;
5. int[] a=new int[5];
6. Scanner sc = new Scanner(System.in);
7. System.out.print("enter Array Length:"); Output:
8. n = sc.nextInt(); enter Array
Length:5
9. for(i=0; i<n; i++) {
enter a[0]:1
10. System.out.print("enter a["+i+"]:"); enter a[1]:2
11. a[i] = sc.nextInt(); enter a[2]:4
12. } enter a[3]:5
13. for(i=0; i<n; i++) enter a[4]:6
14. System.out.println(a[i]); 1
15. } 2
16. } 4
5
6

Module 03 – Methods and Arrays 10


WAP to print elements of an array in reverse order
1. import java.util.*; OOP Java i s the easiest, scoring and my favorite subject

2. public class RevArray{


3. public static void main(String[] args) {
4. int i, n;
5. int[] a;
6. Scanner sc=new Scanner(System.in);
7. System.out.print("Enter Size of an Array:"); Output:
8. n=sc.nextInt();
Enter Size of an
9. a=new int[n];
Array:5
10. for(i=0; i<n; i++){
enter a[0]:1
11. System.out.print("enter a["+i+"]:");
enter a[1]:2
12. a[i]=sc.nextInt();
enter a[2]:3
13. }
enter a[3]:4
14. System.out.println("Reverse Array");
enter a[4]:5
15. for(i=n-1; i>=0; i--)
Reverse Array
16. System.out.println(a[i]);
5
17. }
4
18. }
3
2
1
Module 03 – Methods and Arrays 11
WAP to count positive number, negative number and zero from an array of n size
1. import java.util.*;
2. class ArrayDemo1{ OOP Java i s the easiest, scoring and my favorite subject

3. public static void main (String[] args){


4. int n,pos=0,neg=0,z=0;
5. int[] a=new int[5];
6. Scanner sc = new Scanner(System.in);
7. System.out.print("enter Array Length:");
8. n = sc.nextInt(); Output:
9. for(int i=0; i<n; i++) {
enter Array
10. System.out.print("enter a["+i+"]:");
11. a[i] = sc.nextInt(); Length:5
12. if(a[i]>0) enter a[0]:-3
13. pos++; enter a[1]:5
14. else if(a[i]<0) enter a[2]:0
15. neg++; enter a[3]:-2
16. else enter a[4]:00
17. z++; Positive no=1
18. } Negative no=2
19. System.out.println("Positive no="+pos);
Zero no=2
20. System.out.println("Negative no="+neg);
21. System.out.println("Zero no="+z);
22. }}

Methods and Arrays 12


Exercise: Array
1. WAP to count odd and even elements of an array.
OOP Java i s the easiest, scoring and my favorite subject

2. WAP to calculate sum and average of n numbers from an array.


3. WAP to find largest and smallest from an array.

Methods and Arrays 13


OOP Java i s the easiest, scoring and my favorite subject

Multidimensional Array
Multidimensional Array

OOP Java i s the easiest, scoring and my favorite subject

Methods and Arrays 15


WAP to read 3 x 3 elements in 2d array
1. import java.util.*;
2. class Array2Demo{ Column-0 Column-1 Column-2
OOP Java i s the easiest, scoring and my favorite subject
3. public static void main(String[] args) {
4. int size; Row-0 11 18 -7
5. Scanner sc=new Scanner(System.in);
6. System.out.print("Enter size of an array");
7. size=sc.nextInt(); Row-1 25 100 0
8. int a[][]=new int[size][size];
9. for(int i=0;i<a.length;i++){ Row-2 -4 50 88
10. for(int j=0;j<a.length;j++){
11. a[i][j]=sc.nextInt(); Output:
12. } 11
13. } 12
13
14. for(int i=0;i<a.length;i++){ 14
15. for(int j=0;j<a.length;j++){ 15
16. System.out.print("a["+i+"]["+j+"]:"+a[i][j]+"\t");
16
17. } 17
18. System.out.println(); 18
19. } 19
20. } a[0][0]:11 a[0][1]:12 a[0][2]:13
21.} a[1][0]:14 a[1][1]:15 a[1][2]:16
a[2][0]:17 a[2][1]:18 a[2][2]:19
Methods and Arrays 16
WAP to perform addition of two 3 x 3 matrices
1. import java.util.*; 1. b=new int[size][size];
OOP Java i s the easiest, scoring and my favorite subject

2. class Array2Demo{ 2. for(int i=0;i<b.length;i++){


3. public static void main(String[] args) { 3. for(int j=0;j<b.length;j++){
4. int size; 4. System.out.print("Enter
5. int a[][],b[][],c[][];
6. Scanner sc=new Scanner(System.in); b["+i+"]["+j+"]:");
7. System.out.print("Enter size of an 5. b[i][j]=sc.nextInt();
array:"); 6. }
8. size=sc.nextInt(); 7. }
9. a=new int[size][size]; 8. c=new int[size][size];
10. System.out.println("Enter array 9. for(int i=0;i<c.length;i++){
elements:"); 10. for(int j=0;j<c.length;j++){
11. for(int i=0;i<a.length;i++){ 11. System.out.print("c["+i+"]["+j+"]:“
12. for(int j=0;j<a.length;j++){ +(a[i][j]+b[i][j])+"\t");
13. System.out.print("Enter
a["+i+"]["+j+"]:"); 12. }
14. a[i][j]=sc.nextInt(); 13. System.out.println();
15. } 14. }
16. } 15. }//main()
16. }//class

Dr.G.Sudhakaran Module 03 – Methods and Arrays 17


WAP to perform addition of two 3 x 3 matrices
Output:
OOP Java i s the easiest, scoring and my favorite subject

Enter size of an array:3


Enter array elements:
Enter a[0][0]:1
Enter a[0][1]:1
Enter a[0][2]:1
Enter a[1][0]:1
Enter a[1][1]:1
Enter a[1][2]:1
Enter a[2][0]:1
Enter a[2][1]:1
Enter a[2][2]:1
Enter b[0][0]:4
Enter b[0][1]:4
Enter b[0][2]:4
Enter b[1][0]:4
Enter b[1][1]:4
Enter b[1][2]:4
Enter b[2][0]:4
Enter b[2][1]:4
Enter b[2][2]:4
c[0][0]:5 c[0][1]:5 c[0][2]:5
c[1][0]:5 c[1][1]:5 c[1][2]:5
c[2][0]:5 c[2][1]:5 c[2][2]:5
Initialization of an array elements
1. One dimensional Array
1. int a[5] = { 7, 3, -5, 0, 11 }; // a[0]=7, a[1] = 3, a[2] = -5, a[3] = 0, a[4] = 11
OOP Java i s the easiest, scoring and my favorite subject

2. int a[5] = { 7, 3 }; // a[0] = 7, a[1] = 3, a[2], a[3] and a[4] are 0


3. int a[5] = { 0 }; // all elements of an array are initialized to 0

2. Two dimensional Array


1. int a[2][4] = { { 7, 3, -5, 10 }, { 11, 13, -15, 2} }; // 1st row is 7, 3, -5, 10 & 2nd row is 11, 13, -15, 2
2. int a[2][4] = { 7, 3, -5, 10, 11, 13, -15, 2 }; // 1st row is 7, 3, -5, 10 & 2nd row is 11, 13, -15, 2
3. int a[2][4] = { { 7, 3 }, { 11} }; // 1st row is 7, 3, 0, 0 & 2nd row is 11, 0, 0, 0
4. int a[2][4] = { 7, 3 }; // 1st row is 7, 3, 0, 0 & 2nd row is 0, 0, 0, 0
5. int a[2][4] = { 0 }; // 1st row is 0, 0, 0, 0 & 2nd row is 0, 0, 0, 0

Methods and Arrays 19


Multi-Dimensional Array
 In java, multidimensional array is actually array of arrays.
OOP Java i s the easiest, scoring and my favorite subject

 Example: int runPerOver[][] = new int[3][6];


First Over (a[0]) 4 0 1 3 6 1
a[0][0] a[0][1] a[0][2] a[0][3] a[0][4] a[0][5]

Second Over (a[1]) 1 1 0 6 0 4


a[1][0] a[1][1] a[1][2] a[1][3] a[1][4] a[1][5]

Third Over (a[2]) 2 1 1 0 1 1


a[2][0] a[2][1] a[2][2] a[2][3] a[2][4] a[2][5]

▪ length field:
▪ If we use length field with multidimensional array, it will return length of first dimension.
▪ Here, if runPerOver.length is accessed it will return 3
▪ Also if runPerOver[0].length is accessed it will be 6

Methods and Arrays 20


Multi-Dimensional Array (Example)
Scanner s = new Scanner(System.in); OOP Java i s the easiest, scoring and my favorite subject
int runPerOver[][] = new int[3][6];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
System.out.print("Enter Run taken" +
" in Over numner " + (i + 1) +
" and Ball number " + (j + 1) + " = ");
runPerOver[i][j] = s.nextInt();
}
}
int totalRun = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
totalRun += runPerOver[i][j];
}
}
double average = totalRun / (double) runPerOver.length;
System.out.println("Total Run = " + totalRun);
System.out.println("Average per over = " + average);

Methods and Arrays 21


Multi-Dimensional Array (Cont.)
 manually allocate different size:
int runPerOver[][] = new int[3][];
OOP Java i s the easiest, scoring and my favorite subject

runPerOver[0] = new int[6];


runPerOver[1] = new int[7];
runPerOver[2] = new int[6];
 initialization:
int runPerOver[][] = {
{0,4,2,1,0,6},
{1,-1,4,1,2,4,0},
{6,4,1,0,2,2},
}
Note : here to specify extra runs (Wide, No Ball etc.. ) negative values are used

Methods and Arrays 22


OOP Java i s the easiest, scoring and my favorite subject

Searching in Array
Searching in Array
 Searching is the process of looking for a specific element in an array. for example, discovering
whether a certain element is included in the array. OOP Java i s the easiest, scoring and my favorite subject

 Searching is a common task in computer programming. Many algorithms and data structures
are devoted to searching.
 We will discuss two commonly used approaches,
 Linear Search: The linear search approach compares the key element key sequentially with
each element in the array. It continues to do so until the key matches an element in the
array or the array is exhausted without a match being found.
 Binary Search: The binary search first compares the key with the element in the middle of
the array. Consider the following three cases:
▪ If the key is less than the middle element, you need to continue to search for the key only in the first half
of the array.
▪ If the key is equal to the middle element, the search ends with a match.
▪ If the key is greater than the middle element, you need to continue to search for the key only in the second
half of the array.
Note: Array should be sorted in ascending order if we want to use Binary Search.
Methods and Arrays 24
Linear Search
1. import java.util.*; Output:
2. class LinearSearchDemo{ Enter element to search 6
OOP Java i s the easiest, scoring and my favorite subject

3. public static void main(String[] args) { element found at 5th index


4. int size; Enter element to search 35
5. int a[]={1,2,3,4,5,6,7,8,9}; element NOT found!
6. int search;
7. boolean flag=false;
8. Scanner sc=new Scanner(System.in);
9. System.out.print("Enter element to search");
10. search=sc.nextInt();
11. for(int i=0;i<a.length;i++){
12. if(a[i]==search){
13. System.out.println("element found at "+i+"th index");
14. flag=true;
15. break;
16. }
17. }
18. if(!flag)
19. System.out.println("element NOT found!");
20. }
21. }
Methods and Arrays 25
Binary Search (Animation)

OOP Java i s the easiest, scoring and my favorite subject

Methods and Arrays 26


Binary Search
1. import java.util.*; 13. while(high>=low){
2. class BinaryDemo{ 14. int mid=(high+low)/2;
OOP Java i s the easiest, scoring and my favorite subject

3. public static void main(String[] 15. if(search==a[mid]){


args){ 16. flag=true;
4. int size; 17. System.out.println("element found
5. int a[]={1,2,3,4,5,6,7,8,9}; at "+mid+" index ");
6. int search; 18. break;
7. boolean flag=false; 19. }
8. Scanner sc=new Scanner(System.in); 20. else if(search<a[mid]){
9. System.out.print("Enter element to 21. high=mid-1;
search:"); 22. }
10. search=sc.nextInt(); 23. else if(search>a[mid]){
Output:
11. int low=0; 24. low=mid+1;
Enter element to search:5
12. int found
element high=at a.length-1;
4 index
25. }
26. }//while
Enter element to search:9 27. if(!flag)
element found at 8 index 28. System.out.println("element not found");
Enter element to search:56
29. }
element not found 30. }
Methods and Arrays 27
Sorting Array
 Sorting, like searching, is a common task in computer programming. Many different algorithms
have been developed for sorting. OOP Java i s the easiest, scoring and my favorite subject

 There are many sorting techniques available, we are going to explore selection sort.
 Selection sort
 finds the smallest number in the list and swaps it with the first element.
 It then finds the smallest number remaining and swaps it with the second element, and so
on, until only a single number remains.

Methods and Arrays 28


Bubble Sort (Example)
public class BubbleSortWithoutExtras { for (int i = 0; i < n - 1; i++) {
public static void main(String[] args) for (int j = 0; j < n - i - 1; j++) {
OOP Java i s the easiest, scoring and my favorite subject

{ if (numbers[j] > numbers[j + 1]) {


int[] numbers = {64, 34, 25, 12, int temp = numbers[j];
22, 11, 90}; numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
System.out.println("Unsorted }
array:"); }
for (int num : numbers) { }
System.out.print(num + " "); System.out.println("Sorted array:");
} for (int num : numbers) {
System.out.println(); System.out.print(num + " ");
int n = numbers.length; }
}
}

Methods and Arrays 29


Selection Sort (Example)
1. import java.util.*; 5. for (int i = 0; i < a.length - 1; i++) {
2. class SelectionSearchDemo{ 6. // Find the minimum in the list[i..a.length-1]
OOP Java i s the easiest, scoring and my favorite subject

3. public static void main(String[] args) 7. int min = a[i];


{ 8. int minIndex = i;
4. int a[]={ 5, 2, 9, 3, 4, 1, 8, 6, 7 }; 9. for (int j = i + 1; j < a.length; j++) {
10. if (min > a[j]) {
11. min = a[j];
12. minIndex = j;
13. }
14. }//inner for loop j
15.// Swap a[i] with a[minIndex]
16. if (minIndex != i) {
Output: 17. a[minIndex] = a[i];
1, 2, 3, 4, 5, 6, 7, 8, 9, 18. a[i] = min;
19. }
20. }//outer for i
21. for(int temp: a) { // this is foreach loop
22. System.out.print(temp + ", ");
23. }
24. }//main()
25.}//class
Methods and Arrays 30
String Class
 An object of the String class represents a string of characters.
OOP Java i s the easiest, scoring and my favorite subject

 The String class belongs to the java.lang package, which does not require an import
statement.
 Like other classes, String has constructors and methods.
 String class has two operators, + and += (used for concatenation).
 Empty String :
 An empty String has no characters. It’s length is 0.
String word1 = ""; Empty strings
String word2 = new String();

 Not the same as an uninitialized String. This is null


String word1;

Methods and Arrays 31


String Initialization
 Copy constructor creates a copy of an existing String.
OOP Java i s the easiest, scoring and my favorite subject

Copy Constructor: Each variable points to a different copy of the String.

String word = new String("Java"); word "Java"


String word2 = new String(word); word2 "Java"
Assignment: Both variables point to the same String.

String word = "Java"; word "Java"


String word2 = word; word2

Methods and Arrays 32


String Methods — length, charAt

OOP Java i s the easiest, scoring and my favorite subject

int length(); ◼ Returns the number of characters in the string


Returns:
"Problem".length(); 7

int charAt(i); ◼ Returns the char at position i.

Character positions in strings starts from 0 – just like arrays.


Returns:
"Window".charAt (2); 'n'

Methods and Arrays 33


String Methods — substring

We can obtain a portion of a string by use of substring(), It has two forms


OOP Java i s the easiest, scoring and my favorite subject

1. String subs = word.substring (i, k); television


returns the substring of chars in
positions from i to k-1 i k
2. String subs = word.substring (i); immutable
returns the substring from the i-th
char to the end
i
Returns:
"television".substring(2,5); “lev"
"immutable".substring(2); “mutable"
"rajkot".substring(9);
"" (empty string)

Methods and Arrays 34


String Methods — Concatenation
public class ConcatenationExample{ OOP Java i s the easiest, scoring and my favorite subject

public static void main(String[] args) {


String word1 = "re";
String word2 = "think";
String word3 = "ing";
int num = 2;
String result = word1 + word2;
// concatenates word1 and word2 "rethink"

result = word1.concat(word2);
// the same as word1 + word2 "rethink"

result += word3;
// concatenates word3 to result "rethinking"

result += num;
// converts num to String & joins it to result "rethinking2"
}
}

Methods and Arrays 35


String Methods — Find (indexOf)

OOP Java i s the easiest, scoring and my favorite subject

String name = " P r i m e M i n i s t e r ";


0 1 2 3 4 5 6 7 8 9 10 11 12 13

name.indexOf ('P'); 0
name.indexOf ('e'); 4
name.indexOf ("Minister"); 6
name.indexOf ('e', 8); 12
(starts searching at position 8)
name.indexOf (“xyz"); -1 (not found)
name.lastIndexOf ('e'); 12

Methods and Arrays 36


String Methods — Equality
boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2 OOP Java i s the easiest, scoring and my favorite subject

b = "Raiders".equals("Raiders"); // will return true


b = "Raiders".equals("raiders"); // will return false

boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2, ignoring the case of the string.
b = "Raiders".equalsIgnoreCase("raiders"); // will return true

Methods and Arrays 37


String Methods — Comparisons
int diff = word1.compareTo(word2);
returns the “difference” word1 - word2
OOP Java i s the easiest, scoring and my favorite subject

int diff = word1.compareToIgnoreCase(word2);


returns the “difference” word1 - word2,
ignoring the case of the strings

▪ Usually programmers don’t care what the numerical “difference” of word1 - word2 is,
what matters is if
▪ the difference is negative (word1 less than word2),
▪ zero (word1 and word2 are equal) if(word1.compareTo(word2) > 0){
//word1 grater than word2…
▪ or positive (word1 grater than word2).
}
▪ Often used in conditional statements.

Methods and Arrays 38


Comparison Examples
//negative differences OOP Java i s the easiest, scoring and my favorite subject

diff = "apple".compareTo("berry"); // a less than b


diff = "Zebra".compareTo("apple"); // Z less than a
diff = "dig".compareTo("dug"); // i less than u
diff = "dig".compareTo("digs"); // dig is shorter

//zero differences
diff = "apple".compareTo("apple"); // equal
diff = "dig".compareToIgnoreCase("DIG"); // equal

//positive differences
diff = "berry".compareTo("apple"); // b grater than a
diff = "apple".compareTo("Apple"); // a grater than A
diff = "BIT".compareTo("BIG"); // T grater than G
diff = "application".compareTo("app"); // application is longer

Methods and Arrays 39


String Methods — trim & replace
trim() method replace() method
OOP Java i s the easiest, scoring and my favorite subject

String word2 = word1.trim(); String word2 = word1.replace(oldCh, newCh);


 returns a new string formed from  returns a new string formed from
word1 by removing white space at both word1 by replacing all occurrences of
ends, oldCh with newCh
 it does not affect whites space in the
middle.
String word1 = " Hello From VIT "; String word1 = "late";
String word2 = word1.trim(); String word2 = word1.replace('l', 'h');
// word2 is "Hello From VIT" System.out.println(word2);
// no spaces on either end //Output : "hate"

String str1 = "Hello World";


String str2 =
str1.replace("World","Everyone");
System.out.println(str2);
// Output : "Hello Everyone"
Module 03 – Methods and Arrays 40
String Methods — Changing Case
OOP Java i s the easiest, scoring and my favorite subject

String word2 = word1.toUpperCase();


returns a new string formed from word1 by converting its characters to upper case
String word3 = word1.toLowerCase();
returns a new string formed from word1 by converting its characters to lower case

String word1 = "HeLLo";


String word2 = word1.toUpperCase(); // "HELLO"
String word3 = word1.toLowerCase(); // "hello"

Module 03 – Methods and Arrays 41


StringBuffer Methods
Method description
OOP Java i s the easiest, scoring and my favorite subject

append(String s) is used to append the specified string with this string.


insert(int offset, String s) is used to insert the specified string with this string at the specified
position.
replace(int startIndex, int endIndex, String str) is used to replace the string from specified startIndex and endIndex.
delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.
reverse() is used to reverse the string.

 Remember : “StringBuffer” is mutable


 As StringBuffer class is mutable we need not to replace the reference with a new
reference as we have to do it with String class.
StringBuffer str1 = new StringBuffer("Hello Everyone");
str1.reverse();
// as it is mutable can not write str1 = str1.reverse();
// it will change to value of the string itself
System.out.println(str1);
// Output will be “enoyrevE olleH”
Methods and Arrays 42
Searching a char in an array
// Initialize a flag to keep track of whether the character is
import java.util.Scanner; found or not
OOP Java i s the easiest, scoring and my favorite subject

boolean found = false;


public class CharacterSearch {
// Iterate through the array and check each character
public static void main(String[] args) { for (char c : charArray) {
Scanner scanner = new Scanner(System.in); if (c == searchChar) {
found = true;
// Ask user for the input array break;
for (int i=0;i<input.length();i++) {
System.out.print("Enter the array of characters separated by }
Char c=charArray[i];
space: "); }
if (c == searchChar)
String input = scanner.nextLine(); // Display the result
if (found) {
// Split the input string into an array of characters System.out.println("The character " + searchChar + "
char[] charArray = input.toCharArray(); was found in the array.");
} else {
// Ask user for the character to search System.out.println("The character " + searchChar + "
System.out.print("Enter the character to search: "); was not found in the array.");
char searchChar = scanner.next().charAt(0); }

}
Methods and Arrays 43
Sorting string
 public class Main {
}
OOP Java i s the easiest, scoring and my favorite subject
 public static void main(String[] args) { }
 String str = "sortingexample"; // Input string
// Convert the sorted character array back to
 char[] charArray = str.toCharArray(); // Convert string a string
to character array String sortedStr = new String(charArray);
 int n = charArray.length;
// Print the sorted string
 // Bubble sort algorithm to sort the character array System.out.println("Sorted string: " +
 for (int i = 0; i < n-1; i++) { sortedStr);
}
 for (int j = 0; j < n-i-1; j++) { }
 if (charArray[j] > charArray[j+1]) {
 // Swap characters if they are in the wrong order char[] arr = {'c', 'a', 'e', 'b', 'd’};
 char temp = charArray[j]; //char array sorting

 charArray[j] = charArray[j+1];
 charArray[j+1] = temp;
 }
Methods and Arrays 44
Conversion of string to char array without built-in functions
 public class StringToCharArrayExample {
OOP Java i s the easiest, scoring and my favorite subject

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


 String str = "Hello World";
 byte[] bytes = str.getBytes();
 char[] charArray = new char[bytes.length];

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


 charArray[i] = (char) (bytes[i] & 0xFF);
 }
 System.out.println(charArray);
 }
}
Methods and Arrays 45
Sorting array of strings
public class StringSorter {
public static void main(String[] args) { OOP Java i s the easiest, scoring and my favorite subject

String[] strings = {"hello", "world", "java", "programming"};

// Sort the array of strings


for (int i = 0; i < strings.length; i++) {
for (int j = i + 1; j < strings.length; j++) {
if (strings[i].compareTo(strings[j]) > 0) {
// Swap the two strings
String temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
}

// Print the sorted array of strings


for (String s : strings) {
System.out.println(s);
}
}
Methods and Arrays 46
Sorting using built-in functions
 import java.util.Arrays;
OOP Java i s the easiest, scoring and my favorite subject

 public class StringSort {


 public static void main(String[] args) {
 String[] arr = {"banana", "apple", "cherry", "date", "fig"};

 System.out.println("Original array: " + Arrays.toString(arr));

 Arrays.sort(arr);

 System.out.println("Sorted array: " + Arrays.toString(arr));


 }
} Methods and Arrays 47
 Looping
What we will learn OOP Java i s the easiest, scoring and my favorite subject

• Defining and calling method


• Passing argument by values

Unit-3
Method
OOP Java i s the easiest, scoring and my favorite subject

What is Method?
What is Method?
 A method is a group of statements that performs a specific task.
OOP Java i s the easiest, scoring and my favorite subject

 A large program can be divided into the basic building blocks known as method/function.
 The function contains the set of programming statements enclosed by { }.
 Program execution in many programming language starts from the main function.
 main is also a method/function.
void main()
{
// body part
}

Methods and Arrays 50


Types of Function

Function OOP Java i s the easiest, scoring and my favorite subject

Library Function User Defined Function (UDF)

Predefined or declared inside header files Created by User


• nextInt() – util library • CalculateSimpleInterest()
• pow() – math library • CalculateAreaOfCircle()

Methods and Arrays 51


Program Structure of Function
 User-defined function’s program structure is divided into three parts as follows:
OOP Java i s the easiest, scoring and my favorite subject

C:Function Structure Java:Function for addition of 2 numbers


void func1(); Function Prototype class MethodDemo{
public static void main(String[] ags){
int a=10,b=20,c;
void main() c=add(a,b);
{ Function call System.out.println("a+b="+c);
.... }
func1(); static int add(int i, int j){
} Function definition return i+j;
}
void func1() }
{
....
//function body
....
}

Methods and Arrays 52


Method Definition
 A method definition defines the method header and body.
OOP Java i s the easiest, scoring and my favorite subject

 A method body part defines method logic.


 Method statements

Syntax Example
return-type method_name(datatyp1 arg1, datatype2 arg2, …) int addition(int a, int b);
{ {
functions statements return a+b;
} }

Methods and Arrays 53


WAP to add two number using add(int, int) Function
1. class MethodDemo{
OOP Java i s the easiest, scoring and my favorite subject

2. public static void main(String[] args) {


3. int a=10,b=20,c;
4. MethodDemo md=new MethodDemo();
5. c=md.add(a,b);
6. System.out.println("a+b="+c);
7. }//main()
8. int add(int i, int j){
9. return i+j;
10. }
11.} Output:
a+b=30

Methods and Arrays 54


Actual parameters v/s Formal parameters
 Values that are passed from the calling functions are known actual parameters.
OOP Java i s the easiest, scoring and my favorite subject

 The variables declared in the function prototype or definition are known as formal parameters.
 Name of formal parameters can be same or different from actual parameters.
 Sequence of parameter is important, not name.

Actual Parameters Formal Parameters


int add(int i, int j)
int a=10,b=20,c;
{
MethodDemo md=new MethodDemo();
return i+j;
c=md.add(a,b);
}
// a and b are the actual parameters.
// i and j are the formal parameters.

Methods and Arrays 55


Return Statement
 The function can return only one value. OOP Java i s the easiest, scoring and my favorite subject

 Function cannot return more than one value.


 If function is not returning any value then return type should be void.

Actual Parameters Formal Parameters


int sub(int i, int j)
int a=10,b=20,c;
{
MethodDemo md=new MethodDemo();
return i – j;
c=md.sub(a,b);
}
// a and b are the actual parameters.
// i and j are the formal parameters.

Methods and Arrays 56


WAP to calculate the Power of a Number using method
1. import java.util.*; 14. int power(int a, int b){
2. public class PowerMethDemo1{ OOP Java i s the easiest, scoring and my favorite subject

15. int i, r = 1;
3. public static void main(String[] args){
4. int num, pow, res; 16. for(i=1; i<=b; i++)
5. Scanner sc=new Scanner(System.in); 17. {
6. System.out.print("enter num:");
7. num=sc.nextInt(); 18. r = r * a;
8. System.out.print("enter pow:"); 19. }
9. pow=sc.nextInt(); 20. return r;
10. PowerMethDemo1 pmd=new
PowerMethDemo1(); 21. }//power()
11. res = pmd.power(num, pow); 22. }//class
12. System.out.print("ans="+res);
13. } //main()

Output:
enter num:5
enter pow:3
ans=125
Methods and Arrays 57
Types of Methods(Method Categories)
 Functions can be divided in 4 categories based on arguments and return value.
Method without arguments and without return value
OOP Java i s the easiest, scoring and my favorite subject

1. void add();
2. Method without arguments and with return value int add();
3. Method with arguments and without return value void add(int, int);
4. Method with arguments and with return value int add(int, int);

Methods and Arrays 58


Method without arguments and without return value
OOP Java i s the easiest, scoring and my favorite subject

No Arguments
void add()
main()
{
{
S.O.P(5+10);
add(); No Return Value }
}

Methods and Arrays 59


Method without arguments and with return value
OOP Java i s the easiest, scoring and my favorite subject

No Arguments
main() int add()
{ {
int a; return 5+10;
a = add(); With Return Value }
}

Methods and Arrays 60


Method with arguments and without return value
OOP Java i s the easiest, scoring and my favorite subject

With Arguments
main() void add(int a, int b)
{ {
int a=5,b=10; S.O.P(a+b);
add(a,b); No Return Value }
}

Methods and Arrays 61


Method with arguments and with return value
OOP Java i s the easiest, scoring and my favorite subject

With Arguments
main() int add(int a, int b)
{ {
int a=5,b=10,c; return a + b;
c=add(a,b); With Return Value }
}

Methods and Arrays 62


OOP Java i s the easiest, scoring and my favorite subject

Method Overloading
Method Overloading: Compile-time Polymorphism
 Definition: When two or more methods are implemented that share same name but different
parameter(s), the methods are said to be overloaded, and the process is referred to as method
OOP Java i s the easiest, scoring and my favorite subject

overloading
 Method overloading is one of the ways that Java implements polymorphism.
 When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call.
 E.g. public void draw()
public void draw(int height, int width)
public void draw(int radius)
 Thus, overloaded methods must differ in the type and/or number of their parameters.
 While in overloaded methods with different return types and same name & parameter are not
allowed ,as the return type alone is insufficient for the compiler to distinguish two versions of
a method.

Methods and Arrays 64


Method Overloading: Compile-time Polymorphism
19. class OverloadDemo{
1. class Addition{ 20.public static void
2. int i,j,k; OOP Java i s the easiest, scoring and my favorite subject
main(String[] args){
3. void add(int a){ 21. Addition a1= new Addition();
4. i=a; 22. //call all versions of add()
5. System.out.println("add i="+i); 23. a1.add(20);
6. } 24. a1.add(30,50);
7. void add(int a,int b){\\overloaded add() 25. a1.add(10,30,60);
8. i=a; 26. }
9. j=b; 27.}
10. System.out.println("add i+j="+(i+j));
11. }
12. void add(int a,int b,int c){\\overloaded add()
13. i=a;
14. j=b; Output
15. k=c; add i=20
16. System.out.println("add i+j+k="+(i+j+k)); add i+j=80
17. } add i+j+k=100
18.}

Methods and Arrays 65


Method Overloading: Compile-time Polymorphism
22. class OverloadDemo{
1. class Addition{
2. int i,j,k; 23.public static void
OOP Java i s the easiest, scoring and my favorite subject

3. void add(int a){ main(String[] args){


4. i=a; 24. Addition a1= new Addition();
5. System.out.println("add i="+i); 25. //call all versions of add()
6. } 26. a1.add(20);
7. void add(int a,int b){\\overloaded add() 27. a1.add(30,50);
8. i=a; 28. a1.add(10,30,60);
9. j=b; 29. a1.add(30.5,50.67);
10. System.out.println("add i+j="+(i+j));
30. }
11. }
12. void add(double a, double b){\\overloaded add() 31.}
13. System.out.println("add a+b="+(a+b));
14. }
15. void add(int a,int b,int c){\\overloaded add() Output
16. i=a;
17. j=b; add i=20
18. k=c; add i+j=80
19. System.out.println("add i+j+k="+(i+j+k)); add i+j+k=100
20. }
21.}
add a+b=81.17

Methods and Arrays 66


Method Overloading: Points to remember
 Method overloading supports polymorphism because it is one way that Java implements the
“one interface, multiple methods” paradigm. OOP Java i s the easiest, scoring and my favorite subject

 Overloading increases the readability of the program.


 There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
 In java, method overloading is not possible by changing the return type of the method only
because of ambiguity.

Methods and Arrays 67


Method Overloading: Points to remember
Can we overload java main() method?
OOP Java i s the easiest, scoring and my favorite subject

 Yes, by method overloading. We can have any number of main methods in a class by method
overloading
 But JVM calls main() method which receives string array as arguments only.

Methods and Arrays 68


Advantages of Method
 Reduced Code Redundancy
 Rewriting the same logic or code again and again in a program can be avoided.
OOP Java i s the easiest, scoring and my favorite subject

 Reusability of Code
 Same function can be call from multiple times without rewriting code.
 Reduction in size of program
 Instead of writing many lines, just function need to be called.
 Saves Development Time
 Instead of changing code multiple times, code in a function need to be changed.
 More Traceability of Code
 Large program can be easily understood or traced when it is divide into functions.
 Easy to Test & Debug
 Testing and debugging of code for errors can be done easily in individual function.

Methods and Arrays 69


OOP Java i s the easiest, scoring and my favorite subject

Scope, Lifetime and


Visibility of a Variable
Scope of a Variable
 Whenever we declare a variable, we also determine its scope, lifetime and visibility.
OOP Java i s the easiest, scoring and my favorite subject

Scope Scope is defined as the area in which the declared variable is ‘accessible’.
There are five scopes: program, file, function, block, and class.
Scope is the region or section of code where a variable can be accessed.
Scoping has to do with when a variable is accessible and used.
Lifetime The lifetime of a variable is the period of time in which the variable is allocated a space (i.e., the period
of time for which it “lives”). There are three lifetimes in C: static, automatic and dynamic.
Lifetime is the time duration where an object/variable is in a valid state.
Lifetime has to do with when a variable is created and destroyed
Visibility Visibility is the “accessibility” of the variable declared. It is the result of hiding a variable in outer
scopes.

Methods and Arrays 71


Scope of a Variable
Function Structure
OOP Java i s the easiest, scoring and my favorite subject

class FunctionDemo{ Global Variable Scope Description


float f; Local "visible" within function or
static int a; (block/ statement block from point of
Static Global Variable function) declaration until the end of the
public static void main() block.
{ Local Variables Class "seen" by class members.
int i;
static int j; File visible within current file.
func1(i); Static Local Variable (program)
} Global visible everywhere unless
Parameter Variable "hidden".
void func1(int value)
{
int x;
//function body
....
}
}

Methods and Arrays 72


Lifetime of a variable
 The lifetime of a variable or object is the time period in which the variable/object has valid
memory. OOP Java i s the easiest, scoring and my favorite subject

 Lifetime is also called "allocation method" or "storage duration“.

Lifetime Stored
Static Entire duration of the program's execution. data segment
Automatic Begins when program execution enters the function or statement function call
block and ends when execution leaves the block. stack
Dynamic Begins when memory is allocated for the object (e.g., by a call heap
to malloc() or using new) and ends when memory is deallocated (e.g., by
a call to free() or using delete).

Methods and Arrays 73


Scope vs Lifetime of a variable
Variable Type Scope of a Variable Lifetime of a Variable
OOP Java i s the easiest, scoring and my favorite subject

Instance Variable Throughout the class except in static methods Until object is available in the
memory
Class Variable Throughout the class Until end of the Class
Local Variable Throughout the block/function in which it is declared Until control leaves the block

Methods and Arrays 74


Exercise
1. Write a function to check whether given number is prime or not.
OOP Java i s the easiest, scoring and my favorite subject

2. Write a function to search a given number from an array.

Methods and Arrays 75


OOP Java i s the easiest, scoring and my favorite subject

Thank You

You might also like