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

SE241: Advanced Computer Programming: Lecture # 02: Diving in (Advancing On Basics)

This document provides an overview of primitive data types in Java, including integers, floating-point numbers, characters, and booleans. It discusses the scope and lifetime of variables, and type conversion and casting. The key primitive data types in Java are defined as byte, short, int, long, char, float, double, and boolean. Variables are created when their scope is entered and destroyed when their scope is left. Type conversion between incompatible types requires an explicit cast.

Uploaded by

hazrat ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

SE241: Advanced Computer Programming: Lecture # 02: Diving in (Advancing On Basics)

This document provides an overview of primitive data types in Java, including integers, floating-point numbers, characters, and booleans. It discusses the scope and lifetime of variables, and type conversion and casting. The key primitive data types in Java are defined as byte, short, int, long, char, float, double, and boolean. Variables are created when their scope is entered and destroyed when their scope is left. Type conversion between incompatible types requires an explicit cast.

Uploaded by

hazrat ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

SE241: Advanced Computer

Programming
Lecture # 02: Diving In (Advancing on Basics)

Muhammad Imran
(Based on Java, The Complete Reference)
http://www.secscourses.tk

1
Outline
• The Primitive Data Types
• The Scope and Lifetime of Variables
• Type Conversion and Casting
• Automatic Type Promotion in Expressions

2
The Primitive Data Types
• Java defines eight primitive types of data: byte, short, int,
long, char, float, double, and boolean.
• These can be put in four groups:
 Integers
• This group includes byte, short, int, and long
• Whole-valued signed numbers
 Floating-point numbers
• This group includes float and double
• Numbers with fractional precision

3
The Primitive Data Types
 Characters
• This group includes char
• Represents characters in a character set, like letters and numbers
 Boolean
• This group includes boolean
• Special type for representing true/false values

4
Integers
• Four integer types:
 byte, short, int, and long
• All of these are signed
 Positive and negative values
 Java doesn’t support unsigned (positive-only) integers
• The width of an integer type
 Refers to the behavior it defines for variables and expressions of that type
 It should not be thought of as the amount of storage it consumes
• The java runtime environment
 is free to use whatever size it wants
 as long as the types behaves as are declared.

5
Integers

Name Width Range

long 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 -2,147,483,648 to 2,147,483,647

short 16 -32,768 to 32,767

byte 8 -128 to 127

6
Example
// Compute distance light travels using long variables.
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
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.");//16070400000000
} Output
} In 1000 days light will travel about 16070400000000 miles. 7
Floating-Point Types
• Floating-point numbers are also called real numbers.
• Used when evaluating expressions that require fractional
precision.
• There are two kinds of floating-point types, float and
double, which represent single and double precision
numbers, respectively.

8
Floating-Point Types

Name Width Range

double 64 1.7e-308 to
1.7e+308

float 32 3.4e-038 to
3.4e+038

9
Example
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}

10
Characters
• The data type used to store characters is char.
• Java uses Unicode to represent characters.
• Unicode defines a fully international character set that can
represent all of the characters found in all human
languages.
• For this purpose, it requires 16 bits.
• The range of char is 0 to 65,536.
• There are no negative chars.

11
Example
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
} Output
ch1 and ch2: X Y

12
Example
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
} Output
ch1 contains X
ch1 is now Y
13
Booleans
• The type boolean is used for logical values.

• It can be either true or false.

• This is the type returned by all relational operators, such


as a<b.

• boolean is also the type required by the conditional


expressions that govern the control statements such as if
and for.

14
Example
// Demonstrate boolean values. Output
class BoolTest { b is false
public static void main(String args[]) { b is true
boolean b;
This is executed.
b = false;
System.out.println("b is " + b); 10 > 9 is true
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));
}
} 15
Boolean Literals
• There are only two logical values that a boolean value can
have
 true

 false

• The values of true and false do not convert into any


numerical representation, such as 1 or 0.

16
Integer Literals
• Beginning with JDK 7, you can also specify integer literals
using binary. To do so, prefix the value with 0b or 0B.

int x = 0b1010; // means 10 in decimal

• You can embed one or more underscores in an integer


literal for readability of large integer literals.

• When the literal is compiled the underscores are


discarded.

int x = 123_456_789; 17
The Scope and Lifetime of Variables

• All variables have a


 scope, which defines their visibility
• A code block defines a scope

• A scope determines what objects are visible to other parts of the program

 and a lifetime
• lifetime of a variable is confined to its scope

18
The Scope of Variables
• Objects declared in the outer scope will be visible to code within
the inner scope.

• However, the reverse is not true.

• Objects declared within the inner scope will not be visible outside
it.

19
Example: Scope of Variables
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
20
The Scope of Variables
• Variables are created when their scope is entered, and
destroyed when their scope is left.

• Lifetime of a variable is confined to its scope.

• Although blocks can be nested, we cannot declare a


variable to have the same name as one in an outer
scope.

21
Example
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{// creates a new scope
int bar = 2; //Compile time error, bar already defined!
}
}
}

22
Type Conversion and Casting
• It is common to assign a value of one type to a variable of another
type.
• If the two types are compatible, then Java will perform the
conversion automatically.
• For example, it is always possible to assign an int value to a long
variable.
• However, not all types are compatible.
• Thus, not all type conversions are implicitly allowed.
• For instance, there is no conversion defined from double to byte.

23
Type Conversion and Casting
• Fortunately, it is still possible to obtain a conversion
between incompatible types.

• To do so, we must use a cast.

• A cast performs an explicit conversion between


incompatible types.

24
Automatic Conversions
• 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.
• When these two conditions are met. A widening
conversion takes place.
 For example, the int type is large enough to hold all valid byte
values

25
Automatic Conversions
• For widening conversions, the numeric types, including
integer and floating point types, are compatible with each
other.
• However, the numeric types are not compatible with char
or boolean.
• Also, char and boolean are not compatible with each
other.
• Java also performs an automatic type conversion when
storing a literal integer constant into variables of type
byte, short, or long.

26
Casting Incompatible Types
• If we 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 called a narrowing conversion.
• To create a conversion between two incompatible types,
we must use a cast.
• General form of cast is:
 (target-type) value

27
Casting Incompatible Types
• If the integer’s value is larger than the range of a byte, it
will be reduced modulo (the remainder of an integer
division by) the byte’s range.

int a;
byte b;
// ...
b = (byte) a;

28
Casting Incompatible Types
• Truncation
 A different type of conversion will occur when a floating-point
value is assigned to an integer type.
 When a floating-point value is assigned to an integer type, the
fractional component is lost.
 For example, if the value 1.23 is assigned to an integer, the
resulting value will simply be 1.
 Also, if the size of the whole number component is too large to
fit into the integer type, then that value will be reduced modulo
the target type’s range.

29
Example: Casting Incompatible Types
// Demonstrate casts. Output
class Conversion { Conversion of int to byte.
public static void main(String args[]) { i and b 257 1
byte b; Conversion of double to int.
int i = 257; d and i 323.142 323
double d = 323.142;
System.out.println("\nConversion of int to byte."); Conversion of double to byte.
d and b 323.142 67
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);
}
} 30
Automatic Type Promotion in Expressions

• In addition to assignment, there is another place where


certain type conversions may occur.

• In an expression, the precision required of an intermediate


value will sometimes exceed the range of either operand.

31
Automatic Type Promotion in Expressions
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.
• Java automatically promotes each byte, short or char operand to int
when evaluating an expression.
• Sub-expression a*b is performed using integers.

32
Automatic Type Promotion in Expressions
• Automatic promotions can cause confusing compile time errors.
 byte b = 50;
 b = b * 2; // Error! Cannot assign an int to a byte!
• The code is attempting to store 50*2, a perfectly valid byte value,
back into a byte variable.
• However, because of automatic promotion of operands to int, the
result has also been promoted to int.
• The result is now int, which cannot be assigned to a byte without
the use of a cast.

33
Automatic Type Promotion in Expressions

byte b = 50;

b = (byte)(b * 2);

• This cast is needed even, as in this case, the value being


assigned can easily fit in the target type.

34
The Type Promotion Rules
• Java defines several type promotion rules that apply to
expressions.
 All byte, short and char values are promoted to int.
 If one operand is a long, the whole expression is promoted to
long.
 If one operand is a float operand, the entire expression is
promoted to float.
 If any of operands is a double, the result is double.

35
Example: The Type Promotion Rules
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;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
36
Example: The Type Promotion Rules
double result = (f * b) + (i / c) - (d * s);

• In f*b, b is promoted to a float


• In i/c, c is promoted to int
• In d*s, the value of s is promoted to double
• The outcome of float plus an int is a float.
• Then the resultant float minus the last double is
promoted to double, which is the type for the final
result of the expression.
37
Recommended Reading
• Page # 35 to 51, Chapter # 3: Data Types, Variables, and
Arrays from Herbert Schildt, Java: The Complete
Reference, J2SETM 9th Edition

38

You might also like