Java Data types and Variables
Lecture 8
Naveen Kumar
Primitive Data Types
 Integer
Type Bit Size
byte 8
short 16 (-32,768, 32,767)
int 32
long 64
 Float float 32
double 64
 Character 16 (65,535)
 Boolean 1/0
Identifiers
 Identifier: name of a variable, method, or class
 Rules for identifiers in Java:
– Can be made up of letters, digits, and the underscore (_) character
– Cannot start with a digit
– Cannot use other symbols such as ? or %
– Spaces are not permitted inside identifiers
– You cannot use reserved words
– They are case sensitive
 By convention, variable names start with a lowercase letter
 By convention, class names start with an uppercase letter
Implicit and Explicit Parameters
 Parameter (explicit parameter):
– Input to a method.
– Not all methods have explicit parameters.
System.out.println(greeting)
greeting.length() // has no explicit parameter
 Implicit parameter: The object on which a
method is invoked
greeting.length()
Replace Method
 Let, String river=“Mississippi”;
 replace method carries out a search-and-replace
operation
river.replace("issipp", "our")
// constructs a new string ("Missouri")
 This method call has
– one implicit parameter: the string "Mississippi"
– two explicit parameters: the strings "issipp" and "our"
– a return value: the string "Missouri"
Method Overloading
 A method name is overloaded if a class has
more than one method with the same name (but
different parameter types)
public void println(String output)
public void println(int output)
Rectangular Shapes and
Rectangle Objects
 Objects of type Rectangle describe
rectangular shapes
 A Rectangle object isn't a rectangular shape–
it is an object that contains a set of numbers
that describe the rectangle
Constructing Objects
 new Rectangle(5, 10, 20, 30)
Detail:
– The new operator makes a Rectangle object
– It uses the parameters (in this case, 5, 10, 20, and 30)
to initialize the data of the object
– It returns the object
 Usually the output of the new operator is stored
in a variable
Rectangle box = new Rectangle(5, 10, 20, 30);
Constructing Objects
 The process of creating a new object is called
construction
 The four values 5, 10, 20, and 30 are called the
construction parameters
 new Rectangle()
// constructs a rectangle with its top-left corner
// at the origin (0, 0), width 0, and height 0
Self Check
 How do you construct a square with center (100,
100) and side length 20?
 What does the following statement print?
System.out.println(new Rectangle().getWidth());
Answers
 new Rectangle(90, 90, 20, 20)
 0
Accessor and Mutator Methods
 Accessor method: does not change the state
of its implicit parameter
double width = box.getWidth();
 Mutator method: changes the state of its
implicit parameter
box.translate(15, 25);
Self Check
 Is the toUpperCase method of the String class an
accessor or a mutator?
 Which call to translate is needed to move the box
rectangle so that its top-left corner is the origin (0,0)?
 Answers
 An accessor–it doesn't modify the original string but
returns a new string with uppercase letters
 box.translate(-5, -10), provided the method is called
immediately after storing the new rectangle into box
Rectangle box = new Rectangle(5, 10, 20, 30);
Importing Packages
 Don't forget to include appropriate packages:
Java classes are grouped into packages
 Import library classes by specifying the
package and class name:
import java.awt.Rectangle;
Example
import java.awt.Rectangle;
public class Move
{
public static void main(String[] args)
{
Rectangle box = new Rectangle(5, 10, 20, 30);
// Move the rectangle
box.translate(15, 25);
// Print information about the moved rectangle
System.out.println("After moving, the top-left corner is:");
System.out.println(box.getX());
System.out.println(box.getY());
}
}
Output
 After moving, the top-left corner is:
20
35
Self Check
 The Random class is defined in the java.util
package. What do you need to do in order to use
that class in your program?
Answers
 Add the statement import java.util.Random; at
the top of your program
Random class
 Random r = new Random();
 int i = r.nextInt(int n) Returns random int ≥ 0 and < n
 int i = r.nextInt() Returns random int (full range)
 long i = r.nextLong() Returns random long (full range)
 float f = r.nextFloat() Returns random float ≥0.0 and <1.0
 double d = r.nextDouble() Returns random double ≥ 0.0 and < 1.0
 boolean b = r.nextBoolean() Returns random double (true ,false)
 double x;
x = Math.random(); // assigns random number to x
17
Object References
 Describe the location of objects
 The new operator returns a reference to a new object
Rectangle box = new Rectangle();
 Multiple object variables can refer to the same object
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
box2.translate(15, 25);
 Primitive type variables ≠ object variables
Self Check
 What is the effect of the assignment greeting2 =
greeting?
 After calling greeting2.toUpperCase(), what are the
contents of greeting and greeting2?
 Answers
 Now greeting and greeting2 both refer to the same String
object.
 Both variables still refer to the same string, and the string
has not been modified. Recall that the toUpperCase
method constructs a new string that contains uppercase
characters, leaving the original string unchanged.
Primitive Types
Type Description Size
int The integer type, with range -2,147,483,648 . . . 2,147,483,647 4 bytes
byte The type describing a single byte, with range -128 . . . 127 1 byte
short The short integer type, with range -32768 . . . 32767 2 bytes
long The long integer type, with range -9,223,372,036,854,775,808 . . . -
9,223,372,036,854,775,807
8 bytes
double The double-precision floating-point type, with a range of about ±10
308
and
about 15 significant decimal digits
8 bytes
float The single-precision floating-point type, with a range of about ±10
38
and about
7 significant decimal digits
4 bytes
char The character type, representing code units in the Unicode encoding scheme 2 bytes
boolean The type with the two truth values false and true 1 bit
20
Cast
 (typeName) expression
Example:
 (int) (balance * 100)
Purpose:
 To convert an expression to a different type
21
Self Check
 Which are the most commonly used number types in Java?
 When does the cast (long) x [double x] yield a different result from
the call Math.round(x)?
 How do you round the double value x to the nearest int value?
Answers
 int and double
 When the fractional part of x is ≥ 0.5
 By using a cast: (int) Math.round(x)
22
Constants: final
 A final variable is a constant
 Once its value has been set, it cannot be changed
 Named constants make programs easier to read and maintain
 Convention: use all-uppercase names for constants
final double QUARTER_VALUE = 0.25;
final double DIME_VALUE = 0.1;
23
Constants: static final
 static is used with class members
 If constant values are needed in several methods, declare them
together and tag them as static and final
 Give static final constants public access to enable other classes to
use them
public class Math
{
. . .
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
}
double circumference = Math.PI * diameter; (call without object)
24
Syntax : Constant Definition
 In a method:
final typeName variableName = expression ;
 In a class:
accessSpecifier static final typeName variableName =
expression;
Example:
 final double NICKEL_VALUE = 0.05;
 public static final double LITERS_PER_GALLON = 3.785;
Purpose:
 To define a constant in a method or a class
25
Self Check
 What is the difference between the following two statements?
final double CM_PER_INCH = 2.54;
and
public static final double CM_PER_INCH = 2.54;
 What is wrong with the following statement?
double circumference = 3.14 * diameter;
Answers
 The first definition is used inside a method, the second inside a class
 (1) You should use a named constant, not 3.14
(2) 3.14 is not an accurate representation of π
26
Increment, and Decrement
 items++ is the same as items = items + 1
 items-- subtracts 1 from items
 ++a;
 --a;
 a++;
 a--;
27
Arithmetic Operations
 / is the division operator
 If both arguments are integers, the result is an
integer. The remainder is discarded
– 7.0 / 4 yields 1.75
– 7 / 4 yields 1
 Get the remainder with % (pronounced "modulo")
7 % 4 is 328
The Math class
 Math class: contains methods like sqrt and pow
 To compute xn, you write Math.pow(x, n)
 However, to compute x2 it is significantly more efficient simply to
compute x * x
 To take the square root of a number x, use the Math.sqrt;
for example,
Math.sqrt(x)
29
Mathematical Methods in Java
30
Math.sqrt(x) square root
Math.pow(x, y) power xy
Math.exp(x) ex
Math.log(x) natural log
Math.sin(x), Math.cos(x), Math.tan(x) sine, cosine, tangent (x in radian)
Math.round(x) closest integer to x
Math.min(x, y), Math.max(x, y) minimum, maximum
java.lang.Math methods
 E, PI
 sin(_), cos(_), abs(_), tan(_), ceil(_), floor(_),
log(_), max(_,_), min(_,_), pow(_,_), sqrt(_),
round(_), random(), toDegrees(_),
toRadians(_)
31
Self Check
 What is the value of 1729 / 100? and 1729 % 100?
 What does the following statement compute ?
double average = s1 + s2 + s3 / 3;
 What is the value of Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
in mathematical notation?
 Answers
 17 and 29
 Only s3 is divided by 3. To get the correct result, use
parentheses. Moreover, if s1, s2, and s3 are integers, you must
divide by 3.0 to avoid integer division:
(s1 + s2 + s3) / 3.0
32
Calling Static Methods
 A static method does not operate on an object
double x = 4;
double root = x.sqrt(); // Error
 Static methods are defined inside classes
 Naming convention: Classes start with an uppercase
letter; objects start with a lowercase letter
Math
System.out
33
Static Method Call
 ClassName. methodName(parameters)
Example:
 Math.sqrt(4)
Purpose:
 To invoke a static method (a method that
does not operate on an object) and supply its
parameters34
Self Check
 Why can't you call x.pow(y) to compute xy ?
 Is the call System.out.println(4) a static
method call?
Answers
 x is a number, not an object, and you cannot
invoke methods on numbers
 No–the println method is called on the object
System.out35

More Related Content

PDF
INTRODUCTION TO MATLAB session with notes
PPTX
Java Foundations: Data Types and Type Conversion
PPTX
18. Dictionaries, Hash-Tables and Set
PPTX
Identifiers, keywords and types
PPT
Chapter 3 Arrays in Java
PPTX
Principles of functional progrmming in scala
PDF
Programming with matlab session 6
PPT
Chapter 4 - Classes in Java
INTRODUCTION TO MATLAB session with notes
Java Foundations: Data Types and Type Conversion
18. Dictionaries, Hash-Tables and Set
Identifiers, keywords and types
Chapter 3 Arrays in Java
Principles of functional progrmming in scala
Programming with matlab session 6
Chapter 4 - Classes in Java

What's hot (20)

PPTX
PPTX
17. Trees and Tree Like Structures
PPTX
19. Java data structures algorithms and complexity
PPT
Chapter 3 ds
PPT
Chapter 2 Method in Java OOP
PPTX
18. Java associative arrays
PPT
Arrays and structures
PDF
The Ring programming language version 1.9 book - Part 98 of 210
PDF
Data mining assignment 4
PDF
Introduction à Scala - Michel Schinz - January 2010
PDF
Advance data structure & algorithm
PPTX
Whiteboarding Coding Challenges in Python
PDF
Statistics lab 1
PDF
[FLOLAC'14][scm] Functional Programming Using Haskell
PDF
Mit6 094 iap10_lec04
PDF
A complete introduction on matlab and matlab's projects
PPT
Java Arrays
PDF
Data mining assignment 5
PDF
Programming with matlab session 1
PDF
Mit6 094 iap10_lec01
17. Trees and Tree Like Structures
19. Java data structures algorithms and complexity
Chapter 3 ds
Chapter 2 Method in Java OOP
18. Java associative arrays
Arrays and structures
The Ring programming language version 1.9 book - Part 98 of 210
Data mining assignment 4
Introduction à Scala - Michel Schinz - January 2010
Advance data structure & algorithm
Whiteboarding Coding Challenges in Python
Statistics lab 1
[FLOLAC'14][scm] Functional Programming Using Haskell
Mit6 094 iap10_lec04
A complete introduction on matlab and matlab's projects
Java Arrays
Data mining assignment 5
Programming with matlab session 1
Mit6 094 iap10_lec01
Ad

Similar to Lec 8 03_sept [compatibility mode] (20)

PDF
Lec 9 05_sept [compatibility mode]
PPT
Visula C# Programming Lecture 6
PPTX
IntroductionJava Programming - Math Class
PPT
Object and class
PDF
ádfasdfasdfasdfasdfasdfsadfsadfasdfasfasdfasdfasdfa
PPTX
Chapter 6.6
PPT
Class & Object - User Defined Method
PPTX
Using-Python-Libraries.9485146.powerpoint.pptx
PPT
ch03-parameters-objects.ppt
PDF
Object Oriented Solved Practice Programs C++ Exams
PPT
Parameters
PPTX
Intro to C# - part 2.pptx emerging technology
PDF
Built-in Classes in JAVA
PPTX
Ch2 Elementry Programmin as per gtu oop.pptx
PPT
Defining classes-and-objects-1.0
PPTX
Lecture_3.5-Array_Type Conversion_Math Class.pptx
PDF
Built in classes in java
PPS
Procedures functions structures in VB.Net
PPTX
20.1 Java working with abstraction
Lec 9 05_sept [compatibility mode]
Visula C# Programming Lecture 6
IntroductionJava Programming - Math Class
Object and class
ádfasdfasdfasdfasdfasdfsadfsadfasdfasfasdfasdfasdfa
Chapter 6.6
Class & Object - User Defined Method
Using-Python-Libraries.9485146.powerpoint.pptx
ch03-parameters-objects.ppt
Object Oriented Solved Practice Programs C++ Exams
Parameters
Intro to C# - part 2.pptx emerging technology
Built-in Classes in JAVA
Ch2 Elementry Programmin as per gtu oop.pptx
Defining classes-and-objects-1.0
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Built in classes in java
Procedures functions structures in VB.Net
20.1 Java working with abstraction
Ad

More from Palak Sanghani (20)

PDF
Survey form
PDF
PPTX
PDF
PDF
Lec 11 12_sept [compatibility mode]
PDF
Lec 7 28_aug [compatibility mode]
PDF
Lec 10 10_sept [compatibility mode]
PDF
Lec 6 14_aug [compatibility mode]
PDF
Lec 4 06_aug [compatibility mode]
PDF
Lec 3 01_aug13
PDF
Lec 2 30_jul13
PDF
Lec 1 25_jul13
PDF
Lec 5 13_aug [compatibility mode]
PDF
PDF
Comparisionof trees
PDF
My Structure Patterns
PDF
My Similarity Patterns
PDF
My Radiation Patterns
PDF
My Gradation Patterns
PDF
My Circular Patterns
Survey form
Lec 11 12_sept [compatibility mode]
Lec 7 28_aug [compatibility mode]
Lec 10 10_sept [compatibility mode]
Lec 6 14_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]
Lec 3 01_aug13
Lec 2 30_jul13
Lec 1 25_jul13
Lec 5 13_aug [compatibility mode]
Comparisionof trees
My Structure Patterns
My Similarity Patterns
My Radiation Patterns
My Gradation Patterns
My Circular Patterns

Recently uploaded (20)

PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Credit Without Borders: AI and Financial Inclusion in Bangladesh
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPT
What is a Computer? Input Devices /output devices
PDF
CloudStack 4.21: First Look Webinar slides
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PDF
Flame analysis and combustion estimation using large language and vision assi...
DOCX
search engine optimization ppt fir known well about this
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PPTX
The various Industrial Revolutions .pptx
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
OpenACC and Open Hackathons Monthly Highlights July 2025
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
Developing a website for English-speaking practice to English as a foreign la...
PPTX
Configure Apache Mutual Authentication
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
Two-dimensional Klein-Gordon and Sine-Gordon numerical solutions based on dee...
PDF
Architecture types and enterprise applications.pdf
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
1 - Historical Antecedents, Social Consideration.pdf
Credit Without Borders: AI and Financial Inclusion in Bangladesh
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
What is a Computer? Input Devices /output devices
CloudStack 4.21: First Look Webinar slides
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
Flame analysis and combustion estimation using large language and vision assi...
search engine optimization ppt fir known well about this
Consumable AI The What, Why & How for Small Teams.pdf
The various Industrial Revolutions .pptx
Getting started with AI Agents and Multi-Agent Systems
OpenACC and Open Hackathons Monthly Highlights July 2025
The influence of sentiment analysis in enhancing early warning system model f...
Developing a website for English-speaking practice to English as a foreign la...
Configure Apache Mutual Authentication
Zenith AI: Advanced Artificial Intelligence
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
Two-dimensional Klein-Gordon and Sine-Gordon numerical solutions based on dee...
Architecture types and enterprise applications.pdf

Lec 8 03_sept [compatibility mode]

  • 1. Java Data types and Variables Lecture 8 Naveen Kumar
  • 2. Primitive Data Types  Integer Type Bit Size byte 8 short 16 (-32,768, 32,767) int 32 long 64  Float float 32 double 64  Character 16 (65,535)  Boolean 1/0
  • 3. Identifiers  Identifier: name of a variable, method, or class  Rules for identifiers in Java: – Can be made up of letters, digits, and the underscore (_) character – Cannot start with a digit – Cannot use other symbols such as ? or % – Spaces are not permitted inside identifiers – You cannot use reserved words – They are case sensitive  By convention, variable names start with a lowercase letter  By convention, class names start with an uppercase letter
  • 4. Implicit and Explicit Parameters  Parameter (explicit parameter): – Input to a method. – Not all methods have explicit parameters. System.out.println(greeting) greeting.length() // has no explicit parameter  Implicit parameter: The object on which a method is invoked greeting.length()
  • 5. Replace Method  Let, String river=“Mississippi”;  replace method carries out a search-and-replace operation river.replace("issipp", "our") // constructs a new string ("Missouri")  This method call has – one implicit parameter: the string "Mississippi" – two explicit parameters: the strings "issipp" and "our" – a return value: the string "Missouri"
  • 6. Method Overloading  A method name is overloaded if a class has more than one method with the same name (but different parameter types) public void println(String output) public void println(int output)
  • 7. Rectangular Shapes and Rectangle Objects  Objects of type Rectangle describe rectangular shapes  A Rectangle object isn't a rectangular shape– it is an object that contains a set of numbers that describe the rectangle
  • 8. Constructing Objects  new Rectangle(5, 10, 20, 30) Detail: – The new operator makes a Rectangle object – It uses the parameters (in this case, 5, 10, 20, and 30) to initialize the data of the object – It returns the object  Usually the output of the new operator is stored in a variable Rectangle box = new Rectangle(5, 10, 20, 30);
  • 9. Constructing Objects  The process of creating a new object is called construction  The four values 5, 10, 20, and 30 are called the construction parameters  new Rectangle() // constructs a rectangle with its top-left corner // at the origin (0, 0), width 0, and height 0
  • 10. Self Check  How do you construct a square with center (100, 100) and side length 20?  What does the following statement print? System.out.println(new Rectangle().getWidth()); Answers  new Rectangle(90, 90, 20, 20)  0
  • 11. Accessor and Mutator Methods  Accessor method: does not change the state of its implicit parameter double width = box.getWidth();  Mutator method: changes the state of its implicit parameter box.translate(15, 25);
  • 12. Self Check  Is the toUpperCase method of the String class an accessor or a mutator?  Which call to translate is needed to move the box rectangle so that its top-left corner is the origin (0,0)?  Answers  An accessor–it doesn't modify the original string but returns a new string with uppercase letters  box.translate(-5, -10), provided the method is called immediately after storing the new rectangle into box Rectangle box = new Rectangle(5, 10, 20, 30);
  • 13. Importing Packages  Don't forget to include appropriate packages: Java classes are grouped into packages  Import library classes by specifying the package and class name: import java.awt.Rectangle;
  • 14. Example import java.awt.Rectangle; public class Move { public static void main(String[] args) { Rectangle box = new Rectangle(5, 10, 20, 30); // Move the rectangle box.translate(15, 25); // Print information about the moved rectangle System.out.println("After moving, the top-left corner is:"); System.out.println(box.getX()); System.out.println(box.getY()); } }
  • 15. Output  After moving, the top-left corner is: 20 35
  • 16. Self Check  The Random class is defined in the java.util package. What do you need to do in order to use that class in your program? Answers  Add the statement import java.util.Random; at the top of your program
  • 17. Random class  Random r = new Random();  int i = r.nextInt(int n) Returns random int ≥ 0 and < n  int i = r.nextInt() Returns random int (full range)  long i = r.nextLong() Returns random long (full range)  float f = r.nextFloat() Returns random float ≥0.0 and <1.0  double d = r.nextDouble() Returns random double ≥ 0.0 and < 1.0  boolean b = r.nextBoolean() Returns random double (true ,false)  double x; x = Math.random(); // assigns random number to x 17
  • 18. Object References  Describe the location of objects  The new operator returns a reference to a new object Rectangle box = new Rectangle();  Multiple object variables can refer to the same object Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25);  Primitive type variables ≠ object variables
  • 19. Self Check  What is the effect of the assignment greeting2 = greeting?  After calling greeting2.toUpperCase(), what are the contents of greeting and greeting2?  Answers  Now greeting and greeting2 both refer to the same String object.  Both variables still refer to the same string, and the string has not been modified. Recall that the toUpperCase method constructs a new string that contains uppercase characters, leaving the original string unchanged.
  • 20. Primitive Types Type Description Size int The integer type, with range -2,147,483,648 . . . 2,147,483,647 4 bytes byte The type describing a single byte, with range -128 . . . 127 1 byte short The short integer type, with range -32768 . . . 32767 2 bytes long The long integer type, with range -9,223,372,036,854,775,808 . . . - 9,223,372,036,854,775,807 8 bytes double The double-precision floating-point type, with a range of about ±10 308 and about 15 significant decimal digits 8 bytes float The single-precision floating-point type, with a range of about ±10 38 and about 7 significant decimal digits 4 bytes char The character type, representing code units in the Unicode encoding scheme 2 bytes boolean The type with the two truth values false and true 1 bit 20
  • 21. Cast  (typeName) expression Example:  (int) (balance * 100) Purpose:  To convert an expression to a different type 21
  • 22. Self Check  Which are the most commonly used number types in Java?  When does the cast (long) x [double x] yield a different result from the call Math.round(x)?  How do you round the double value x to the nearest int value? Answers  int and double  When the fractional part of x is ≥ 0.5  By using a cast: (int) Math.round(x) 22
  • 23. Constants: final  A final variable is a constant  Once its value has been set, it cannot be changed  Named constants make programs easier to read and maintain  Convention: use all-uppercase names for constants final double QUARTER_VALUE = 0.25; final double DIME_VALUE = 0.1; 23
  • 24. Constants: static final  static is used with class members  If constant values are needed in several methods, declare them together and tag them as static and final  Give static final constants public access to enable other classes to use them public class Math { . . . public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846; } double circumference = Math.PI * diameter; (call without object) 24
  • 25. Syntax : Constant Definition  In a method: final typeName variableName = expression ;  In a class: accessSpecifier static final typeName variableName = expression; Example:  final double NICKEL_VALUE = 0.05;  public static final double LITERS_PER_GALLON = 3.785; Purpose:  To define a constant in a method or a class 25
  • 26. Self Check  What is the difference between the following two statements? final double CM_PER_INCH = 2.54; and public static final double CM_PER_INCH = 2.54;  What is wrong with the following statement? double circumference = 3.14 * diameter; Answers  The first definition is used inside a method, the second inside a class  (1) You should use a named constant, not 3.14 (2) 3.14 is not an accurate representation of π 26
  • 27. Increment, and Decrement  items++ is the same as items = items + 1  items-- subtracts 1 from items  ++a;  --a;  a++;  a--; 27
  • 28. Arithmetic Operations  / is the division operator  If both arguments are integers, the result is an integer. The remainder is discarded – 7.0 / 4 yields 1.75 – 7 / 4 yields 1  Get the remainder with % (pronounced "modulo") 7 % 4 is 328
  • 29. The Math class  Math class: contains methods like sqrt and pow  To compute xn, you write Math.pow(x, n)  However, to compute x2 it is significantly more efficient simply to compute x * x  To take the square root of a number x, use the Math.sqrt; for example, Math.sqrt(x) 29
  • 30. Mathematical Methods in Java 30 Math.sqrt(x) square root Math.pow(x, y) power xy Math.exp(x) ex Math.log(x) natural log Math.sin(x), Math.cos(x), Math.tan(x) sine, cosine, tangent (x in radian) Math.round(x) closest integer to x Math.min(x, y), Math.max(x, y) minimum, maximum
  • 31. java.lang.Math methods  E, PI  sin(_), cos(_), abs(_), tan(_), ceil(_), floor(_), log(_), max(_,_), min(_,_), pow(_,_), sqrt(_), round(_), random(), toDegrees(_), toRadians(_) 31
  • 32. Self Check  What is the value of 1729 / 100? and 1729 % 100?  What does the following statement compute ? double average = s1 + s2 + s3 / 3;  What is the value of Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) in mathematical notation?  Answers  17 and 29  Only s3 is divided by 3. To get the correct result, use parentheses. Moreover, if s1, s2, and s3 are integers, you must divide by 3.0 to avoid integer division: (s1 + s2 + s3) / 3.0 32
  • 33. Calling Static Methods  A static method does not operate on an object double x = 4; double root = x.sqrt(); // Error  Static methods are defined inside classes  Naming convention: Classes start with an uppercase letter; objects start with a lowercase letter Math System.out 33
  • 34. Static Method Call  ClassName. methodName(parameters) Example:  Math.sqrt(4) Purpose:  To invoke a static method (a method that does not operate on an object) and supply its parameters34
  • 35. Self Check  Why can't you call x.pow(y) to compute xy ?  Is the call System.out.println(4) a static method call? Answers  x is a number, not an object, and you cannot invoke methods on numbers  No–the println method is called on the object System.out35