SlideShare a Scribd company logo
IMPLEMENTING TYPE
CONVERSION
Chapter 3.4:
Analyzing an Expression
Data Conversion
 Sometimes it is convenient to convert data from
one type to another
 For example, in a particular situation we may want
to treat an integer as a floating point value
 These conversions do not change the type of a
variable or the value that's stored in it – they only
convert a value as part of a computation
Data Conversion
 Widening conversions are safest because they
tend to go from a small data type to a larger
one (such as a short to an int)
 Narrowing conversions can lose information
because they tend to go from a large data type
to a smaller one (such as an int to a short)
 In Java, data conversions can occur in three
ways:
 assignment conversion
 promotion
 casting
Data Conversion
Widening Conversions Narrowing Conversions
Assignment Conversion
 Assignment conversion occurs when a
value of one type is assigned to a variable
of another
 Example:
int dollars = 20;
double money = dollars;
 Only widening conversions can happen via
assignment
 Note that the value or type of dollars did
not change
Promotion
 Promotion happens automatically when operators
in expressions convert their operands
 Example:
int count = 12;
double sum = 490.27;
result = sum / count;
 The value of count is converted to a floating point
value to perform the division calculation
Casting
 Casting is the most powerful, and dangerous,
technique for conversion
 Both widening and narrowing conversions can be
accomplished by explicitly casting a value
 To cast, the type is put in parentheses in front of
the value being converted
int total = 50;
float result = (float) total / 6;
 Without the cast, the fractional part of the answer
would be lost
Explicit Type Casting
 Instead of relying on the promotion rules, we can
make an explicit type cast by prefixing the operand
with the data type using the following syntax:
( <data type> ) <expression>
 Example
(float) x / 3
(int) (x / y * 3.0)
Type cast x to float and
then divide it by 3.
Type cast the result of the
expression x / y * 3.0 to
int.
Explicit Type Casting
 Consider the following expression:
double x = 3 + 5;
 The result of 3 + 5 is of type int. However, since
the variable x is double, the value 8 (type int) is
promoted to 8.0 (type double) before being
assigned to x.
 Notice that it is a promotion. Demotion is not
allowed.
int x = 3.5;
A higher precision value
cannot be assigned to a
lower precision variable.
Example
public class TestCasting
{
public static void main(String[] args)
{
double number=3.45;
System.out.println("Number: "+number);
System.out.println("The integer nearest to"
+ number + " = "+ (int)(number + 0.5));
}
}
Number: 3.45
The integer nearest to 3.45 = 3
Output:
Type Conversion
1. Casting
• to cast operator in an arithmetic
expression
2. Wrapper classes
• to perform necessary type conversions,
such as converting a String object to a
numerical value.
Type Conversion – Wrapper
Classes
Reading Input
 Programs generally need input on which to
operate
 The Scanner class provides convenient methods
for reading input values of various types
 A Scanner object can be set up to read input from
various sources, including the user typing values
on the keyboard
 Keyboard input is represented by the System.in
object
Reading Input
 The following line creates a Scanner object that
reads from the keyboard:
Scanner scan = new Scanner (System.in);
 The new operator creates the Scanner object
 Once created, the Scanner object can be used to
invoke various input methods, such as:
answer = scan.nextLine();
Reading Input
 The Scanner class is part of the java.util
class library, and must be imported into a program
to be used
 The nextLine method reads all of the input until
the end of the line is found
 See Echo.java
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
public class Echo
{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String message;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a line of text:");
message = scan.nextLine();
System.out.println ("You entered: "" + message + """);
}
}
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
public class Echo
{
//-----------------------------------------------------------------
// Reads a character string from the user and prints it.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String message;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a line of text:");
message = scan.nextLine();
System.out.println ("You entered: "" + message + """);
}
}
Sample Run
Enter a line of text:
You want fries with that?
You entered: "You want fries with that?"
Reading Input – Input
Tokens
 Unless specified otherwise, white space is used to
separate the elements (called tokens) of the input
 White space includes space characters, tabs, new
line characters
 The next method of the Scanner class reads the
next input token and returns it as a string
 Methods such as nextInt and nextDouble
read data of particular types
 See GasMileage.java
Goals//********************************************************************
// GasMileage.java Author: Lewis/Loftus
//
// Demonstrates the use of the Scanner class to read numeric data.
//********************************************************************
import java.util.Scanner;
public class GasMileage
{
//-----------------------------------------------------------------
// Calculates fuel efficiency based on values entered by the
// user.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int miles;
double gallons, mpg;
Scanner scan = new Scanner (System.in);
continue
continue
System.out.print ("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print ("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;
System.out.println ("Miles Per Gallon: " + mpg);
}
}
continue
System.out.print ("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print ("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;
System.out.println ("Miles Per Gallon: " + mpg);
}
}
Sample Run
Enter the number of miles: 328
Enter the gallons of fuel used: 11.2
Miles Per Gallon: 29.28571428571429
Primitive vs. Reference
 Numerical data are called primitive data types.
 Objects are called reference data types, because
the contents are addresses that refer to memory
locations where the objects are actually stored.
Primitive Data Declaration and
Assignments
Code State of Memory
int firstNumber, secondNumber;
firstNumber = 234;
secondNumber = 87;
A
B
firstNumber
secondNumber
A. Variables are
allocated in memory.
B. Values are assigned
to variables.
234
87
Assigning Numerical Data
Code State of Memory
number
A. The variable
is allocated in
memory.
B. The value 237
is assigned to
number.
237
int number;
number = 237;
A
B
Cnumber = 35;
C. The value 35
overwrites the
previous value 237.
35
Assigning Objects
Code State of Memory
customer
A. The variable is
allocated in memory.
Customer customer;
customer = new Customer( );
customer = new Customer( );
A
B
C
B. The reference to the
new object is assigned
to customer.
Customer
C. The reference to
another object overwrites
the reference in customer.
Customer
Having Two References to a Single
Object
Code State of Memory
Customer clemens, twain,
clemens = new Customer( );
twain = clemens;
A
B
C
A. Variables are
allocated in memory.
clemens
twain
B. The reference to the
new object is assigned
to clemens.
Customer
C. The reference in
clemens is assigned to
customer.
Programming Style and
Documentation
 Appropriate Comments
 Naming Conventions
 Proper Indentation and Spacing Lines
 Block Styles
Appropriate Comments
 Include a summary at the beginning of the
program to explain what the program does, its key
features, its supporting data structures, and any
unique techniques it uses.
 Include your name, class section, instructor, date,
and a brief description at the beginning of the
program.
Naming Conventions
 Choose meaningful and descriptive names.
 Variables and method names:
 Use lowercase. If the name consists of several
words, concatenate all in one, use lowercase for
the first word, and capitalize the first letter of
each subsequent word in the name. For
example, the variables radius and area, and the
method computeArea.
Naming Conventions
 Class names:
 Capitalize the first letter of each word in the
name. For example, the class name
ComputeArea.
 Constants:
 Capitalize all letters in constants, and use
underscores to connect words. For example,
the constant PI and MAX_VALUE
Proper Indentation and Spacing
 Indentation
 Indent two spaces.
 Spacing
 Use blank line to separate segments of the
code.
Block Styles
Use end-of-line style for braces.
public class Test
{
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
End-of-line
style
Next-line
style
Special Symbols
Commonly used Escape Sequences
Escape Sequences
 What if we wanted to print the quote character?
 The following line would confuse the compiler
because it would interpret the second quote as the
end of the string
System.out.println ("I said "Hello" to you.");
 An escape sequence is a series of characters that
represents a special character
 An escape sequence begins with a backslash
character ()
System.out.println ("I said "Hello" to you.");
Goals
//********************************************************************
// Roses.java Author: Lewis/Loftus
//
// Demonstrates the use of escape sequences.
//********************************************************************
public class Roses
{
//-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,ntViolets are blue,n" +
"Sugar is sweet,ntBut I have "commitment issues",nt" +
"So I'd rather just be friendsntAt this point in our " +
"relationship.");
}
}
Goals
//********************************************************************
// Roses.java Author: Lewis/Loftus
//
// Demonstrates the use of escape sequences.
//********************************************************************
public class Roses
{
//-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,ntViolets are blue,n" +
"Sugar is sweet,ntBut I have "commitment issues",nt" +
"So I'd rather just be friendsntAt this point in our " +
"relationship.");
}
}
Output
Roses are red,
Violets are blue,
Sugar is sweet,
But I have "commitment issues",
So I'd rather just be friends
At this point in our relationship.

More Related Content

What's hot

Cis160 Final Review
Cis160 Final ReviewCis160 Final Review
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
Eduardo Bergavera
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
Jaya Kumari
 
M C6java3
M C6java3M C6java3
M C6java3
mbruggen
 
C# String
C# StringC# String
Lecture#08 sequence diagrams
Lecture#08 sequence diagramsLecture#08 sequence diagrams
Lecture#08 sequence diagrams
babak danyal
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
topu93
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
Rajeshkumar Reddy
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
dplunkett
 
M C6java2
M C6java2M C6java2
M C6java2
mbruggen
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
Dhrumil Patel
 
The Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram TutorialThe Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram Tutorial
Creately
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
nmahi96
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
Kuntal Bhowmick
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
Syed Asrarali
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Basic
BasicBasic
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
Ram Sagar Mourya
 
Pointers
PointersPointers
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
Suchit Patel
 

What's hot (20)

Cis160 Final Review
Cis160 Final ReviewCis160 Final Review
Cis160 Final Review
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
M C6java3
M C6java3M C6java3
M C6java3
 
C# String
C# StringC# String
C# String
 
Lecture#08 sequence diagrams
Lecture#08 sequence diagramsLecture#08 sequence diagrams
Lecture#08 sequence diagrams
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
C UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDYC UNIT-3 PREPARED BY M V B REDDY
C UNIT-3 PREPARED BY M V B REDDY
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
M C6java2
M C6java2M C6java2
M C6java2
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
The Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram TutorialThe Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram Tutorial
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
Basic
BasicBasic
Basic
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Pointers
PointersPointers
Pointers
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
 

Viewers also liked

Chapter 3.1
Chapter 3.1Chapter 3.1
Chapter 3.1
sotlsoc
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
sotlsoc
 
Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1
sotlsoc
 
Chapter 7.4
Chapter 7.4Chapter 7.4
Chapter 7.4
sotlsoc
 
Chapter 11.2
Chapter 11.2Chapter 11.2
Chapter 11.2
sotlsoc
 
Chapter 5.1
Chapter 5.1Chapter 5.1
Chapter 5.1
sotlsoc
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
sotlsoc
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2
sotlsoc
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1
sotlsoc
 

Viewers also liked (9)

Chapter 3.1
Chapter 3.1Chapter 3.1
Chapter 3.1
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
 
Chapter 10.1
Chapter 10.1Chapter 10.1
Chapter 10.1
 
Chapter 7.4
Chapter 7.4Chapter 7.4
Chapter 7.4
 
Chapter 11.2
Chapter 11.2Chapter 11.2
Chapter 11.2
 
Chapter 5.1
Chapter 5.1Chapter 5.1
Chapter 5.1
 
Chapter 10.3
Chapter 10.3Chapter 10.3
Chapter 10.3
 
Chapter 2.2
Chapter 2.2Chapter 2.2
Chapter 2.2
 
Chapter 9.1
Chapter 9.1Chapter 9.1
Chapter 9.1
 

Similar to Chapter 3.4

Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
PriyadarshiniS28
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
InfinityWorld3
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
Eduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
Synapseindiappsdevelopment
 
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
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
Abed Bukhari
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
Ananthu Mahesh
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
Philip Schwarz
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
shubhra chauhan
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2pp
J. C.
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
 
2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf
TrnThBnhDng
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
DeepasCSE
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
tjunicornfx
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
Rakesh Madugula
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
PowerfullBoy1
 

Similar to Chapter 3.4 (20)

Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
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
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2pp
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
 

More from sotlsoc

Chapter 2.0 new
Chapter 2.0 newChapter 2.0 new
Chapter 2.0 new
sotlsoc
 
Chapter 1.0 new
Chapter 1.0 newChapter 1.0 new
Chapter 1.0 new
sotlsoc
 
Chapter 3.0 new
Chapter 3.0 newChapter 3.0 new
Chapter 3.0 new
sotlsoc
 
Chapter 6.5 new
Chapter 6.5 newChapter 6.5 new
Chapter 6.5 new
sotlsoc
 
Chapter 11.1
Chapter 11.1Chapter 11.1
Chapter 11.1
sotlsoc
 
Chapter 11.4
Chapter 11.4Chapter 11.4
Chapter 11.4
sotlsoc
 
Chapter 11.3
Chapter 11.3Chapter 11.3
Chapter 11.3
sotlsoc
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
Chapter 11.0
Chapter 11.0Chapter 11.0
Chapter 11.0
sotlsoc
 
Chapter 10.2
Chapter 10.2Chapter 10.2
Chapter 10.2
sotlsoc
 
Chapter 8.0
Chapter 8.0Chapter 8.0
Chapter 8.0
sotlsoc
 
Chapter 10.0
Chapter 10.0Chapter 10.0
Chapter 10.0
sotlsoc
 
Chapter 9.3
Chapter 9.3Chapter 9.3
Chapter 9.3
sotlsoc
 
Chapter 9.4
Chapter 9.4Chapter 9.4
Chapter 9.4
sotlsoc
 
Chapter 8.1
Chapter 8.1Chapter 8.1
Chapter 8.1
sotlsoc
 
Chapter 9.0
Chapter 9.0Chapter 9.0
Chapter 9.0
sotlsoc
 
Chapter 9.2
Chapter 9.2Chapter 9.2
Chapter 9.2
sotlsoc
 
Chapter 8.3
Chapter 8.3Chapter 8.3
Chapter 8.3
sotlsoc
 
Chapter 5.2
Chapter 5.2Chapter 5.2
Chapter 5.2
sotlsoc
 
Chapter 7.3
Chapter 7.3Chapter 7.3
Chapter 7.3
sotlsoc
 

More from sotlsoc (20)

Chapter 2.0 new
Chapter 2.0 newChapter 2.0 new
Chapter 2.0 new
 
Chapter 1.0 new
Chapter 1.0 newChapter 1.0 new
Chapter 1.0 new
 
Chapter 3.0 new
Chapter 3.0 newChapter 3.0 new
Chapter 3.0 new
 
Chapter 6.5 new
Chapter 6.5 newChapter 6.5 new
Chapter 6.5 new
 
Chapter 11.1
Chapter 11.1Chapter 11.1
Chapter 11.1
 
Chapter 11.4
Chapter 11.4Chapter 11.4
Chapter 11.4
 
Chapter 11.3
Chapter 11.3Chapter 11.3
Chapter 11.3
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
 
Chapter 11.0
Chapter 11.0Chapter 11.0
Chapter 11.0
 
Chapter 10.2
Chapter 10.2Chapter 10.2
Chapter 10.2
 
Chapter 8.0
Chapter 8.0Chapter 8.0
Chapter 8.0
 
Chapter 10.0
Chapter 10.0Chapter 10.0
Chapter 10.0
 
Chapter 9.3
Chapter 9.3Chapter 9.3
Chapter 9.3
 
Chapter 9.4
Chapter 9.4Chapter 9.4
Chapter 9.4
 
Chapter 8.1
Chapter 8.1Chapter 8.1
Chapter 8.1
 
Chapter 9.0
Chapter 9.0Chapter 9.0
Chapter 9.0
 
Chapter 9.2
Chapter 9.2Chapter 9.2
Chapter 9.2
 
Chapter 8.3
Chapter 8.3Chapter 8.3
Chapter 8.3
 
Chapter 5.2
Chapter 5.2Chapter 5.2
Chapter 5.2
 
Chapter 7.3
Chapter 7.3Chapter 7.3
Chapter 7.3
 

Recently uploaded

ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Diana Rendina
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 

Recently uploaded (20)

ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 

Chapter 3.4

  • 3. Data Conversion  Sometimes it is convenient to convert data from one type to another  For example, in a particular situation we may want to treat an integer as a floating point value  These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation
  • 4. Data Conversion  Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int)  Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)  In Java, data conversions can occur in three ways:  assignment conversion  promotion  casting
  • 5. Data Conversion Widening Conversions Narrowing Conversions
  • 6. Assignment Conversion  Assignment conversion occurs when a value of one type is assigned to a variable of another  Example: int dollars = 20; double money = dollars;  Only widening conversions can happen via assignment  Note that the value or type of dollars did not change
  • 7. Promotion  Promotion happens automatically when operators in expressions convert their operands  Example: int count = 12; double sum = 490.27; result = sum / count;  The value of count is converted to a floating point value to perform the division calculation
  • 8. Casting  Casting is the most powerful, and dangerous, technique for conversion  Both widening and narrowing conversions can be accomplished by explicitly casting a value  To cast, the type is put in parentheses in front of the value being converted int total = 50; float result = (float) total / 6;  Without the cast, the fractional part of the answer would be lost
  • 9. Explicit Type Casting  Instead of relying on the promotion rules, we can make an explicit type cast by prefixing the operand with the data type using the following syntax: ( <data type> ) <expression>  Example (float) x / 3 (int) (x / y * 3.0) Type cast x to float and then divide it by 3. Type cast the result of the expression x / y * 3.0 to int.
  • 10. Explicit Type Casting  Consider the following expression: double x = 3 + 5;  The result of 3 + 5 is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type double) before being assigned to x.  Notice that it is a promotion. Demotion is not allowed. int x = 3.5; A higher precision value cannot be assigned to a lower precision variable.
  • 11. Example public class TestCasting { public static void main(String[] args) { double number=3.45; System.out.println("Number: "+number); System.out.println("The integer nearest to" + number + " = "+ (int)(number + 0.5)); } } Number: 3.45 The integer nearest to 3.45 = 3 Output:
  • 12. Type Conversion 1. Casting • to cast operator in an arithmetic expression 2. Wrapper classes • to perform necessary type conversions, such as converting a String object to a numerical value.
  • 13. Type Conversion – Wrapper Classes
  • 14. Reading Input  Programs generally need input on which to operate  The Scanner class provides convenient methods for reading input values of various types  A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard  Keyboard input is represented by the System.in object
  • 15. Reading Input  The following line creates a Scanner object that reads from the keyboard: Scanner scan = new Scanner (System.in);  The new operator creates the Scanner object  Once created, the Scanner object can be used to invoke various input methods, such as: answer = scan.nextLine();
  • 16. Reading Input  The Scanner class is part of the java.util class library, and must be imported into a program to be used  The nextLine method reads all of the input until the end of the line is found  See Echo.java
  • 17. //******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. //******************************************************************** import java.util.Scanner; public class Echo { //----------------------------------------------------------------- // Reads a character string from the user and prints it. //----------------------------------------------------------------- public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: "" + message + """); } }
  • 18. //******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. //******************************************************************** import java.util.Scanner; public class Echo { //----------------------------------------------------------------- // Reads a character string from the user and prints it. //----------------------------------------------------------------- public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine(); System.out.println ("You entered: "" + message + """); } } Sample Run Enter a line of text: You want fries with that? You entered: "You want fries with that?"
  • 19. Reading Input – Input Tokens  Unless specified otherwise, white space is used to separate the elements (called tokens) of the input  White space includes space characters, tabs, new line characters  The next method of the Scanner class reads the next input token and returns it as a string  Methods such as nextInt and nextDouble read data of particular types  See GasMileage.java
  • 20. Goals//******************************************************************** // GasMileage.java Author: Lewis/Loftus // // Demonstrates the use of the Scanner class to read numeric data. //******************************************************************** import java.util.Scanner; public class GasMileage { //----------------------------------------------------------------- // Calculates fuel efficiency based on values entered by the // user. //----------------------------------------------------------------- public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); continue
  • 21. continue System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } }
  • 22. continue System.out.print ("Enter the number of miles: "); miles = scan.nextInt(); System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } } Sample Run Enter the number of miles: 328 Enter the gallons of fuel used: 11.2 Miles Per Gallon: 29.28571428571429
  • 23. Primitive vs. Reference  Numerical data are called primitive data types.  Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects are actually stored.
  • 24. Primitive Data Declaration and Assignments Code State of Memory int firstNumber, secondNumber; firstNumber = 234; secondNumber = 87; A B firstNumber secondNumber A. Variables are allocated in memory. B. Values are assigned to variables. 234 87
  • 25. Assigning Numerical Data Code State of Memory number A. The variable is allocated in memory. B. The value 237 is assigned to number. 237 int number; number = 237; A B Cnumber = 35; C. The value 35 overwrites the previous value 237. 35
  • 26. Assigning Objects Code State of Memory customer A. The variable is allocated in memory. Customer customer; customer = new Customer( ); customer = new Customer( ); A B C B. The reference to the new object is assigned to customer. Customer C. The reference to another object overwrites the reference in customer. Customer
  • 27. Having Two References to a Single Object Code State of Memory Customer clemens, twain, clemens = new Customer( ); twain = clemens; A B C A. Variables are allocated in memory. clemens twain B. The reference to the new object is assigned to clemens. Customer C. The reference in clemens is assigned to customer.
  • 28. Programming Style and Documentation  Appropriate Comments  Naming Conventions  Proper Indentation and Spacing Lines  Block Styles
  • 29. Appropriate Comments  Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses.  Include your name, class section, instructor, date, and a brief description at the beginning of the program.
  • 30. Naming Conventions  Choose meaningful and descriptive names.  Variables and method names:  Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea.
  • 31. Naming Conventions  Class names:  Capitalize the first letter of each word in the name. For example, the class name ComputeArea.  Constants:  Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE
  • 32. Proper Indentation and Spacing  Indentation  Indent two spaces.  Spacing  Use blank line to separate segments of the code.
  • 33. Block Styles Use end-of-line style for braces. public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } } public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } } End-of-line style Next-line style
  • 35. Commonly used Escape Sequences
  • 36. Escape Sequences  What if we wanted to print the quote character?  The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you.");  An escape sequence is a series of characters that represents a special character  An escape sequence begins with a backslash character () System.out.println ("I said "Hello" to you.");
  • 37. Goals //******************************************************************** // Roses.java Author: Lewis/Loftus // // Demonstrates the use of escape sequences. //******************************************************************** public class Roses { //----------------------------------------------------------------- // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("Roses are red,ntViolets are blue,n" + "Sugar is sweet,ntBut I have "commitment issues",nt" + "So I'd rather just be friendsntAt this point in our " + "relationship."); } }
  • 38. Goals //******************************************************************** // Roses.java Author: Lewis/Loftus // // Demonstrates the use of escape sequences. //******************************************************************** public class Roses { //----------------------------------------------------------------- // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("Roses are red,ntViolets are blue,n" + "Sugar is sweet,ntBut I have "commitment issues",nt" + "So I'd rather just be friendsntAt this point in our " + "relationship."); } } Output Roses are red, Violets are blue, Sugar is sweet, But I have "commitment issues", So I'd rather just be friends At this point in our relationship.