The document discusses different ways of implementing type conversion in Java. It covers widening and narrowing conversions, as well as assignment conversion, promotion, and casting. It provides examples of each type of conversion and discusses how conversions can occur during arithmetic expressions and assignments. It also covers wrapper classes and their role in type conversions.
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
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.
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.
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
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.