SlideShare una empresa de Scribd logo
1 de 38
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.

Más contenido relacionado

La actualidad más candente

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 summaryEduardo 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.netJaya Kumari
 
Lecture#08 sequence diagrams
Lecture#08 sequence diagramsLecture#08 sequence diagrams
Lecture#08 sequence diagramsbabak 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 REDDYRajeshkumar Reddy
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And UnionsDhrumil Patel
 
The Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram TutorialThe Ultimate Sequence Diagram Tutorial
The Ultimate Sequence Diagram TutorialCreately
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programmingnmahi96
 
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 argumentsKuntal Bhowmick
 
Intro to tsql unit 11
Intro to tsql   unit 11Intro to tsql   unit 11
Intro to tsql unit 11Syed Asrarali
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programmingnmahi96
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of CSuchit Patel
 

La actualidad más candente (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
 

Destacado

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

Destacado (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 a Chapter 3.4

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 IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
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 3Mohamed Essam
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access PrinciplePhilip Schwarz
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2ppJ. C.
 
2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdf2.Types_Variables_Functions.pdf
2.Types_Variables_Functions.pdfTrnThBnhDng
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxDeepasCSE
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Nettjunicornfx
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdfPowerfullBoy1
 

Similar a 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
 

Más de sotlsoc

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

Más de 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
 

Último

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 

Último (20)

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.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.