• Tidak ada hasil yang ditemukan

Type Conversion and Casting

N/A
N/A
Protected

Academic year: 2018

Membagikan "Type Conversion and Casting"

Copied!
41
0
0

Teks penuh

(1)

Lecture Three

Type Conversion and Casting

Introduction to Class

(2)

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.

(3)

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

(4)

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;

(5)

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); }

(6)

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

(7)

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.

(8)

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.

(9)

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;

(10)

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

(11)

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

(12)

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

(13)

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

(14)

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;

(15)

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 }

(16)

Class and Object

A class defines a new data type. This new data type is

used to create objects of that type.

(17)

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.

(18)

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;

(19)

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

(20)

A Simple Example- Some points

(21)

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

(22)

References

An reference variable holds the memory address.

It is similar to the pointer.

(23)

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

(24)

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

(25)

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:

(26)

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:

(27)

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:

(28)

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.

(29)

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

(30)

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);

(31)

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

(32)

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); }

(33)

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

(34)

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.

(35)

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

(36)

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.

(37)

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); }

(38)

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

(39)

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(); }

(40)

Chapter 3 – Type casting

Chapter 6 - Class

Chapter 18—Scanner Class

(41)

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.

Referensi

Dokumen terkait

Tanaman yang tumbuh pada lingkungan yang kaya akan unsur hara, H2O, CO2, dan cahaya mempunyai kapasitas fotosintesis yang jauh lebih tinggi dari pada

Fungsi trigonometri merupakan fungsi yang periodik, artinya pada selang sudut tertentu nilai fungsi itu akan berulang

Menganalisa deteksi tepi dengan menggunakan beberapa operator deteksi untuk mengetahui metode mana yang lebih baik dalam mendeteksi tepi suatu citra pada kain batik secara

Based on the results of an interview with one of the students majoring in Electrical Engineering Faculty of Engineering, State University of Padang, before getting a letter they

h) Melalui media gambar dan penjelasan dari guru, siswa mampu menjelaskan proses pencernaan pada manusia. i) Melalui kerja sama kelompok,siswa mampu mengurutkan gambar

seluruh aspek perusahaan yang dikenal dengan sistem manajemen mutu terpadu (TQM). PT XYZ merupakan salah satu perusahaan manufaktur roti dengan

Setelah diteliti dan dibahas maka didapatkan hasil penelitian, yaitu pada kelas eksperimen rata-rata kecepatan membaca siswa berubah dari 144 kpm saat pretes menjadi 149 kpm

karena setiap biaya yang dikeluarkan perusahaan akan mempengaruhi laba. yang diperoleh, dengan dilakukannya pertimbangan tersebut maka