You are on page 1of 13

UET TAXILA

CLO Learning Outcomes Assessment Item BT Level PLO


No.

1 Construct the experiments / projects of Lab Task, Mid Exam, Final


varying complexities. Exam, Quiz, Assignment, P2 3
Semester Project

2 Use modern tool and languages. Lab Task, Semester Project P2 5

3 Demonstrate an original solution of Lab Task, Semester Project


A2 8
problem under discussion.

4 Work individually as well as in teams Lab Task, Semester Project A2 9

Lab Manual - 2
OOP
3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
Laboratory 2:
Lab Objectives: After this lab, the students should be able to

1. Understand Data Types and Wrapper Classes in Java


2. Understand Literals in Java
3. Perform Dynamic Initialization in Java
4. Perform Data Type Conversions
5. Type promotion in Java

1. Primitive Data Types:


A primitive type is predefined by the language and is named by a reserved keyword.

Each of these primitive types has a related class type, Long, Integer, Short and Byte defined in the
Java API package java.lang. These classes are called wrapper classes because they "wrap" a
primitive type with some useful methods. They also define class constants called MAX_VALUE and
MIN_VALUE, which store the maximum and minimum values for the corresponding primitive type.
To access a class constant dot the constant name with the name of the class.
ClassName.CONSTANT_NAME

In Java, our programs are all built from just a few basic types of data:

Examples:

public class Ex1 {


public static void main(String[] args) {
float values;
double doubles;
values = (float) (1.42222*234.56433);
doubles = 1.42222*234.56433;
System.out.println(values);
System.out.println(doubles);
}
}
Engr. Sidra Shafi Lab-2 1
3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
Output:

333.60208
333.6020814126

Note: Float store 6-7 significant digits and double store 15-16 significant digits.

Example (Wrapper Class):

public class MinMax {

public static void main(String[] args) {


//Program: MinMax.java prints the minimum and maximum values
// that can be stored in types byte, short, int and long

System.out.println(
"\nMinimum byte value: " + Byte.MIN_VALUE +
"\nMaximum byte value: " + Byte.MAX_VALUE);
}
}

Output:

Minimum byte value: -128


Maximum byte value: 127

Example (Wrapper Class):

public class Example{

public static void main(String[] args) {

Integer i = 68; //cannot use constructor here to assign value


Double d = 2.33;
Boolean b = false;
System.out.println(i);
System.out.println(d);
System.out.println(b);

}
}

Lab Exercise: Observe the output and use methods getClass and intValue(),
doubleValue and booleanValue() with these objects. Marks: 2

Integer wrapper class also have toString() method, so you can convert an int to a String.
// int conv=4 ;
Integer convert=3;
System.out.println("\n"+convert+ " String is " +convert.toString());

Let's say we have a String, which we know for sure contains a number. Regardless, there's no
native way to use a primitive int to extract the number from the String and convert it to a
number, but we can with the wrapper classes.

Engr. Sidra Shafi Lab-2 2


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java

String str = "1166628";

Integer i_str = Integer.parseInt(str);

System.out.println("int value is " +i_str);

Output:

Autoboxing/unboxing:
In Java, a feature of primitives and their wrappers is autoboxing/unboxing.

A wrapper variable can be assigned a primitive value. This process is called autoboxing.
Similarly, a primitive variable can be assigned a wrapper object. This process is called
unboxing. For example:

int x = 7;
Integer y = 111;
x = y; // Unboxing
y = x * 2; // Autoboxing
// y = x ; // Autoboxing also possible here
System.out.println("x is " +x + " and y is "+y);

Output:

x is 111 and y is 222

In line 3, we assign y, which is an Integer object, to the primitive x.

As you can see, we don't have to take any additional steps: the compiler knows that int and
Integer are, essentially, the same thing. That's unboxing.

Something similar is happening with autoboxing on line 4: the primitive value (x * 2) is


easily assigned to object y. This is an example of autoboxing.

That's why the term includes the word "auto": because you don't have to do anything
special to assign primitives to their corresponding wrapper objects (and vice versa). It
all happens automatically.

2. Literals in Java:
Integer Literal:

Integer literals create an int value, which in Java is a 32-bit integer value.

Example: int a = 100000, int b = -20000

Long Literal:

Engr. Sidra Shafi Lab-2 3


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
To specify a long literal, you will need to explicitly tell the compiler that the literal value is of type
long. You do this by appending an upper- or lowercase L to the literal.

Example: long a = 100000L, int b = -200000L

Note: Integer Literals can be assigned to short and byte variables if they are within their range. They
can also be assigned to Long Variables.

Floating-Point Literal:

Floating-point literals in Java default to double precision. To specify a float literal, you must append
an F or f to the constant.

Example: float f1 = 234.5f

Double Literal:

Double literals in Java can be explicitly specified by appending a D or d. Doing so, is redundant.

Example: double d1 = 123.4

Boolean Literal:

Boolean literals in Java can be specified by true and false. The true literal in Java does not equal 1,
nor does the false literal equal 0. In Java, they can only be assigned to variables declared as Boolean
or used in expression with Boolean operators.

Example: boolean one = true

Character Literal:

A character literal is represented inside a pair of single quotes. All the visible ASCII characters can be
directly entered inside the quotes, such as ‘a’,’z’, and ‘@’. For characters that are impossible to enter
directly, there are several escape sequences, which allow you to enter the character you need, such as
‘\” for the single-quote character itself, and ‘\n’ for the newline character. Java Character Literals are
16-bit (2-bytes) Unicode characters, ranging from 0 to 65535.

Example: char letterA ='A'

Example:
char c = 'a';
char A = '\u0041'; //'u0041' is unicode for capital A
char special_char = '@';
char leftSquareBracket = '\u005B'; //'u005B' is unicode for
left square bracket '['

System.out.println("The value of c is " +c);


System.out.println("The value of A is " +A);
System.out.println("The value of special-char is "
+special_char);
System.out.println("The value of leftSquareBracket is "
+leftSquareBracket);

Engr. Sidra Shafi Lab-2 4


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
Output:

Some Java Escape Sequences are given in Table 1.

An escape sequence is a series of characters that represents a special character.

Table 1: Escape Sequences


Escape Sequence Meaning
\t tab
\n newline
\” Double quote
\’ Single quote
\\ backslash

Getting the ASCII or Unicode value of a character is simple in Java. The char type is already an
integer type, so you can simply use it in most places that you would use an int. To print it out as an
integer (since characters are usually printed out as the character and not the integer value), simply cast
it into an int.

System.out.println((int)'A');
System.out.println((int)'B');
System.out.println((int)'C');
System.out.println((int)'a');
System.out.println((int)'b');
System.out.println((int)'c');

Output:

String Literal:

String literals in Java are specified by enclosing a sequence of characters between a pair of double
quotes.

Examples of string literals are:

"Hello World"
"two\nlines"
"\"This is in quotes\””

Engr. Sidra Shafi Lab-2 5


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
Types of variables

In Java, there are three types of variables:

1. Local Variables
2. Instance Variables
3. Static Variables

1. Local Variables are a variable that are declared inside the body of a method.
2. Instance variables are defined without the STATIC keyword. They are defined Outside a
method declaration. They are Object specific and are known as instance variables.
3. Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables.

Example:

class varT{
static int a = 1; //static variable
int data = 99; //instance variable
void method() {
int b = 90; //local variable
System.out.println("value of local variable b is : "+b);
}
}

3. Dynamic Initialization
If any variable is not assigned with value at compile-time and assigned at run time is called
dynamic initialization of a variable. You can initialize a variable dynamically at runtime
using constructors, setter methods, normal methods and API methods which returns values.

Using Built-In Methods to initialize a variable dynamically:

Java Math API has utility static methods that return values.

The java.lang.Math.addExact() is a built-in math function in java which returns the sum
of its arguments. It throws an exception if the result overflows an int.

The java.lang.Math.subtractExact() returns the difference of the arguments. It will throw


an exception if the result overflows either int or long.

Example:
public class DynamicInitialization {
public static void main(String[] args) {
int sum = Math.addExact(10, 20);
System.out.println("Sum : " + sum);

int sub = Math.subtractExact(20, 10);


System.out.println("Substract : " + sub);
}
}

In the above program, sum and sub-variables are initialized dynamically at runtime.
Engr. Sidra Shafi Lab-2 6
3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
Output:

Example:

//dynamic initialization
int a=4;
int cube = a * a * a;
System.out.println("cube : " + cube);

In above example variable cube is initialized at run time using expression a * a * a.

4. Data Types Conversions


The process of converting the value of one data type (int, float, double, etc.) to another data type is
known as typecasting.

Widening Type Casting:

In Widening Type Casting, Java automatically converts one data type to another data type.

public class WideningTypeC {


public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value: " + num);

// convert into double type


double data = num;
System.out.println("The double value: " + data);
}
}

Output:

Here, the Java first converts the int type data into the double type. And then assign it to
the double variable.

In the case of Widening Type Casting, the lower data type (having smaller size) is converted into the
higher data type (having larger size). Hence there is no loss in data. This is why this type of
conversion happens automatically.

Narrowing Type Casting:

In Narrowing Type Casting, we manually convert one data type into another using the parenthesis.

Engr. Sidra Shafi Lab-2 7


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
public class NarowingTypeC {
public static void main(String[] args) {
// create double type variable
double num = 10.99;
System.out.println("The double value: " + num);

// convert into int type


int data = (int)num;
System.out.println("The integer value: " + data);
} }
Output:

In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into
lower data types (having smaller size). Hence there is the loss of data. This is why this type of
conversion does not happen automatically.

Examples:
To understand data types, consider the following sample codes. Compile the following codes and
observe the outputs:

This program Light.java computes the number of miles that light will travel in a specified number of
days.

//computes distance light travels using long variables

a) Light.java

public class Light {


public static void main(String[] args) {
int lightspeed;
long days;
long seconds;
long distance;
//approximate speed of light in miles per second
lightspeed = 186000;
days=1000; //specify number of days here, also integer literals can be assigned to
long type variables directly.
seconds=days*24*60*60; //convert to seconds
distance=lightspeed*seconds;//compute distance
System.out.print("In " +days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles."); } }

Output:

Lab Exercise: In Light.java, declare distance as int type and see the results. Mark: 1

Engr. Sidra Shafi Lab-2 8


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
b) Chartest.java

//Demonstrates char data type.

class Chartest{
public static void main(String args[]){
char ch1,ch2;
ch1='A';
ch2= 75;
System.out.println("ch1 is: " +ch1);
ch1++;
System.out.println("ch1 is now: " +ch1);
System.out.println("ch2 is :" + ch2);
System.out.println("ch1 + ch2 =" + (ch1+ch2));
}

Output:

Type the following code in your editor and run it to observe the code.

c) Booltest.java

//Demonstrates Boolean data type.

class Booltest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);

// a boolean value can control the if statement


if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9)); } }

Output:

d) Conversion.java

Engr. Sidra Shafi Lab-2 9


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
//Demonstrate casts

class Conversion{
public static void main(String args[]){
byte b;
int i=257;
float f=4.4f;
double d=323.142;
System.out.println("\n Conversion of int to byte");
b=(byte)i;
System.out.println("i and b "+i+" "+b);
System.out.println("\n Conversion of float to int");
i = (int)f;
System.out.println("f and i "+f+" "+i);
System.out.println("\n Conversion of double to int");
i=(int)d;
System.out.println("d and i "+d+" "+i);
System.out.println("\n Conversion of double to float");
f = (float)d;
System.out.println("d and f "+d+" "+f);
System.out.println("\n Conversion of int to double");
d=i;
System.out.println("i and d "+i+" "+d);
System.out.println("\n Conversion of double to byte");
b=(byte)d;
System.out.println("d and b "+d+" "+b);
}
}

Output:

Lab Exercise: Is there method to convert double to int other than explicit type casting?
If yes, give an example. Mark: 1

Engr. Sidra Shafi Lab-2 10


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
Type Conversion from Int to String:
public class InttoString {
public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value is: " + num);

// converts int to string type


String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}
}

Output:

Here, we have used the valueOf() method of the Java String class to convert the int type
variable into a string.

5. Type Promotion in Java:


Type Promotion Rules:
i. All byte and short values are promoted to int.
ii. If one operand is long, the whole expression is promoted to long.
iii. If one operand is float, the whole expression is promoted to float.
iv. If any of the operands is double, the result is double.

e) Type Promotion Examples:


//Following examples show Type Promotion rules.

Example 1:
public class TypePromotion1 {
public static void main(String[] args) {
short a = 120;
byte b = 50;
//120*50 is promoted to int automatically
int c = a*b;
System.out.println(c);

int z = 4;
byte d = z * 5;
System.out.println(d);
}
}

Example 2:
public class TypePromotion2 {
public static void main(String[] args) {
short a = 120;
float b = 50.0f;
//120*50.0f is promoted to float automatically
float c = a*b;

Engr. Sidra Shafi Lab-2 11


3rdSemester Lab-2: Data Type Conversions & Type Promotions in Java
Java
System.out.println(c);

float d = 65;
System.out.println(d);
} }

Example 3:
public class TypePromotion3 {
public static void main(String[] args) {
short a = 120;
int b = 50;
double c = 1.0;
//120*50*1.0 is promoted to double automatically
//short * int * 1.0 == double
double e = a*b*c;
System.out.println(e);

double f = 35*1.0;
//35*1.0 => int * double == double
System.out.println(f);

double g = 40;
//40 is converted to double
System.out.println(g); } }

LAB TASKS and LAB EXERCISES: Total Marks: 1

1. Write a Java program to calculate the total cost of travelling in dollars (int) from
first city to second city. Marks: 3

Input:
Declare some variables to store the following.
• Starting city name (String),
• Ending city name (String),
• Distance in miles between cities (int),
• Cost of travel per mile (float).

Expected Output: Total cost of travelling in dollars must be an int value.

2. Create an ArrayList of Integers and add 3 int values in it using add() method and
then print this ArrayList. It is in Java.util Package. Marks: 3

**************

Engr. Sidra Shafi Lab-2 12

You might also like