SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210Mahmoud Samir Fayed
 
Data mining assignment 4
Data mining assignment 4Data mining assignment 4
Data mining assignment 4BarryK88
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithmK Hari Shankar
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonAndrew Ferlitsch
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using HaskellFunctional Thursday
 
A complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsA complete introduction on matlab and matlab's projects
A complete introduction on matlab and matlab's projectsMukesh Kumar
 
Data mining assignment 5
Data mining assignment 5Data mining assignment 5
Data mining assignment 5BarryK88
 

La actualidad más candente (20)

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

Similar a Lec 8 03_sept [compatibility mode]

Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUadAccount
 
ch03-parameters-objects.ppt
ch03-parameters-objects.pptch03-parameters-objects.ppt
ch03-parameters-objects.pptMahyuddin8
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
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 technologyworldchannel
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxShahinAhmed49
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Nettjunicornfx
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 

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

Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Object and class
Object and classObject and class
Object and class
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
ch03-parameters-objects.ppt
ch03-parameters-objects.pptch03-parameters-objects.ppt
ch03-parameters-objects.ppt
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Parameters
ParametersParameters
Parameters
 
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
 
Built-in Classes in JAVA
Built-in Classes in JAVABuilt-in Classes in JAVA
Built-in Classes in JAVA
 
Methods
MethodsMethods
Methods
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Java execise
Java execiseJava execise
Java execise
 
Second chapter-java
Second chapter-javaSecond chapter-java
Second chapter-java
 

Más de Palak Sanghani

Más de Palak Sanghani (20)

Survey form
Survey formSurvey form
Survey form
 
Survey
SurveySurvey
Survey
 
Nature2
Nature2Nature2
Nature2
 
Texture
TextureTexture
Texture
 
Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]
 
Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]
 
Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]
 
Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]Lec 6 14_aug [compatibility mode]
Lec 6 14_aug [compatibility mode]
 
Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]Lec 4 06_aug [compatibility mode]
Lec 4 06_aug [compatibility mode]
 
Lec 3 01_aug13
Lec 3 01_aug13Lec 3 01_aug13
Lec 3 01_aug13
 
Lec 2 30_jul13
Lec 2 30_jul13Lec 2 30_jul13
Lec 2 30_jul13
 
Lec 1 25_jul13
Lec 1 25_jul13Lec 1 25_jul13
Lec 1 25_jul13
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
 
Nature
NatureNature
Nature
 
Comparisionof trees
Comparisionof treesComparisionof trees
Comparisionof trees
 
My Structure Patterns
My Structure PatternsMy Structure Patterns
My Structure Patterns
 
My Similarity Patterns
My Similarity PatternsMy Similarity Patterns
My Similarity Patterns
 
My Radiation Patterns
My Radiation PatternsMy Radiation Patterns
My Radiation Patterns
 
My Gradation Patterns
My Gradation PatternsMy Gradation Patterns
My Gradation Patterns
 
My Circular Patterns
My Circular PatternsMy Circular Patterns
My Circular Patterns
 

Último

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

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