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

Arrays Functions

The document is a training module focused on Java software development, specifically covering arrays and functions. It provides a comprehensive overview of single-dimensional and multi-dimensional arrays, including jagged arrays, along with their declaration, instantiation, and usage in problem-solving. The content is structured to facilitate learning with examples, quizzes, and practical applications.

Uploaded by

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

Arrays Functions

The document is a training module focused on Java software development, specifically covering arrays and functions. It provides a comprehensive overview of single-dimensional and multi-dimensional arrays, including jagged arrays, along with their declaration, instantiation, and usage in problem-solving. The content is structured to facilitate learning with examples, quizzes, and practical applications.

Uploaded by

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

SDE Readiness Training

Empowering Tomorrow’s Innovators


Module I
Java Software Development:
Effective Problem Solving

2 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays and Functions
Learning Level: Basic and Easy

DATE: 18.09.2024
Contents

• Arrays

• Functions

4 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

5 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Contents

• Introduction

• Single Dimensional Array

• Multi Dimensional Array

• Multi Dimensional Array: Jagged Array

• Quiz

6 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Introduction

• An array is a container that holds a fixed number of values of a same data type.

• Need of Array: Difficult to manage large number of variable in normal way. The idea of array is to

represent many instances in one variable.

• Length of the array is fixed and index starts with 0. Can’t access the elements beyond the array

limit.

7 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Types

• There are three types of arrays in Java:

• Single Dimensional Array

• Multidimensional Array

• Jagged Array

8 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

• Single dimensional array is a collection of items under common name in linear array fashion.

• Declaration

• Syntax Example
dataType[] arrayName; (or) int []salary; //declaration
dataType []arrayName; (or) salary=new int[10]; //Instantiation
dataType arrayName[];
Instantiation of an Array in Java Declaration and Instantiation
arrayReferenceVariable=new dataType[size] int salary[]=new int[10];

Note:
• Array declaration only create reference of array variable.

• To create or give memory to array only at that time of array instantiation.


9 Arrays & Functions | © SmartCliff | Internal | Version 1.0
Arrays

Single Dimensional Array

Create Array

• int [] marks=new int[10]; //declaration and instantiation

(OR)

• int marks[]=new int[10];

• The [] operator is the indication to the compiler we are naming an array object and not an ordinary
variable.

• Java Array is object, we use the new operator to create an array.

10 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

Define or initialize Array values:

• There are two ways to define the array values:

1. During Declaration: int [] marks={89, 90, 67,35, 99, 80};

2. Using index : int marks[]=new int[10]; // declaration

marks[0]=89;

marks[1]=90;

………..

• Array Length: To find the array length java provides inbuilt length variable

int len=marks.length; //assigns the size of marks array in to the variable len

11 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

Retrieving and Processing Array Elements

• Array elements are accessed using index value. The index starts with 0.

element=marks[3]; //retrieve 4th element of array

marks[4]= 100; // update 100 into 5th position

• Since more number of elements are there in an array, loops are more convenient way to process.

• In general, array elements are accessed and processed using for loop and for….each loop.

12 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

/** Output:
* The ArrayDemo1 class implements an application that
Element at index 0: 89
* Illustrate the access array elements
*/ Element at index 1: 90
public class ArrayDemo1 { Element at index 2: 0
public static void main(String[] args) {
int[] marks = new int[3]; ; // create array
marks[0] = 89; //assign values
marks[1] = 90;
System.out.println("Element at index 0: " + marks[0]); //access elements
System.out.println("Element at index 1: " + marks[1]);
System.out.println("Element at index 2: " + marks[2]);
}
}

13 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

/**
* The CustomerDetail class implements an application that
* Illustrate the access array elements
*/
public class CustomerDetail {
public static void main(String[] args) {
String[] custName = new String[5]; ; // create array
custName[0] = "Aaron"; //assign values
custName[1] = "Kavin";
custName[2] = "Jesicca";
custName[3] = "Rishabh";
custName[4] = "Vinitha";

14 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

System.out.println("*********CUSTOMER DETAIL********"); Output:


System.out.println(custName[0]); //access elements *********CUSTOMER DETAIL********
System.out.println(custName[1]); Aaron
System.out.println(custName[2]);
Kavin
System.out.println(custName[3]);
Jesicca
System.out.println(custName[4]);
Rishabh
}
}
Vinitha

15 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

/** Output:
* The ArrayDemoForEach class implements an application that
Using for each Loop:
* Illustrate the access array elements using for-each statements
*/ 56
Class ArrayDemoForEach { 84
public static void main(String[] args) {
52
int[] marks = {56, 84, 52, 90, 100};
System.out.println("Using for each Loop:"); 90
for(int i:marks) { 100
System.out.println(i);
}
}
}

16 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

/**
* The CustomerDetailForEach class implements an application that
* Illustrate the access array elements using for-each statements
*/
public class CustomerDetailForEach {
public static void main(String[] args) {
String[] custName = new String[5]; ; // create array
custName[0] = "Aaron"; //assign values
custName[1] = "Kavin";
custName[2] = "Jesicca";
custName[3] = "Rishabh";
custName[4] = "Vinitha";

17 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Single Dimensional Array

System.out.println("************CUSTOMER DETAIL***********"); Output:


for(String name : custName) { ************CUSTOMER DETAIL***********
System.out.println(name); Aaron
} Kavin
} Jesicca
} Rishabh
Vinitha

18 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array

• In general, more than one dimension refer to the multi dimensional array. Its is array of arrays. The
retrieve and processing like single dimensional array.

• Declaration and Instantiation


• Two-Dimensional Array: In the form of matrix which represents collection of rows and columns.

Syntax:

DataType[][] ArrayName = new int[RowSize][ColumnSize];

int bookCount[][] = new int[3][3];


• Three Dimensional Array: In the form of table and each table contains number of rows and columns.

Syntax:
DataType[][][] ArrayName = new int[TableSize][RowSize][ColumnSize];
int bookCount[][][]= new int[3][3][3];
19 Arrays & Functions | © SmartCliff | Internal | Version 1.0
Arrays

Multi Dimensional Array

Need for Multi-dimensional Array:

• Data is stored in the form of table or matrix form. It is used to represents the data in different

dimension like row and column wise.

• It is used to represents Graph and database like data structure.

• Specifically used to find minimum spanning tree and connectivity checking between nodes.

20 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array

/** Output:
* The ArrayDemo3 class implements an application that illustrate the access of multidimensional 12
array elements */ 34
Class ArrayDemo3{ 56
public static void main(String[] args){
int [][] x = new int[][] {{1,2},{3,4},{5,6}}; // initialize values
for(int i=0; i < x.length; i++) {
// print array elements
for (int j=0; j < x[i].length; j++) {
System.out.print(x[i][j]);
}
System.out.println();
}
}
}
21 Arrays & Functions | © SmartCliff | Internal | Version 1.0
Arrays

Multi Dimensional Array

/**
* The MovieSeat class implements an application that illustrate the access of multidimensional array elements */
public class MovieSeat {
public static void main(String[] args){
String [][] seatType = new String[][] {{"B","B","A","A","A"},{"A","A","A","B","B"},{"A","B","B","B","B"},{"B","A","A","B","A"}};
int vipcount = 0, premiumcount = 0, regularcount = 0, viptotal = 5, premiumtotal = 10, regulartotal = 5;
System.out.println("--MOVIE SEAT ARRANGEMENT--");
for(int i=0; i < seatType.length; i++) {
if (i==0)
System.out.println("--------VIP SEATS--------");
else if(i==1)
System.out.println("------PREMIUM SEATS------");
else if(i==3)
System.out.println("------REGULAR SEATS------");

22 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array

for (int j=0; j < seatType[i].length; j++) {


System.out.print(" "+seatType[i][j]+" ");
if(i==0 && seatType[i][j].equalsIgnoreCase("B"))
vipcount++;
else if(i>0 && i<3 && seatType[i][j].equalsIgnoreCase("B"))
premiumcount++;
else if(i==3 && seatType[i][j].equalsIgnoreCase("B"))
regularcount++;
}
System.out.println();
}
System.out.println("----SEAT BOOKED DETAIL----");
System.out.println("--------VIP SEATS--------");
System.out.println("BOOKED : "+vipcount+" AVAILABLE : "+(viptotal-vipcount)+" TOTAL : "+viptotal);

23 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array

System.out.println("-----PREMIUM SEATS-----"); Output:


System.out.println("BOOKED : "+premiumcount+" AVAILABLE : "+(premiumtotal- --MOVIE SEAT ARRANGEMENT--
--------VIP SEATS--------
premiumcount)+" TOTAL : "+premiumtotal); B B A A A
System.out.println("-----REGULAR SEATS-----"); ------PREMIUM SEATS------
A A A B B
System.out.println("BOOKED : "+regularcount+" AVAILABLE : "+(regulartotal-
A B B B B
regularcount)+" TOTAL : "+regulartotal); ------REGULAR SEATS------
} B A A B A
----SEAT BOOKED DETAIL----
} --------VIP SEATS--------
BOOKED : 2 AVAILABLE : 3 TOTAL : 5
-----PREMIUM SEATS-----
BOOKED : 6 AVAILABLE : 4 TOTAL : 10
-----REGULAR SEATS-----
BOOKED : 2 AVAILABLE : 3 TOTAL : 5

24 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array : Jagged Array

• Java supports jagged array. It is array of arrays with different number of columns.

• Declaration and Instantiation

• Jagged Array: In the form of matrix which represents fixed number of rows and different size
columns.

Syntax:
DataType[][] Array_Name = new int[Row_Size][];
int bookNo[][] = new int[3][]; //variable size column
//adding column
bookNo[0] = new int[3]; //0th row contains 3 columns
bookNo[1] = new int[5]; //1st row contains 5 columns
bookNo[2] = new int[1]; //2nd row contains 1 column

25 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array : Jagged Array

Need for Jagged Array:

• It improves the performance when working with multi-dimensional arrays.

• In a jagged array, which is an array of arrays, each inner array can be of a different size. It helps the

efficient memory management.

• For example:

• Course registration count based on different category.

• Ticket reservation details based on different category. Etc.

26 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array : Jagged Array

/**
* The JaggedArray class implements an application that
* Illustrate the jagged array
*/
public class JaggedArray {
public static void main(String[] args) {
int bookNo[][] = new int[3][];
bookNo[0] = new int[] {1,2,3};
bookNo[1] = new int[] {4,5};
bookNo[2] = new int[] {6,7,8,9,10};
System.out.println("Two Dimensional Jagged Array");

27 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array : Jagged Array

for(int i=0;i<bookNo.length;i++) { Output:

for(int j=0;j<bookNo[i].length;j++) {
Two Dimensional Jagged Array
1
System.out.println(bookNo[i][j]+" "); 2
} 3
System.out.println();
4
} 5
}
}
6
7
8
9
10

28 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array

/**
* The MovieSeat class implements an application that illustrate the access of multidimensional array elements */
public class MovieSeatJaggedArray {
public static void main(String[] args){
String [][] seatType = new String[][] {{"B","A","A"},{"A","A","A","B","B"},{"A","B","B","B","B"},{"B","A","A","A"}};
int vipcount = 0, premiumcount = 0, regularcount = 0, viptotal = 5, premiumtotal = 10, regulartotal = 5;
System.out.println("--MOVIE SEAT ARRANGEMENT--");
for(int i=0; i < seatType.length; i++) {
if (i==0)
System.out.println("--------VIP SEATS--------");
else if(i==1)
System.out.println("------PREMIUM SEATS------");
else if(i==3)
System.out.println("------REGULAR SEATS------");

29 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array

for (int j=0; j < seatType[i].length; j++) {


System.out.print(" "+seatType[i][j]+" ");
if(i==0 && seatType[i][j].equalsIgnoreCase("B"))
vipcount++;
else if(i>0 && i<3 && seatType[i][j].equalsIgnoreCase("B"))
premiumcount++;
else if(i==3 && seatType[i][j].equalsIgnoreCase("B"))
regularcount++;
}
System.out.println();
}
System.out.println("----SEAT BOOKED DETAIL----");
System.out.println("--------VIP SEATS--------");
System.out.println("BOOKED : "+vipcount+" AVAILABLE : "+(viptotal-vipcount)+" TOTAL : "+viptotal);

30 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Multi Dimensional Array

System.out.println("-----PREMIUM SEATS-----"); Output:


System.out.println("BOOKED : "+premiumcount+" AVAILABLE : "+(premiumtotal- --MOVIE SEAT ARRANGEMENT--
--------VIP SEATS--------
premiumcount)+" TOTAL : "+premiumtotal); B A A
System.out.println("-----REGULAR SEATS-----"); ------PREMIUM SEATS------
A A A B B
System.out.println("BOOKED : "+regularcount+" AVAILABLE : "+(regulartotal-
A B B B B
regularcount)+" TOTAL : "+regulartotal); ------REGULAR SEATS------
} B A A A
----SEAT BOOKED DETAIL----
} --------VIP SEATS--------
BOOKED : 1 AVAILABLE : 2 TOTAL : 3
-----PREMIUM SEATS-----
BOOKED : 6 AVAILABLE : 4 TOTAL : 10
-----REGULAR SEATS-----
BOOKED : 1 AVAILABLE : 3 TOTAL : 4

31 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Quiz

1. Which of the following is FALSE about Java array?

b) Length of array can be


a) A java array is always an
changed after the creation of
object
array

c) Arrays in Java are always d) Array is the example for


allocated on heap Non-Primitive type

b) Length of array can be changed


after the creation of array

32 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Quiz

2. In java array supports,

a) Primitive type only b) Object type only

c) Both d) None of these above

C) Both

33 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Arrays

Quiz

3. Java supports variable size column in multidimensional array

a) Yes b) No

a) Yes

34 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Please download pictures in


suitable size here and insert them
by clicking the symbol above.

35 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Contents

• Introduction

• Function elements

• Quiz

36 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Introduction

• A function/Method is a block of code which perform specific task and the task is executed when the

function is invoked or called.

• Primary uses of functions:

–It allows code reusability (define once and use multiple times)

–You can break a complex program into smaller chunks of code

–Reducing duplication of code

–Make program shorter and increases code readability

37 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Types

• There are two types of functions:

– Built-in function: Java has several functions that are readily available for use. In Java, every built-
in function should be part of some class.

– User defined function: Function created by user based on the need of application.

• With methods (functions), there are 2 major points of view

– Builder of the method - responsible for creating the declaration and the definition of the method (i.e.
how it works)

– Caller - somebody (i.e. some portion of code) that uses the method to perform a task

38 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Function Elements

• There are two important elements of function:

1. Function Definition

– It define the operation of a function. It consists of the function signature followed by the

function body. The function prototype includes function name, parameter list and return type.

2. Function Call

– It means call or invoke the specific function. When a function is invoked, the program control

jumps to the called function to execute the statements that are in the part of that function. Once

the called function is executed the program control passes back to the calling function.

39 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Function Elements

• Function Definition

Syntax:
modifier returnType methodName(parameterlists) // Function signature
{
//Function Body
}

– Modifiers / Specifiers: It defines the visibility of the method i.e. from where it can be accessible in

the application.

40 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Function Elements

•In Java, there 4 type of the access specifiers.

• public: accessible in all class in your application.

• protected: accessible within the class in which it is defined and, in its subclass,(es).

• private: accessible only within the class in which it is defined.

• default (declared/defined without using any modifier) : accessible within same class and

package within which its class is defined.

41 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Function Elements

• Function Definition

– The return type : The data type of the value returned by the method or void if does not return a
value.

– Method Name : Name of the function should specify using valid identifier

– Java Naming Convention: It is a single word that should be a verb in lowercase or multi-word,
that begins with a verb in lowercase followed by adjective or noun. After the first word, first letter of
each word should be capitalized. Example: computeAddition, setName

– Parameter list : Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().

– Method body : It is enclosed between braces. The code specifies the task to be done.
42 Arrays & Functions | © SmartCliff | Internal | Version 1.0
Functions

Function Elements

• Function Call

– Static method is invoked by the class name or using object. (Refer Example)

– Example: className.methodName(argumentList)

– Non static method is invoked by the instance/object of the class (We Will discuss later)

– Example: objectName.methodName(argumentList)

43 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Return Values

• Function return types: Function return values of any valid types. It must return data that matches
their return type.

• Example:
public int addTwoInt(int a, int b){
return a+b; // return integer
}

//void method return nothing


public void printName(String name){
System.out.println("Hello World!!!"); // return
void
}

44 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Arguments and Parameters

• Arguments and Parameters: The terms parameter and argument can be used for the same thing

information that are passed into a function.

– Arguments –An argument is a value that is passed during a function call or calling function.

– Parameters – Parameters used in the function definition or called function. A parameter is a variable

defined in the function definition or calling function.

Note:

• During program execution, the values in the actual arguments is assigned to the formal parameter.

45 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Function Elements

//Called Function Here,


a & b is formal parameters
public int addTwoInt(int a, int b){

return a+b; //Function Body

//Calling Function

public static void main (String[] args){

int sum; Function Call


Here,
sum=addTwoInt(5,6); 5 & 6 is actual arguments

System.out.println(“Sum of two integer values :"+ sum);


}

46 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Function Elements

/** Output:
* The MethodDeclareDemo class implements an application that Sum of two integer
* Illustrate the user defined methods(static) */
values :11
class MethodDeclareDemo{
//User Defined Method
public int static addTwoInt(int a, int b){ //a, b is parameters
return a+b;
}
public static void main (String[] args){
int sum;
sum=addTwoInt(5,6); //5, 6 is arguments
System.out.println(“Sum of two integer values :"+ sum);
}
}
47 Arrays & Functions | © SmartCliff | Internal | Version 1.0
Functions

Function Elements

/**
* The FunctionDeclare class implements an application that display the Movie details
* using the user defined methods(static) */
public class FunctionDeclare {
static void getMovieDetail(String moviename,String moviedescription,int movieduration,String movielanguage,
String moviereleasedate,String moviecountry,String moviegenre) {
System.out.println("Movie Title : "+moviename);
System.out.println("Movie Description : "+moviedescription);
System.out.println("Movie Duration : "+movieduration);
System.out.println("Movie Language : "+movielanguage);
System.out.println("Movie Release Date : "+moviereleasedate);
System.out.println("Movie Country : "+moviecountry);
System.out.println("Movie Genre : "+moviegenre);
}
48 Arrays & Functions | © SmartCliff | Internal | Version 1.0
Functions

Function Elements

public static void main(String[] args) {


String moviename = "AAA";
String moviedescription = "Dramaof1945";
int movieduration = 3;
String movielanguage = "English";
String moviereleasedate = "25/03/2022";
String moviecountry = "XYZ";
String moviegenre = "THRILLER";
System.out.println("-------Movie Detail-------");
getMovieDetail(moviename, moviedescription, movieduration, movielanguage, moviereleasedate,
moviecountry, moviegenre);
System.out.println("---------------------------");
} }
49 Arrays & Functions | © SmartCliff | Internal | Version 1.0
Functions

Function Elements

Output:
-------Movie Detail-------
Movie Title : AAA
Movie Description : Dramaof1945
Movie Duration : 3
Movie Language : English
Movie Release Date : 25/03/2022
Movie Country : XYZ
Movie Genre : THRILLER
---------------------------

50 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Quiz

1. Java method signature is a combination of ___.

a)returnType b) methodName

c) Argumentlist d) All the above

d) All the above

51 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Quiz

2. What the naming convention should be for Methods in Java?

b) If name contains many words


a) It should start with then first word's letter start with
lowercase letter. lowercase only and other words
will start with uppercase

c) It should be a verb such


d) All the above
as show(), count(), describe()

d) All the above

52 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Functions

Quiz

3. Which is not an advantage of the function?

a) Re-usability b) Makes problem simple to


solve

d) Easy to Understand the


c) Efficiency
Solution

c) Efficiency

53 Arrays & Functions | © SmartCliff | Internal | Version 1.0


Proper Preparation
Prevents
Poor Performance
- Charlie Batch

54 Arrays & Functions | © SmartCliff | Internal | Version 1.0


THANK YOU

You might also like