Lecture Three
Type Conversion and Casting
Introduction to Class
Automatic Type Conversion
When one type of data is assigned to another type of variable, an automatic type conversion will take place if:
1. Two types are compatible.
2. The destination type is larger than the source type.
It is known as widening conversion.
The numeric types, including integer and floating point types are compatible.
Automatic Type Conversion
short’s variable = byte’s variable
int’s variable = byte’s variable
byte’s variable = int’s variable
float’s variable = int’s variable
int’s variable = float’s variable
double’s variable = float’s variable
float’s variable = double’s variable
char’s variable = any other variable
int’s variable = char’s variable
short’s variable = char’s variable
boolean variable = any other variable
Any other variable = boolean variable
Casting Type
Problem: assigning int value to a byte type variable.
This type of conversion is known as narrowing conversion.
A cast is simply an explicit type conversion : (target_type) value
Example:
int a; byte b; ….
b = (byte) a;
Casting Type
class test {
public static void main(String args[]) {
byte b; int i = 257;
double d = 323.142; b=(byte)i;
System.out.println (“Conversion of int to byte: ” + i +” “+ b); i = (int)d;
System.out.println(“Conversion of double to int: “ +d+” “+i); b=(byte)d;
System.out.println(“Conversion of double to byte: “ +d+” “+b); }
Casting Type
Output:
Conversion of int to byte: 257 1
Conversion of double to int: 323.142 323
Conversion of double to byte: 323.142 67
Note:
When assigning a fractional number’s to a whole number’s variable, fractional part is truncated.
If the value of the whole number part is too large to fit into the
Automatic Type Promotion in Expression
Takes place in expression.
Rules:
1. All byte and short values are promoted to int.
2. If one operand is long, the whole expression is promoted to long.
3.If one operand is float, the entire expression is promoted to float.
Automatic Type Promotion-Example
byte b =42; char c=‘a’; short s=1024; int i=50000; float f=5.67f; double d=.1234;
double result = (f * b) + (i / c) – (d * s); 1. (f * b) is promoted to float.
2. (i / c) is promoted to int.
3. (d *s ) is promoted to double.
Automatic Type Conversion-Example
1. byte a =40, b= 50, c =100;
int d = a * b /c;
2. byte b =50;
b = b * 2; //Error
3. byte b =50;
An Example of Object Oriented
Programming
Colored points on the screen
What data goes into making one?
Coordinates
Color
What should a point be able to do?
Move itself
My x: 5 My y: 20
My color: black Things I can do: move report x report y
My x: 20 My y: 10
My color: dark g rey Things I can do: move report x report y
My x: 17 My y: 25
Java Terminology
Each point is an
object
Each includes three
fields
Each has three
methods
Each is an
instance
of the same
class
My x: 10 My y: 50
Object-Oriented Style
Solve problems using objects: little bundles of data
that know how to do things to themselves
Not the computer knows how to move the point, but
rather the point knows how to move itself
class Point { int xCoord; int yCoord; Point() {
xCoord = 0; yCoord = 0; }
int currentX() {
return xCoord; }
int currentY() {
return yCoord; }
void move (int newXCoord, int newYCoord) {
xCoord = newXCoord; yCoord = newYCoord;
The General Form of a Class
A class is defined by specifying the data and the code that operate on the data.
The general form: class classname{
type instance-variable1; type instance-variable2; …………
type methodname1( parameter-list) {
// body of the method }
type methodname2( parameter-list) {
//body of the method }
Class and Object
A class defines a new data type. This new data type is
used to create objects of that type.
Creating Objects
Obtaining objects of a class is two steps process:
1. Declare a variable of the class type.
2. Acquire an actual, physical copy of the object and
assign it to that variable.
To allocate a physical memory
new()
is used. It
dynamically allocates memory for an object and
returns a reference to it.
A Simple Example
class Box { double width; double height; double depth; } class BoxDemo {public static void main( String args[]) {
Box mybox, mybox1; mybox = new Box(); mybox1 = new Box();
mybox.width=10; mybox.height = 20; mybox. depth = 15;
A Simple Example- Some points
Members are linked to an object using dot (.)
operator.
Each object contains its own copy of each instance
variables defined by the class.
The java compiler automatically puts each class into
it’s own
.class
file.
- For this example, two .class files:
1. Box.class
A Simple Example- Some points
A Closer Look at New
Box mybox;
mybox = new Box();
Box b1 = new Box();
Box b2 = b1;
null mybox
mybox
Width
Height
Depth Call to the default constructor defined
by the compiler. It initializes the instance variables to 0.
Width
Height
Depth b1
References
An reference variable holds the memory address.
It is similar to the pointer.
The null Reference
An object reference variable that does not currently point to an object is called a null reference
The reserved word null can be used to explicitly set a null reference:
name = null;
An object reference variable declared at the class level (an instance variable) is automatically initialized to null
Instance variables
Default initialization
If the variable is within a method, Java does NOT
initialize it.
If the variable is within a class, Java initializes it as
follows:
Numeric instance variables initialized to 0
Logical instance variables initialized to false
Import Statement
A java package is a collection of related classes.
In order to access the available classes in the package, the
program must specify the complete dot seperated package path.
The general format:
import package-level1.[package-level2.]classname|*
Two form of import statement: 1. import.package.class;
2. import package.*; Example:
Example
import java.util.Random;
class random {
public static void main(String args[]) {
Random r = new Random(); int i; float v; for(i=0;i<5;i++) { v=r.nextFloat(); System.out.println(v); } } } Output:
Predefined Stream
Stream:
-A stream is an abstraction that either produces or consumes information.
-It is linked to a physical device by a java I/O system.
-The hide the details of the physical device to which they are connected.
System:
-System is a predefined class included in the package java.lang.
(Imported automatically by all java programs). -It includes three predefined stream variables:
The Predefined Streams
1. System.out: refers to the standard output stream. It is an object of type PrintStream.
2. System.in: refers to the standard input stream. It is an object of type InputStream.
3. System.err: refers to the standard error stream. It is an object of type PrintStream.
Note: they are defined as public and static.
InputStream:
- This class in included in the package java.io.
- It has some subclasses the handle the differences between various devices.
Scanner Class
Scanner class is used to read input from the keyboard, a file, a string or any source that implements the Readable or ReadByteChannel.
Scanner can be created for a string, an InputStream, or any object that implements Readable or ReadByteChannel interface.
Scanner class is under the package of java.util
Added in J2SE 5.
Readable Interface:
It is added by J2SE.
It is included in Java.lang.
It defines one method:
int read(CharBuffer buf) throws IOException
Taking Input from the Keyboard
First, Scanner class is connected to System.in
which is an object of type InputStream.
Then, it uses it’s internal functions to read
from System.in
Example:
Scanner test = new Scanner(System.in);
Take an input from the keyboard-1
import java.util.*;
public static void main(String[] args) { int value;
System.out.print(“Enter an Integer number:");
Scanner tmp = new Scanner(System.in);
if(tmp.hasNextInt()) {
value=tmp.nextInt();
System.out.println(“You have entered: ”+value); }
else
Taking Input from the KeyBoard-2
import java.util.*; class input
{
public static void main(String args[]) {
Scanner tmp = new Scanner(System.in); float i;
while(tmp.hasNextFloat()) {
i=tmp.nextFloat();
System.out.println("The Number: ",i); }
Scanning Basics
A Scanner reads tokens from the underlying source.
A token is a portion of input that is delineated by a set of delimiters, which is by default whitespace.
A token is read by matching it with a particular regular expression.
Scanner follow the procedure below:
1. Determine if a specific type of input is available by calling one of the
hasNextX methods.
2. If input is available, read it by calling one of nextX method. 3. Repeat the process until the input is exhausted.
Note: if nextX() method does not find a matching token, it throws a
Important Methods of Scanner Class
public Scanner(InputStream in) // Scanner(): convenience constructor for an InputStream object
boolean hasNext() //Return true if another token of any type is available to be read.
boolean hasNextBoolean() //Return true if a boolean value is available to read.
boolean hasNextByte() //Return true if a byte value is available to read.
boolean hasNextShort() //Return true if a byte value is available to read.
boolean hasNextInt() //Return true if a int value is available to read.
boolean hasNextLong() //Return true if a long value is available to read.
boolean hasNextFloat() //Return true if a float value is available to read.
Important Methods of Scanner Class
int nextInt() // return next token as int value.
short nextShort() // return next token as short value.
byte nextByte() // return next token as byte value.
long nextLong() // return next token as long value.
double nextDouble() // return next token as double value
float nextFloat() // return next token as float value
String next() //return next token of any type from the input source
Taking Input from the File
The following lines read data from a file:
FileReader fin = new FileReader(“c:\\f_input.txt”); Scanner test = new Scanner(fin);
FileReader:
- belongs to java.io package.
-It creates an object that can read the content of a file.
Taking Input from the File
import java.io.*; import java.util.*;
class file_input {
public static void main(String args[]) throws IOException {
double i; String str;
FileReader fin = new FileReader("c:\\f_input.txt"); Scanner test = new Scanner(fin);
while(test.hasNext())
{
if(test.hasNextDouble())
{
i=test.nextDouble();
System.out.println("The number is:" + i); }
else {
str = test.next();
System.out.println(str); }
Taking Input from a File
Suppose the file contains the following data: 2 3.4 5 6 7.4 9.1 10.5 done
Output:
The number is: 2.0 The number is: 3.4 The number is: 5.0 The number is: 6.0 The number is: 7.4 The number is: 9.1 The number is: 10.5 done
Writing Data into a File
import java.io.*;
class test {
public static void main (String args[]) {
FileWriter fout = new FileWriter(“c:\\test1.txt”); fout.write(“2 3.4 5 6 7.4 9.1 10.5 done”);
fout.close(); }
Chapter 3 – Type casting
Chapter 6 - Class
Chapter 18—Scanner Class
Homework (Math Library)
Suppose you are given the following
double a=56.34, b=6.58334, c=-34.4265;
Calculate the following value: Print a random number.
Find the absolute value of the variable c
Find the square root of a
Find the maximum value between a and b
Calculate the value ab
Round the number a
Calculate the value of √(a2+b2)
Find the floor, ceil and round value of b and c
Find the radian value of a.