SlideShare a Scribd company logo
IntroductionJava Programming - Math Class
Standard Classes and Methods:
The Math Class: Java Math class provides several
methods to work on math calculations
Fundamentals of Java 2
Table 4-1: Seven methods in the Math class
Standard Classes and Methods: The
Math Class (cont.)
• Using sqrt() method example:
Fundamentals of Java 3
Standard Classes and Methods: The
Math Class (cont.)
Fundamentals of Java 4
 Math class methods example:
Standard Classes and Methods: The
Random Class
• Random number generator: Returns numbers
chosen at random from a pre-designated interval
Fundamentals of Java 5
Table 4-2: Methods in the Random class
Java Methods
6
Defining Methods
7
Defining Methods
8
A method is a collection of statements that are
grouped together to perform an operation.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
Defining Methods
9
A method is a collection of statements that are
grouped together to perform an operation.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
Method Signature
10
Method signature is the combination of the method name and the
parameter list.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
Formal Parameters
11
The variables defined in the method header are known as
formal parameters.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
Actual Parameters
12
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
Return Value Type
13
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
Calling Methods
14
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
pass the value of i
pass the value of j
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The max
method can be invoked from any class besides TestMax. If
you create a new class Test, you can invoke the static method
max using ClassName.methodName (e.g., TestMax.max).
15
void Method Example
16
Passing Parameters
17
Pass by Value
18
When you invoke a method with an
argument, the value of the argument is
passed to the parameter. This is referred to
as pass-by-value. If the argument is a
variable rather than a literal value, the value
of the variable is passed to the parameter.
The variable is not affected, regardless of
the changes made to the parameter inside
the method
Pass by Value
19
Overloading Methods
• Overloading methods enables you to define the methods with the
same name as long as their signatures are different.
• The max method that was used earlier works only with the int
data type. But what if you need to determine which of two
floating-point numbers has the maximum value? The solution
is to create another method with the same name but different
parameters, as shown in the following code:
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
20
Ambiguous Invocation
• The Java compiler determines which method to use
based on the method signature.
• Sometimes there may be two or more possible matches
for an invocation of a method, but the compiler cannot
determine the most specific match. This is referred to as
ambiguous invocation. Ambiguous invocation is a
compile error.
21
Ambiguous Invocation
22
Scope of Local Variables
A local variable: a variable defined inside a
method.
Scope: the part of the program where the
variable can be referenced.
The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable. A local
variable must be declared before it can be
used.
23
Scope of Local Variables, cont.
You can declare a local variable with the
same name multiple times in different non-
nesting blocks in a method, but you cannot
declare a local variable twice in nested
blocks.
24
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop
header has its scope in the entire loop. But a variable
declared inside a for loop body has its scope limited in the
loop body from its declaration and to the end of the block
that contains the variable.
25
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
The scope of j
The scope of i
Scope of Local Variables, cont.
26
public static void method1() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
x += i;
}
for (int i = 1; i < 10; i++) {
y += i;
}
}
It is fine to declare i in two
non-nesting blocks
public static void method2() {
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
sum += i;
}
}
It is wrong to declare i in
two nesting blocks
Benefits of Methods
27
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
Arrays
• An array is an ordered list of values
28
0 1 2 3 4 5 6 7 8 9
79 87 94 82 67 98 87 81 74 91
An array of size N is indexed from zero to N-1
scores
The entire array
has a single name
Each value has a numeric index
This array holds 10 values that are indexed from 0 to 9
Arrays
• A particular value in an array is referenced using the array name
followed by the index in brackets
• For example, the expression
scores[2]
refers to the value 94 (the 3rd value in the array)
• That expression represents a place to store a single integer and can be
used wherever an integer variable can be used
29
Arrays
• For example, an array element can be assigned a value, printed, or
used in a calculation:
scores[2] = 89;
scores[first] = scores[first] + 2;
mean = (scores[0] + scores[1])/2;
System.out.println ("Top = " + scores[5]);
30
Arrays
• The values held in an array are called array elements
• An array stores multiple values of the same type (the element
type)
• The element type can be a primitive type or an object reference
• Therefore, we can create an array of integers, or an array of
characters, or an array of String objects, etc.
• In Java, the array itself is an object
• Therefore the name of the array is a object reference variable, and
the array itself must be instantiated
31
Declaring Arrays
• The scores array could be declared as follows:
int[] scores = new int[10];
• The type of the variable scores is int[] (an array of integers)
• Note that the type of the array does not specify its size, but each
object of that type has a specific size
• The reference variable scores is set to a new array object that can
hold 10 integers
32
Declaring Arrays
• Some examples of array declarations:
float[] prices = new float[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
33
Bounds Checking
• Once an array is created, it has a fixed size
• An index used in an array reference must specify a valid element
• That is, the index value must be in bounds (0 to N-1)
• The Java interpreter throws an
ArrayIndexOutOfBoundsException if an array index is out
of bounds
• This is called automatic bounds checking
34
Bounds Checking
• For example, if the array codes can hold 100 values, it can be
indexed using only the numbers 0 to 99
• If count has the value 100, then the following reference will cause
an exception to be thrown:
System.out.println (codes[count]);
• It’s common to introduce off-by-one errors when using arrays
35
for (int index=0; index <= 100; index++)
codes[index] = index*50 + epsilon;
problem
Bounds Checking
• Each array object has a public constant called length that stores the
size of the array
• It is referenced using the array name:
scores.length
• Note that length holds the number of elements, not the largest
index
36
Alternate Array Syntax
• The brackets of the array type can be associated with the element
type or with the name of the array
• Therefore the following declarations are equivalent:
float[] prices;
float prices[];
• The first format generally is more readable
37
Initializer Lists
• An initializer list can be used to instantiate and initialize an array in
one step
• The values are delimited by braces and separated by commas
• Examples:
int[] units = {147, 323, 89, 933, 540,
269, 97, 114, 298, 476};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
38
Initializer Lists
• Note that when an initializer list is used:
• the new operator is not used
• no size value is specified
• The size of the array is determined by the number of items in the
initializer list
• An initializer list can only be used only in the array declaration
39
Arrays as Parameters
• An entire array can be passed as a parameter to a method
• Like any other object, the reference to the array is passed, making the
formal and actual parameters aliases of each other
• Changing an array element within the method changes the original
• An array element can be passed to a method as well, and follows the
parameter passing rules of that element's type
40
Arrays of Objects
• The elements of an array can be object references
• The following declaration reserves space to store 53 references to
String objects
String[] words = new String[53];
• It does NOT create the String objects themselves
• Each object stored in an array must be instantiated separately
41
Command-Line Arguments
• The signature of the main method indicates that it takes an array of
String objects as a parameter
• These values come from command-line arguments that are provided
when the interpreter is invoked
• For example, the following invocation of the interpreter passes an
array of three String objects into main:
> java delhi colcutta jaipur bangalore
• These strings are stored at indexes 0-3 of the parameter
42
Arrays of Objects
• Objects can have arrays as instance variables
• Many useful structures can be created with arrays and objects
• The software designer must determine carefully an organization of
data and objects that makes sense for the situation
43
IntroductionJava Programming - Math Class
Two-Dimensional Arrays
• A one-dimensional array stores a list of elements
• A two-dimensional array can be thought of as a table
of elements, with rows and columns
45
one
dimension
two
dimensions
Two-Dimensional Arrays
• To be precise, a two-dimensional array in Java is an
array of arrays
• A two-dimensional array is declared by specifying the
size of each dimension separately:
int[][] scores = new int[12][50];
• A two-dimensional array element is referenced using
two index values
value = scores[3][6]
• The array stored in one row or column can be
specified using one index
46
Two-Dimensional Arrays
Expression Type Description
scores int[][] 2D array of integers, or
array of integer arrays
scores[5] int[] array of integers
scores[5][12] int integer
47
Multidimensional Arrays
• An array can have many dimensions
• If it has more than one dimension, it is called a multidimensional array
• Each dimension subdivides the previous one into the specified number
of elements
• Each array dimension has its own length constant
• Because each dimension is an array of array references, the arrays
within one dimension can be of different lengths
• these are sometimes called ragged arrays
48
49
Ad

More Related Content

Similar to IntroductionJava Programming - Math Class (20)

Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 
Array assignment
Array assignmentArray assignment
Array assignment
Ahmad Kamal
 
For Beginners - C#
For Beginners - C#For Beginners - C#
For Beginners - C#
Snehal Harawande
 
6 arrays injava
6 arrays injava6 arrays injava
6 arrays injava
irdginfo
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
worldchannel
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptx
MaheenVohra
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
Liza Abello
 
Building Java Programas
Building Java ProgramasBuilding Java Programas
Building Java Programas
ssuser4df5ef
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
Mohammed Khan
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
chandrasekar529044
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ansariparveen06
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
AqeelAbbas94
 
array Details
array Detailsarray Details
array Details
shivas379526
 
14method in c#
14method in c#14method in c#
14method in c#
Sireesh K
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
Delegate
DelegateDelegate
Delegate
abhay singh
 
Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
Ain-ul-Moiz Khawaja
 

More from sandhyakiran10 (18)

email marketing in digital marketing platform
email marketing in digital marketing platformemail marketing in digital marketing platform
email marketing in digital marketing platform
sandhyakiran10
 
SEO_ Types_ and_ Ethics_Presentation.pptx
SEO_ Types_ and_ Ethics_Presentation.pptxSEO_ Types_ and_ Ethics_Presentation.pptx
SEO_ Types_ and_ Ethics_Presentation.pptx
sandhyakiran10
 
Google adwords and AdSense in digital Marketing
Google adwords and AdSense in digital MarketingGoogle adwords and AdSense in digital Marketing
Google adwords and AdSense in digital Marketing
sandhyakiran10
 
search engine optimisation techniques and types
search engine optimisation techniques and typessearch engine optimisation techniques and types
search engine optimisation techniques and types
sandhyakiran10
 
content marketing in - digital marketing
content marketing in - digital marketingcontent marketing in - digital marketing
content marketing in - digital marketing
sandhyakiran10
 
The five generatios of computers-history
The five generatios of computers-historyThe five generatios of computers-history
The five generatios of computers-history
sandhyakiran10
 
Application Layer protocols- OSI Model Layers
Application Layer protocols- OSI Model LayersApplication Layer protocols- OSI Model Layers
Application Layer protocols- OSI Model Layers
sandhyakiran10
 
Cellular Networks - concepts, technology
Cellular Networks - concepts, technologyCellular Networks - concepts, technology
Cellular Networks - concepts, technology
sandhyakiran10
 
OSI Model - transport Layer protocols
OSI Model   -  transport Layer protocolsOSI Model   -  transport Layer protocols
OSI Model - transport Layer protocols
sandhyakiran10
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
sandhyakiran10
 
Chapter_1_Business_Information_Systems.ppt
Chapter_1_Business_Information_Systems.pptChapter_1_Business_Information_Systems.ppt
Chapter_1_Business_Information_Systems.ppt
sandhyakiran10
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
OSI model - physical layer,Transmission medium, switching mechanisms, multipl...
OSI model - physical layer,Transmission medium, switching mechanisms, multipl...OSI model - physical layer,Transmission medium, switching mechanisms, multipl...
OSI model - physical layer,Transmission medium, switching mechanisms, multipl...
sandhyakiran10
 
java - Introduction , control structures
java - Introduction , control structuresjava - Introduction , control structures
java - Introduction , control structures
sandhyakiran10
 
Database Management system, database architecture unikkkkkkkkkkkkkkk
Database Management system, database architecture unikkkkkkkkkkkkkkkDatabase Management system, database architecture unikkkkkkkkkkkkkkk
Database Management system, database architecture unikkkkkkkkkkkkkkk
sandhyakiran10
 
High level data link control and point to point protocol
High level data link control and point to point protocolHigh level data link control and point to point protocol
High level data link control and point to point protocol
sandhyakiran10
 
Software Development Life Cycle (SDLC).pptx
Software Development Life Cycle (SDLC).pptxSoftware Development Life Cycle (SDLC).pptx
Software Development Life Cycle (SDLC).pptx
sandhyakiran10
 
Data Communication.pptx
Data Communication.pptxData Communication.pptx
Data Communication.pptx
sandhyakiran10
 
email marketing in digital marketing platform
email marketing in digital marketing platformemail marketing in digital marketing platform
email marketing in digital marketing platform
sandhyakiran10
 
SEO_ Types_ and_ Ethics_Presentation.pptx
SEO_ Types_ and_ Ethics_Presentation.pptxSEO_ Types_ and_ Ethics_Presentation.pptx
SEO_ Types_ and_ Ethics_Presentation.pptx
sandhyakiran10
 
Google adwords and AdSense in digital Marketing
Google adwords and AdSense in digital MarketingGoogle adwords and AdSense in digital Marketing
Google adwords and AdSense in digital Marketing
sandhyakiran10
 
search engine optimisation techniques and types
search engine optimisation techniques and typessearch engine optimisation techniques and types
search engine optimisation techniques and types
sandhyakiran10
 
content marketing in - digital marketing
content marketing in - digital marketingcontent marketing in - digital marketing
content marketing in - digital marketing
sandhyakiran10
 
The five generatios of computers-history
The five generatios of computers-historyThe five generatios of computers-history
The five generatios of computers-history
sandhyakiran10
 
Application Layer protocols- OSI Model Layers
Application Layer protocols- OSI Model LayersApplication Layer protocols- OSI Model Layers
Application Layer protocols- OSI Model Layers
sandhyakiran10
 
Cellular Networks - concepts, technology
Cellular Networks - concepts, technologyCellular Networks - concepts, technology
Cellular Networks - concepts, technology
sandhyakiran10
 
OSI Model - transport Layer protocols
OSI Model   -  transport Layer protocolsOSI Model   -  transport Layer protocols
OSI Model - transport Layer protocols
sandhyakiran10
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
sandhyakiran10
 
Chapter_1_Business_Information_Systems.ppt
Chapter_1_Business_Information_Systems.pptChapter_1_Business_Information_Systems.ppt
Chapter_1_Business_Information_Systems.ppt
sandhyakiran10
 
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
8.-OBJECT-ORIENTED-PROGRAMMING-USING-JAVA-Multithreading.pptx
sandhyakiran10
 
OSI model - physical layer,Transmission medium, switching mechanisms, multipl...
OSI model - physical layer,Transmission medium, switching mechanisms, multipl...OSI model - physical layer,Transmission medium, switching mechanisms, multipl...
OSI model - physical layer,Transmission medium, switching mechanisms, multipl...
sandhyakiran10
 
java - Introduction , control structures
java - Introduction , control structuresjava - Introduction , control structures
java - Introduction , control structures
sandhyakiran10
 
Database Management system, database architecture unikkkkkkkkkkkkkkk
Database Management system, database architecture unikkkkkkkkkkkkkkkDatabase Management system, database architecture unikkkkkkkkkkkkkkk
Database Management system, database architecture unikkkkkkkkkkkkkkk
sandhyakiran10
 
High level data link control and point to point protocol
High level data link control and point to point protocolHigh level data link control and point to point protocol
High level data link control and point to point protocol
sandhyakiran10
 
Software Development Life Cycle (SDLC).pptx
Software Development Life Cycle (SDLC).pptxSoftware Development Life Cycle (SDLC).pptx
Software Development Life Cycle (SDLC).pptx
sandhyakiran10
 
Data Communication.pptx
Data Communication.pptxData Communication.pptx
Data Communication.pptx
sandhyakiran10
 
Ad

Recently uploaded (20)

Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Ad

IntroductionJava Programming - Math Class

  • 2. Standard Classes and Methods: The Math Class: Java Math class provides several methods to work on math calculations Fundamentals of Java 2 Table 4-1: Seven methods in the Math class
  • 3. Standard Classes and Methods: The Math Class (cont.) • Using sqrt() method example: Fundamentals of Java 3
  • 4. Standard Classes and Methods: The Math Class (cont.) Fundamentals of Java 4  Math class methods example:
  • 5. Standard Classes and Methods: The Random Class • Random number generator: Returns numbers chosen at random from a pre-designated interval Fundamentals of Java 5 Table 4-2: Methods in the Random class
  • 8. Defining Methods 8 A method is a collection of statements that are grouped together to perform an operation. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } Define a method Invoke a method int z = max(x, y); actual parameters (arguments)
  • 9. Defining Methods 9 A method is a collection of statements that are grouped together to perform an operation. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 10. Method Signature 10 Method signature is the combination of the method name and the parameter list. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 11. Formal Parameters 11 The variables defined in the method header are known as formal parameters. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 12. Actual Parameters 12 When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 13. Return Value Type 13 A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 14. Calling Methods 14 public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println( "The maximum between " + i + " and " + j + " is " + k); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } pass the value of i pass the value of j
  • 15. Reuse Methods from Other Classes NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the static method max using ClassName.methodName (e.g., TestMax.max). 15
  • 18. Pass by Value 18 When you invoke a method with an argument, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method
  • 20. Overloading Methods • Overloading methods enables you to define the methods with the same name as long as their signatures are different. • The max method that was used earlier works only with the int data type. But what if you need to determine which of two floating-point numbers has the maximum value? The solution is to create another method with the same name but different parameters, as shown in the following code: public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } 20
  • 21. Ambiguous Invocation • The Java compiler determines which method to use based on the method signature. • Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compile error. 21
  • 23. Scope of Local Variables A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. 23
  • 24. Scope of Local Variables, cont. You can declare a local variable with the same name multiple times in different non- nesting blocks in a method, but you cannot declare a local variable twice in nested blocks. 24
  • 25. Scope of Local Variables, cont. A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable. 25 public static void method1() { . . for (int i = 1; i < 10; i++) { . . int j; . . . } } The scope of j The scope of i
  • 26. Scope of Local Variables, cont. 26 public static void method1() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { x += i; } for (int i = 1; i < 10; i++) { y += i; } } It is fine to declare i in two non-nesting blocks public static void method2() { int i = 1; int sum = 0; for (int i = 1; i < 10; i++) { sum += i; } } It is wrong to declare i in two nesting blocks
  • 27. Benefits of Methods 27 • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity.
  • 28. Arrays • An array is an ordered list of values 28 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9
  • 29. Arrays • A particular value in an array is referenced using the array name followed by the index in brackets • For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) • That expression represents a place to store a single integer and can be used wherever an integer variable can be used 29
  • 30. Arrays • For example, an array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); 30
  • 31. Arrays • The values held in an array are called array elements • An array stores multiple values of the same type (the element type) • The element type can be a primitive type or an object reference • Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. • In Java, the array itself is an object • Therefore the name of the array is a object reference variable, and the array itself must be instantiated 31
  • 32. Declaring Arrays • The scores array could be declared as follows: int[] scores = new int[10]; • The type of the variable scores is int[] (an array of integers) • Note that the type of the array does not specify its size, but each object of that type has a specific size • The reference variable scores is set to a new array object that can hold 10 integers 32
  • 33. Declaring Arrays • Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; 33
  • 34. Bounds Checking • Once an array is created, it has a fixed size • An index used in an array reference must specify a valid element • That is, the index value must be in bounds (0 to N-1) • The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds • This is called automatic bounds checking 34
  • 35. Bounds Checking • For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 • If count has the value 100, then the following reference will cause an exception to be thrown: System.out.println (codes[count]); • It’s common to introduce off-by-one errors when using arrays 35 for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem
  • 36. Bounds Checking • Each array object has a public constant called length that stores the size of the array • It is referenced using the array name: scores.length • Note that length holds the number of elements, not the largest index 36
  • 37. Alternate Array Syntax • The brackets of the array type can be associated with the element type or with the name of the array • Therefore the following declarations are equivalent: float[] prices; float prices[]; • The first format generally is more readable 37
  • 38. Initializer Lists • An initializer list can be used to instantiate and initialize an array in one step • The values are delimited by braces and separated by commas • Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'}; 38
  • 39. Initializer Lists • Note that when an initializer list is used: • the new operator is not used • no size value is specified • The size of the array is determined by the number of items in the initializer list • An initializer list can only be used only in the array declaration 39
  • 40. Arrays as Parameters • An entire array can be passed as a parameter to a method • Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other • Changing an array element within the method changes the original • An array element can be passed to a method as well, and follows the parameter passing rules of that element's type 40
  • 41. Arrays of Objects • The elements of an array can be object references • The following declaration reserves space to store 53 references to String objects String[] words = new String[53]; • It does NOT create the String objects themselves • Each object stored in an array must be instantiated separately 41
  • 42. Command-Line Arguments • The signature of the main method indicates that it takes an array of String objects as a parameter • These values come from command-line arguments that are provided when the interpreter is invoked • For example, the following invocation of the interpreter passes an array of three String objects into main: > java delhi colcutta jaipur bangalore • These strings are stored at indexes 0-3 of the parameter 42
  • 43. Arrays of Objects • Objects can have arrays as instance variables • Many useful structures can be created with arrays and objects • The software designer must determine carefully an organization of data and objects that makes sense for the situation 43
  • 45. Two-Dimensional Arrays • A one-dimensional array stores a list of elements • A two-dimensional array can be thought of as a table of elements, with rows and columns 45 one dimension two dimensions
  • 46. Two-Dimensional Arrays • To be precise, a two-dimensional array in Java is an array of arrays • A two-dimensional array is declared by specifying the size of each dimension separately: int[][] scores = new int[12][50]; • A two-dimensional array element is referenced using two index values value = scores[3][6] • The array stored in one row or column can be specified using one index 46
  • 47. Two-Dimensional Arrays Expression Type Description scores int[][] 2D array of integers, or array of integer arrays scores[5] int[] array of integers scores[5][12] int integer 47
  • 48. Multidimensional Arrays • An array can have many dimensions • If it has more than one dimension, it is called a multidimensional array • Each dimension subdivides the previous one into the specified number of elements • Each array dimension has its own length constant • Because each dimension is an array of array references, the arrays within one dimension can be of different lengths • these are sometimes called ragged arrays 48
  • 49. 49
  翻译: