Arrays
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
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
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
int percentage[10];
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]
Multidimensional Array
Multidimensional Array
▪ 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
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
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.
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();
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"
}
}
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
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
▪ 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.
//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 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
Arrays.sort(arr);
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
}
Syntax Example
return-type method_name(datatyp1 arg1, datatype2 arg2, …) int addition(int a, int b);
{ {
functions statements return a+b;
} }
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.
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);
No Arguments
void add()
main()
{
{
S.O.P(5+10);
add(); No Return Value }
}
No Arguments
main() int add()
{ {
int a; return 5+10;
a = add(); With Return Value }
}
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 }
}
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 }
}
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.
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.
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.
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.
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).
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
Thank You