0% found this document useful (0 votes)
4 views

oop3

This document covers Java type casting, type promotion, and control statements through various tasks and examples. It explains automatic conversions, explicit casting, and provides programming tasks related to type conversions, expressions, and a Rock, Paper, Scissors game. Additionally, it includes questions and answers to reinforce understanding of implicit vs explicit casting and type promotion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

oop3

This document covers Java type casting, type promotion, and control statements through various tasks and examples. It explains automatic conversions, explicit casting, and provides programming tasks related to type conversions, expressions, and a Rock, Paper, Scissors game. Additionally, it includes questions and answers to reinforce understanding of implicit vs explicit casting and type promotion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

JAVA TYPE CASTING, TYPE

PROMOTION & CONTROL


STATEMENTS
Lab-03
LAB 03 Casting, Type Promotion and Control Statements
Lab Objectives:
1. Understand Java type casting and type promotion
Understanding java control statements

Software Required:
JDK & Notepad/ Textpad

Java’s Automatic Conversions


When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are met:

• The two types are compatible.

• The destination type is larger than the source type.

Example:
int i = 3;
double d;
d = i; //no Explicit type casting required

TASK 1: Write a program which does following conversions and prints the
result. Observe the output.
int i = 3;
double d;
d = i; // OK, no explicit type casting required
// d = 3.0
d = (double) i; // Explicit type casting operator used here
double aDouble = 55; // Compiler auto-casts int 55 to double 55.0
double nought = 0; // Compiler auto-casts int 0 to double 0.0
// int 0 and double 0.0 are different.

Casting Incompatible Types


Although the automatic type conversions are helpful, they will not fulfill all needs. For example,
what if you want to assign an int value to a byte variable? This conversion will not be performed
automatically, because a byte is smaller than an int. This kind of conversion is sometimes called
a narrowing conversion, since you are explicitly making the value narrower so that it will fit into
the target type. To create a conversion between two incompatible types, you must use a cast. A
cast is simply an explicit type conversion. It has this general form:
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion. It has this general form:
(target-type) value

TASK 2: Implement and study the following code


// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
TASK 3: Run and observe the output of following code

TASLK 4: Convert Fahrenheit to Celsius


C= (F-32.0)*(5/9);

TASK 5: Write a Java program to compute body mass index (BMI).


Formula: BMI = weight * 0.45359237 / (inches * 0.0254 * inches * 0.0254)
Test Data
Input weight in pounds: 452
Input height in inches: 72

Expected Output:
Body Mass Index is 61.30159143458721

Automatic Type Promotion in Expressions


In addition to assignments, there is another place where certain type conversions may occur: in
expressions. To see why, consider the following. In an expression, the precision required of an
intermediate value will sometimes exceed the range of either operand. For example, examine the
following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte operands.
To handle this kind of problem, Java automatically promotes each byte, short, or char operand to
int when evaluating an expression.

TASK 6: Implement and study the following program.


class Promote {
public static void main (String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
……… result = (f * b) + (i / c) - (d * s); //identify the datatype of result
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

TASK 7: Program Rock.java contains a skeleton for the game Rock, Paper,
Scissors. Open it and save it to your directory. Add statements to the program
as indicated by the comments so that the program asks the user to enter a play,
generates a random play for the computer, compares them and announces the
winner (and why). For example, one run of your program might look like this:
$ java Rock
Enter your play: R, P, or S
r
Computer play is S
Rock crushes scissors, you win!

Use a switch statement to convert the randomly generated integer for the computer's play to
a string.

// ****************************************************************
// Rock.java
//
// Play Rock, Paper, Scissors with the user
//
// ****************************************************************
import java.util.Scanner;
import java.util.Random;
public class Rock
{
public static void main(String[] args)
{
String personPlay; //User's play -- "R", "P", or "S"
String computerPlay; //Computer's play -- "R", "P", or "S"
int computerInt; //Randomly generated number used to determine
//computer's play
Scanner scan = new Scanner(System.in);
Random generator = new Random();
//Get player's play -- note that this is stored as a string
//Make player's play uppercase for ease of comparison
//Generate computer's play (0,1,2)
//Translate computer's randomly generated play to string
switch (computerInt)
{
}
//Print computer's play
//See who won. Use nested ifs instead of &&.
if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else
//... Fill in rest of code
}
}

QUESTIONS
Please Fill the blank space with respective answers to following questions:
Question 1: What is different between implicit and explicit type casting?
Implicit type casting is automatic and performed by the compiler without explicit indication, while
explicit type casting requires the programmer to specify the conversion explicitly.

Question 2: Explain each output in TASK 3 one by one in your own words.

1. myInt/5 gives: 24 • Explanation: Integer division, 123 divided by 5 is 24.

2. myInt%5 gives: 3 • Explanation: Modulus operation, remainder of 123 divided by 5 is 3.

3. myDouble/5 gives: 24.6 • Explanation: Division involving a double, 123.0 divided by 5


is 24.6.

4. myInt/5.0 gives: 24.6 • Explanation: Division involving a double, 123 divided by 5.0 is
24.6.

5. Converting string to int: 123


Explanation: Successfully converts the string "123" to an int.

Explanation: Throws a NumberFormatException since " Hello World! " is not a valid
integer. The Integer.parseInt() method expects a string containing a valid integer, and
attempting to parse a non-numeric string results in an exception.

6. Exception in thread "main" java.lang.NumberFormatException: For input


string: " Hello World! "

Question 3: Explain type promotion in your own words


type promotion refers to the automatic conversion of data types to wider or larger
types in expressions or operations involving multiple data types. It occurs when
smaller or narrower data types are implicitly converted to larger or wider types to
avoid loss of precision or to ensure consistent handling of data.

For example, if you perform an operation involving an integer and a floating-point


number, the integer will typically be promoted to a floating-point number before
the operation is carried out to ensure that the result maintains the higher precision
of the floating-point type.
Type promotion helps maintain consistency in operations and prevent data loss by
promoting smaller data types to larger ones when necessary, ensuring that

calculations are performed accurately and efficiently.


Question 4: Draw Flow chart for rock paper scissors game.

THE END

You might also like