SlideShare a Scribd company logo
https://www.facebook.com/Oxus20
oxus20@gmail.com
Java
Methods
Conditional statements
Zalmai Arman
Outline
https://www.facebook.com/Oxus20
Introduction
Creating & Calling a Method
Void Method
Passing Parameters by Values
Overloading Methods
The Scope of Variables
The Math Class
The Random Method
Method Abstraction
Introduction
» In the preceding chapters, you learned about such
methods as System.out.println,
JOptionPane.showMessageDialog,
JOptionPane.showInputDialog.
» A method is a collection of statements that are grouped
together to perform an operation.
» When you call the System.out.println method, for
example, the system actually executes several statements
in order to display a message.
https://www.facebook.com/Oxus20
Creating a Method
» In general, a method has the following syntax:
modifier returnValueType methodName(list of parameters)
{
// Method body;
}
» Let's take a look at a method created to find which of two
integers is bigger.This method, named max, has two int
parameters, num1 and num2, the larger of which is
returned by the method.
https://www.facebook.com/Oxus20
Creating & Calling Method
https://www.facebook.com/Oxus20
Output will be: the result of max methd is 45
Creating a Method
» A method declaration consists of a method header and a
method body.
https://www.facebook.com/Oxus20
Method Header
Method Body
Modifier return value type method name formal parameter
Creating a Method
» The method header specifies the modifiers, return value type,
method name, and parameters of the method.The modifier, which
is optional, tells the compiler how to call the method.The
static modifier is used for all the methods in this chapter.The
reason for using it will be discussed in "Objects and Classes.“.
» A method may return a value.The returnValueType is the data
type of the value the method returns. Some methods perform
the desired operations without returning a value. In this case,
the returnValueType is the keyword void. For example, the
returnValueType in the main method is void, as well as in
System.exit, System.out.println, and
JOptionPane.showMessageDialog.The method that returns a
value is called a nonvoid method, and the method that does
not return a value is called a void method.
https://www.facebook.com/Oxus20
Creating a Method
» The variables defined in the method header are known as
formal parameters or simply parameters.
» When a method is invoked, you pass a value to the
parameter.This value is referred to as actual parameter or
argument.
» The parameter list refers to the type, order, and number
of the parameters of a method.The method name and the
parameter list together constitute the method signature.
Parameters are optional; that is, a method may contain no
parameters.
https://www.facebook.com/Oxus20
Void Method
» The preceding section gives an example of a nonvoid
method.This section shows how to declare and invoke a
void method.
» gives a program that declares a method named grade and
invokes it to print the grade for a given score.
» The grade method is a void method. It does not return
any value.A call to a void method must be a statement.
So, it is invoked as a statement in the main method.This
statement is like any Java statement terminated with a
semicolon.
https://www.facebook.com/Oxus20
Void Method
https://www.facebook.com/Oxus20
Void Method
https://www.facebook.com/Oxus20
» A return statement is not needed for a void method, but it
can be used for terminating the method and returning to
the method's caller.The syntax is simply:
return;
Passing Parameters by Values
https://www.facebook.com/Oxus20
» The power of a method is its ability to work with
parameters.
» You can use println to print any string and max to find the
maximum between any two int values.
» When calling a method, you need to provide arguments,
which must be given in the same order as their respective
parameters in the method specification.This is known as
parameter order association.
» For example, the following method prints a message n
times:
Passing Parameters by Values
https://www.facebook.com/Oxus20
» You can use nPrintln(“hello", 3) to print "Hello" three times.The
nPrintln(“hello", 3) statement passes the actual string parameter,
“hello", to the parameter, message; passes 3 to n; and prints “hello"
three times. However, the statement nPrintln(3,“hello") would be
wrong.The data type of 3 does not match the data type for the first
parameter, message, nor does the second parameter,“hello", match
the second parameter, n.
Passing Parameters by Values
https://www.facebook.com/Oxus20
» The arguments must match the parameters in order,
number, and compatible type, as defined in the method
signature.
» Compatible type means that you can pass an argument to
a parameter without explicit casting, such as passing an int
value argument to a double value parameter.
» When you invoke a method with a parameter, the value of
the argument is passed to the parameter.This is referred
to as pass-by-value.
Passing Parameters by Values
https://www.facebook.com/Oxus20
» Swap is a program that demonstrates the effect of passing
by value.
» The program creates a method for swapping two
variables.
» The swap method is invoked by passing two arguments.
Interestingly, the values of the arguments are not changed
after the method is invoked.
Passing Parameters by Values
https://www.facebook.com/Oxus20
Passing Parameters by Values
https://www.facebook.com/Oxus20
» Before the swap method is invoked, num1 is 1 and num2
is 2.
» After the swap method is invoked, num1 is still 1 and
num2 is still 2.Their values are not swapped after the
swap method is invoked.
» the values of the arguments num1 and num2 are passed to
n1 and n2, but n1 and n2 have their own memory
locations independent of num1 and num2.
» Therefore, changes in n1 and n2 do not affect the contents
of num1 and num2.
Overloading Method
https://www.facebook.com/Oxus20
» The max method that was used earlier works only with
the int data type.
» But what if you need to find 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;
}
Overloading Method
https://www.facebook.com/Oxus20
» If you call max with int parameters, the max method that
expects int parameters will be invoked;
» if you call max with double parameters, the max method
that expects double parameters will be invoked.
» This is referred to as method overloading; that is, two
methods have the same name but different parameter lists
within one class.
» Next page program that creates three methods.The first
finds the maximum integer, the second finds the
maximum double, and the third finds the maximum
among three double values.All three methods are named
max.
Overloading Method
https://www.facebook.com/Oxus20
Overloading Method
https://www.facebook.com/Oxus20
» When calling max(5, 6) , the max method for finding the
maximum of two integers is invoked.
» When calling max(5.5, 6.6), the max method for finding the
maximum of two doubles is invoked.
» When calling max(10, 11.2, 12.5) , the max method for
finding the maximum of three double values is invoked.
» Can you invoke the max method with an int value and a
double value, such as max(10, 11.2,12.5)? If so, which of the
max methods is invoked?The answer to the first question is
yes.The answer to the second is that the max method for
finding the maximum of two double values is invoked.The
argument value 10 is automatically converted into a double
value and passed to this method.
Overloading Method
https://www.facebook.com/Oxus20
» Sometimes there are 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 causes a
compilation error.
Consider the following
code:
» Both max(int, double) and max(double,
int) are possible candidates to match
max(1, 2). Since neither of them is
more specific than the other, the
invocation is ambiguous, resulting in a
compilation error.
The Scope and Variables
https://www.facebook.com/Oxus20
» The scope of a variable is the part of the program where the
variable can be referenced.
» A variable defined inside a method is referred to as a local
variable.
» 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.
» A parameter is actually a local variable.The scope of a method
parameter covers the entire method.
The Scope and Variables
https://www.facebook.com/Oxus20
» 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 to the end of the block that
contains the variable.
The Scope and Variables
https://www.facebook.com/Oxus20
» 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.
The Scope and Variables
https://www.facebook.com/Oxus20
» Do not declare a variable inside a block and then attempt to use it
outside the block. Here is an example of a common mistake:
» The last statement would cause a syntax error because variable i is
not defined outside of the for loop.
The Math Class
https://www.facebook.com/Oxus20
» The Math class contains the methods needed to perform basic
mathematical functions.
» Trigonometric Methods
public static double sin(double radians)
public static double cos(double radians)
public static double tan(double radians)
public static double asin(double radians)
public static double acos(double radians)
public static double atan(double radians)
public static double toRadians(double degree)
public static double toDegrees(double radians)
The Math Class
https://www.facebook.com/Oxus20
Examples
Math.sin(0) returns 0.0
Math.sin(Math.toRadians(270)) returns -1.0
Math.sin(Math.PI / 6) returns 0.5
Math.sin(Math.PI / 2) returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6) returns 0.866
Math.cos(Math.PI / 2) returns 0
The Math Class
https://www.facebook.com/Oxus20
Exponent Methods
» There are five methods related to exponents in the Math class:
/** Return e raised to the power of x (ex) */
public static double exp(double x)
/** Return the natural logarithm of x (ln(x) = loge(x)) */
static double log(double x)
/** Return the base 10 logarithm of x (log10(x)) */
public static double log10(double x)
/** Return a raised to the power of b (xb) */
public static double pow(double x, double b)
/** Return the square root of a () */
public static double sqrt(double x)
» Note that the parameter in the sqrt method must not be negative.
The Math Class
https://www.facebook.com/Oxus20
Examples
Math.exp(1) returns 2.71828
Math.log(Math.E) returns 1.0
Math.log10(10) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns 22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
The Math Class
https://www.facebook.com/Oxus20
The Rounding Methods
» The Math class contains five rounding methods:
/** x rounded up to its nearest integer. This integer is
* returned as a double value. */
public static double ceil(double x)
/** x is rounded down to its nearest integer. This integer is
* returned as a double value. */
public static double floor(double x)
/** x is rounded to its nearest integer. If x is equally close
* to two integers, the even one is returned as a double. */
public static double rint(double x)
/** Return (int)Math.floor(x + 0.5). */
public static int round(float x)
/** Return (long)Math.floor(x + 0.5). */
public static long round(double x)
The Math Class
https://www.facebook.com/Oxus20
Examples
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(–2.0) returns –2.0
Math.ceil(–2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns –2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3 // Returns int
Math.round(2.0) returns 2 // Returns long
Math.round(–2.0f) returns -2
Math.round(–2.6) returns -3
The Math Class
https://www.facebook.com/Oxus20
The min, max, and abs Methods
» The min and max methods are overloaded to return the minimum
and maximum numbers between two numbers (int, long, float, or
double). For example, max(3.4, 5.0) returns 5.0, and min(3, 2)
returns 2.
» The abs method is overloaded to return the absolute value of the
number (int, long, float, and double). For example,
Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 3.0
Math.min(2.5, 3.6) returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1
The Math Class
https://www.facebook.com/Oxus20
The random Method
» The Math class also has a powerful method, random, which generates a
random double value greater than or equal to 0.0 and less than 1.0 (0.0 <=
Math.random() < 1.0).
» Not all classes need a main method.The Math class and JOptionPane class
do not have main methods.These classes contain methods for other classes
to use.
The Math Class
https://www.facebook.com/Oxus20
The random Method
Method Abstraction
https://www.facebook.com/Oxus20
» The key to developing software is to apply the concept of abstraction.
» Method abstraction is achieved by separating the use of a method from
its implementation.
» The client can use a method without knowing how it is implemented.
The details of the implementation are encapsulated in the method
and hidden from the client who invokes the method.This is known as
information hiding or encapsulation.
» If you decide to change the implementation, the client program will
not be affected, provided that you do not change the method
signature.The implementation of the method is hidden from the
client in a "black box,"
Method Abstraction
https://www.facebook.com/Oxus20
» You have already used the System.out.print method to display a
string, the JOptionPane.showInputDialog method to read a
string from a dialog box, and the max method to find the
maximum number.You know how to write the code to invoke
these methods in your program, but as a user of these methods,
you are not required to know how they are implemented.
END
https://www.facebook.com/Oxus20
38

More Related Content

What's hot

Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMS
PadamNepal1
 
Functions in javascript
Functions in javascriptFunctions in javascript
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
What are variables and keywords in c++
What are variables and keywords in c++What are variables and keywords in c++
What are variables and keywords in c++
Abdul Hafeez
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
Abhilash Nair
 
String in java
String in javaString in java
Java tokens
Java tokensJava tokens
Java tokens
shalinikarunakaran1
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
Prasanna Kumar SM
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Java Tokens
Java  TokensJava  Tokens
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
Modular programming
Modular programmingModular programming
Php basics
Php basicsPhp basics
Php basics
Jamshid Hashimi
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
kunal kishore
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
How java differs from c and c++
How java differs from c and c++How java differs from c and c++
How java differs from c and c++
shalinikarunakaran1
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
Array in c#
Array in c#Array in c#
Array in c#
Prem Kumar Badri
 

What's hot (20)

Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMS
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
What are variables and keywords in c++
What are variables and keywords in c++What are variables and keywords in c++
What are variables and keywords in c++
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
 
String in java
String in javaString in java
String in java
 
Java tokens
Java tokensJava tokens
Java tokens
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Modular programming
Modular programmingModular programming
Modular programming
 
Php basics
Php basicsPhp basics
Php basics
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Interface in java
Interface in javaInterface in java
Interface in java
 
How java differs from c and c++
How java differs from c and c++How java differs from c and c++
How java differs from c and c++
 
Java program structure
Java program structureJava program structure
Java program structure
 
Array in c#
Array in c#Array in c#
Array in c#
 

Similar to Java Methods

Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement
OXUS 20
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
procedures
proceduresprocedures
procedures
Rajendran
 
Progamming Primer Polymorphism (Method Overloading) VB
Progamming Primer Polymorphism (Method Overloading) VBProgamming Primer Polymorphism (Method Overloading) VB
Progamming Primer Polymorphism (Method Overloading) VB
sunmitraeducation
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptx
MaheenVohra
 
Java execise
Java execiseJava execise
Java execise
Keneth miles
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
Md Showrov Ahmed
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
Mohamed Essam
 
Discrete structure ch 3 short question's
Discrete structure ch 3 short question'sDiscrete structure ch 3 short question's
Discrete structure ch 3 short question's
hammad463061
 
Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
Geekster
 
Mcs 021
Mcs 021Mcs 021
Mcs 021
Ujjwal Kumar
 
Essential language features
Essential language featuresEssential language features
JMeter Post-Processors
JMeter Post-ProcessorsJMeter Post-Processors
JMeter Post-Processors
Loadium
 
Effective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload VarargsEffective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload Varargs
Roshan Deniyage
 
Algorithms
AlgorithmsAlgorithms
Algorithms
Ramy F. Radwan
 
Sharbani bhattacharya VB Structures
Sharbani bhattacharya VB StructuresSharbani bhattacharya VB Structures
Sharbani bhattacharya VB Structures
Sharbani Bhattacharya
 
Php
PhpPhp
Hemajava
HemajavaHemajava
Hemajava
SangeethaSasi1
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 

Similar to Java Methods (20)

Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
procedures
proceduresprocedures
procedures
 
Progamming Primer Polymorphism (Method Overloading) VB
Progamming Primer Polymorphism (Method Overloading) VBProgamming Primer Polymorphism (Method Overloading) VB
Progamming Primer Polymorphism (Method Overloading) VB
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptx
 
Java execise
Java execiseJava execise
Java execise
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
 
Discrete structure ch 3 short question's
Discrete structure ch 3 short question'sDiscrete structure ch 3 short question's
Discrete structure ch 3 short question's
 
Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)Java Polymorphism: Types And Examples (Geekster)
Java Polymorphism: Types And Examples (Geekster)
 
Mcs 021
Mcs 021Mcs 021
Mcs 021
 
Essential language features
Essential language featuresEssential language features
Essential language features
 
JMeter Post-Processors
JMeter Post-ProcessorsJMeter Post-Processors
JMeter Post-Processors
 
Effective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload VarargsEffective Java - Design Method Signature Overload Varargs
Effective Java - Design Method Signature Overload Varargs
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Sharbani bhattacharya VB Structures
Sharbani bhattacharya VB StructuresSharbani bhattacharya VB Structures
Sharbani bhattacharya VB Structures
 
Php
PhpPhp
Php
 
Hemajava
HemajavaHemajava
Hemajava
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 

More from OXUS 20

Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
OXUS 20
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
OXUS 20
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
OXUS 20
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
OXUS 20
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
OXUS 20
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
OXUS 20
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
OXUS 20
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
OXUS 20
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
OXUS 20
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
OXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
OXUS 20
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
OXUS 20
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
OXUS 20
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
OXUS 20
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
OXUS 20
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART III
OXUS 20
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
OXUS 20
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
OXUS 20
 

More from OXUS 20 (19)

Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART III
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 

Recently uploaded

zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
YousufSait3
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 

Recently uploaded (20)

zOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL DifferenceszOS Mainframe JES2-JES3 JCL-JECL Differences
zOS Mainframe JES2-JES3 JCL-JECL Differences
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 

Java Methods

  • 2. Outline https://www.facebook.com/Oxus20 Introduction Creating & Calling a Method Void Method Passing Parameters by Values Overloading Methods The Scope of Variables The Math Class The Random Method Method Abstraction
  • 3. Introduction » In the preceding chapters, you learned about such methods as System.out.println, JOptionPane.showMessageDialog, JOptionPane.showInputDialog. » A method is a collection of statements that are grouped together to perform an operation. » When you call the System.out.println method, for example, the system actually executes several statements in order to display a message. https://www.facebook.com/Oxus20
  • 4. Creating a Method » In general, a method has the following syntax: modifier returnValueType methodName(list of parameters) { // Method body; } » Let's take a look at a method created to find which of two integers is bigger.This method, named max, has two int parameters, num1 and num2, the larger of which is returned by the method. https://www.facebook.com/Oxus20
  • 5. Creating & Calling Method https://www.facebook.com/Oxus20 Output will be: the result of max methd is 45
  • 6. Creating a Method » A method declaration consists of a method header and a method body. https://www.facebook.com/Oxus20 Method Header Method Body Modifier return value type method name formal parameter
  • 7. Creating a Method » The method header specifies the modifiers, return value type, method name, and parameters of the method.The modifier, which is optional, tells the compiler how to call the method.The static modifier is used for all the methods in this chapter.The reason for using it will be discussed in "Objects and Classes.“. » A method may return a value.The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void. For example, the returnValueType in the main method is void, as well as in System.exit, System.out.println, and JOptionPane.showMessageDialog.The method that returns a value is called a nonvoid method, and the method that does not return a value is called a void method. https://www.facebook.com/Oxus20
  • 8. Creating a Method » The variables defined in the method header are known as formal parameters or simply parameters. » When a method is invoked, you pass a value to the parameter.This value is referred to as actual parameter or argument. » The parameter list refers to the type, order, and number of the parameters of a method.The method name and the parameter list together constitute the method signature. Parameters are optional; that is, a method may contain no parameters. https://www.facebook.com/Oxus20
  • 9. Void Method » The preceding section gives an example of a nonvoid method.This section shows how to declare and invoke a void method. » gives a program that declares a method named grade and invokes it to print the grade for a given score. » The grade method is a void method. It does not return any value.A call to a void method must be a statement. So, it is invoked as a statement in the main method.This statement is like any Java statement terminated with a semicolon. https://www.facebook.com/Oxus20
  • 11. Void Method https://www.facebook.com/Oxus20 » A return statement is not needed for a void method, but it can be used for terminating the method and returning to the method's caller.The syntax is simply: return;
  • 12. Passing Parameters by Values https://www.facebook.com/Oxus20 » The power of a method is its ability to work with parameters. » You can use println to print any string and max to find the maximum between any two int values. » When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method specification.This is known as parameter order association. » For example, the following method prints a message n times:
  • 13. Passing Parameters by Values https://www.facebook.com/Oxus20 » You can use nPrintln(“hello", 3) to print "Hello" three times.The nPrintln(“hello", 3) statement passes the actual string parameter, “hello", to the parameter, message; passes 3 to n; and prints “hello" three times. However, the statement nPrintln(3,“hello") would be wrong.The data type of 3 does not match the data type for the first parameter, message, nor does the second parameter,“hello", match the second parameter, n.
  • 14. Passing Parameters by Values https://www.facebook.com/Oxus20 » The arguments must match the parameters in order, number, and compatible type, as defined in the method signature. » Compatible type means that you can pass an argument to a parameter without explicit casting, such as passing an int value argument to a double value parameter. » When you invoke a method with a parameter, the value of the argument is passed to the parameter.This is referred to as pass-by-value.
  • 15. Passing Parameters by Values https://www.facebook.com/Oxus20 » Swap is a program that demonstrates the effect of passing by value. » The program creates a method for swapping two variables. » The swap method is invoked by passing two arguments. Interestingly, the values of the arguments are not changed after the method is invoked.
  • 16. Passing Parameters by Values https://www.facebook.com/Oxus20
  • 17. Passing Parameters by Values https://www.facebook.com/Oxus20 » Before the swap method is invoked, num1 is 1 and num2 is 2. » After the swap method is invoked, num1 is still 1 and num2 is still 2.Their values are not swapped after the swap method is invoked. » the values of the arguments num1 and num2 are passed to n1 and n2, but n1 and n2 have their own memory locations independent of num1 and num2. » Therefore, changes in n1 and n2 do not affect the contents of num1 and num2.
  • 18. Overloading Method https://www.facebook.com/Oxus20 » The max method that was used earlier works only with the int data type. » But what if you need to find 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; }
  • 19. Overloading Method https://www.facebook.com/Oxus20 » If you call max with int parameters, the max method that expects int parameters will be invoked; » if you call max with double parameters, the max method that expects double parameters will be invoked. » This is referred to as method overloading; that is, two methods have the same name but different parameter lists within one class. » Next page program that creates three methods.The first finds the maximum integer, the second finds the maximum double, and the third finds the maximum among three double values.All three methods are named max.
  • 21. Overloading Method https://www.facebook.com/Oxus20 » When calling max(5, 6) , the max method for finding the maximum of two integers is invoked. » When calling max(5.5, 6.6), the max method for finding the maximum of two doubles is invoked. » When calling max(10, 11.2, 12.5) , the max method for finding the maximum of three double values is invoked. » Can you invoke the max method with an int value and a double value, such as max(10, 11.2,12.5)? If so, which of the max methods is invoked?The answer to the first question is yes.The answer to the second is that the max method for finding the maximum of two double values is invoked.The argument value 10 is automatically converted into a double value and passed to this method.
  • 22. Overloading Method https://www.facebook.com/Oxus20 » Sometimes there are 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 causes a compilation error. Consider the following code: » Both max(int, double) and max(double, int) are possible candidates to match max(1, 2). Since neither of them is more specific than the other, the invocation is ambiguous, resulting in a compilation error.
  • 23. The Scope and Variables https://www.facebook.com/Oxus20 » The scope of a variable is the part of the program where the variable can be referenced. » A variable defined inside a method is referred to as a local variable. » 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. » A parameter is actually a local variable.The scope of a method parameter covers the entire method.
  • 24. The Scope and Variables https://www.facebook.com/Oxus20 » 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 to the end of the block that contains the variable.
  • 25. The Scope and Variables https://www.facebook.com/Oxus20 » 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.
  • 26. The Scope and Variables https://www.facebook.com/Oxus20 » Do not declare a variable inside a block and then attempt to use it outside the block. Here is an example of a common mistake: » The last statement would cause a syntax error because variable i is not defined outside of the for loop.
  • 27. The Math Class https://www.facebook.com/Oxus20 » The Math class contains the methods needed to perform basic mathematical functions. » Trigonometric Methods public static double sin(double radians) public static double cos(double radians) public static double tan(double radians) public static double asin(double radians) public static double acos(double radians) public static double atan(double radians) public static double toRadians(double degree) public static double toDegrees(double radians)
  • 28. The Math Class https://www.facebook.com/Oxus20 Examples Math.sin(0) returns 0.0 Math.sin(Math.toRadians(270)) returns -1.0 Math.sin(Math.PI / 6) returns 0.5 Math.sin(Math.PI / 2) returns 1.0 Math.cos(0) returns 1.0 Math.cos(Math.PI / 6) returns 0.866 Math.cos(Math.PI / 2) returns 0
  • 29. The Math Class https://www.facebook.com/Oxus20 Exponent Methods » There are five methods related to exponents in the Math class: /** Return e raised to the power of x (ex) */ public static double exp(double x) /** Return the natural logarithm of x (ln(x) = loge(x)) */ static double log(double x) /** Return the base 10 logarithm of x (log10(x)) */ public static double log10(double x) /** Return a raised to the power of b (xb) */ public static double pow(double x, double b) /** Return the square root of a () */ public static double sqrt(double x) » Note that the parameter in the sqrt method must not be negative.
  • 30. The Math Class https://www.facebook.com/Oxus20 Examples Math.exp(1) returns 2.71828 Math.log(Math.E) returns 1.0 Math.log10(10) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24
  • 31. The Math Class https://www.facebook.com/Oxus20 The Rounding Methods » The Math class contains five rounding methods: /** x rounded up to its nearest integer. This integer is * returned as a double value. */ public static double ceil(double x) /** x is rounded down to its nearest integer. This integer is * returned as a double value. */ public static double floor(double x) /** x is rounded to its nearest integer. If x is equally close * to two integers, the even one is returned as a double. */ public static double rint(double x) /** Return (int)Math.floor(x + 0.5). */ public static int round(float x) /** Return (long)Math.floor(x + 0.5). */ public static long round(double x)
  • 32. The Math Class https://www.facebook.com/Oxus20 Examples Math.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0 Math.ceil(–2.0) returns –2.0 Math.ceil(–2.1) returns -2.0 Math.floor(2.1) returns 2.0 Math.floor(2.0) returns 2.0 Math.floor(-2.0) returns –2.0 Math.floor(-2.1) returns -3.0 Math.rint(2.1) returns 2.0 Math.rint(2.0) returns 2.0 Math.rint(-2.0) returns –2.0 Math.rint(-2.1) returns –2.0 Math.rint(2.5) returns 2.0 Math.rint(-2.5) returns -2.0 Math.round(2.6f) returns 3 // Returns int Math.round(2.0) returns 2 // Returns long Math.round(–2.0f) returns -2 Math.round(–2.6) returns -3
  • 33. The Math Class https://www.facebook.com/Oxus20 The min, max, and abs Methods » The min and max methods are overloaded to return the minimum and maximum numbers between two numbers (int, long, float, or double). For example, max(3.4, 5.0) returns 5.0, and min(3, 2) returns 2. » The abs method is overloaded to return the absolute value of the number (int, long, float, and double). For example, Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 Math.abs(-2.1) returns 2.1
  • 34. The Math Class https://www.facebook.com/Oxus20 The random Method » The Math class also has a powerful method, random, which generates a random double value greater than or equal to 0.0 and less than 1.0 (0.0 <= Math.random() < 1.0). » Not all classes need a main method.The Math class and JOptionPane class do not have main methods.These classes contain methods for other classes to use.
  • 36. Method Abstraction https://www.facebook.com/Oxus20 » The key to developing software is to apply the concept of abstraction. » Method abstraction is achieved by separating the use of a method from its implementation. » The client can use a method without knowing how it is implemented. The details of the implementation are encapsulated in the method and hidden from the client who invokes the method.This is known as information hiding or encapsulation. » If you decide to change the implementation, the client program will not be affected, provided that you do not change the method signature.The implementation of the method is hidden from the client in a "black box,"
  • 37. Method Abstraction https://www.facebook.com/Oxus20 » You have already used the System.out.print method to display a string, the JOptionPane.showInputDialog method to read a string from a dialog box, and the max method to find the maximum number.You know how to write the code to invoke these methods in your program, but as a user of these methods, you are not required to know how they are implemented.