Sie sind auf Seite 1von 32

COMP2111

Object Oriented Programming

Unit 1: Basic of Object


Oriented Programming (Part 5)

1
Contents for Today’s Lecture

• Working with Java Data Types

2
Identifier, Variable, Constant
• Identifier is a name that we associate with some program
entity (class name, variable name, parameter name, etc.)
• Java Identifier Rule:
– May consist of letters (‘a’ - ‘z’, ‘A’ - ‘Z’), digit characters (‘0’ - ‘9’),
underscore (_) and dollar sign ($)
– Cannot begin with a digit character
• Variable is used to store data in a program
– A variable must be declared with a specific data type
– E.g.: int countDays, $total, _total, total5;
double priceOfItem;

• Constant is used to represent a fixed value


– Eg: public static final int PASSING_MARK = 50;
• Keyword final indicates that the value cannot change
3
Guidelines on how to name classes,
variables, and constants:
Class name: UpperCamelCase
Eg: Math, HelloWorld, ConvexGeometricShape

Variable name: LowerCamelCase


Eg: countDays, innerDiameter, numOfCoins

Constant: All uppercase with underscore


Eg: PI, CONVERSION_RATE, CM_PER_INCH

4
Comments

Java supports three types of comments:

5
Primitive Data Types
• A data type is essentially a name given to certain kind of data.
• Java has two fundamental kinds of data types:
– Primitive Data Types:
• Numeric Data Types
– Integral Data Types (byte, char, short, int, long)
– Floating Point Data Types (float, double)
• Boolean Data Type
– boolean
– Reference Data Types:
• Classes
• Interfaces
• Enums
• String

6
Primitive Data Types
 Primitive data types are designed to be used when you are
working with raw data such as integers, floating point numbers,
characters, and booleans.

 Java (by Java, I mean, the Java compiler and the Java Virtual
Machine) inherently knows what these data types mean, how
much space they take up, and what can be done with them. You
don’t need to explain anything about them to Java.

 Primitive data types are the most basic building blocks of a Java
program. You combine primitive data types together in a class to
build more complicated data types.

7
Reference Data Types
 Reference data types, on the other hand, are designed to be used
when you are working with data that has a special and unique
meaning for code that Java has no knowledge of.
 For example, if you are developing an application for student
management, you might define entities such as Student, Course,
and Grade. Java has no knowledge of what Student, Course, and
Grade mean. It doesn’t know how much space they take, what
operations they support, or what properties they have. Java will
expect you to define all these things. Once you define them, you
can use them to implement the business logic of your
application. When you write a class, interface, or enum, you
are essentially defining a reference data type.
 Reference data types are built by combining primitive data types
and other reference data types.
8
Data Types
Data Type Default Size Range Default Value
boolean 1 bit true or false false
char 2 bytes 0 to 216-1 or '\u0000‘ to '\uffff‘ '\u0000'
i.e. 0 to 65,535
byte 1 byte -27 to 27-1 or -128 to 127 0
short 2 bytes -215 to 215-1 or -32,768 to 32,767 0
int 4 bytes -231 to 231-1 0
long 8 bytes -263 to 263-1 0L
float 4 bytes approximately 0.0f
±3.40282347E+38F
(6-7 significant decimal digits)
double 8 bytes approximately 0.0d
±1.79769313486231570E+308
(15 significant decimal digits)
String - null
9
A word on void
 void is a keyword in Java and it means “nothing”.
 It is used as a return type of a method to signify that the method
never returns anything.
 In that sense, void is a type specification and not a data type in
itself.
 That is why, even though you can declare a method as returning
void but you cannot declare a variable of type void.

10
Difference between null and void
 null is also a keyword in Java and means “nothing”. However,
null is a value. It is used to signify that a reference variable is
currently not pointing to any object. It is not a data type and so, it
is not possible to declare a variable of type null.
 Note that null is a valid value for a reference variable while void
is not. In other words, return null; can be a valid return statement
for a method but return void; is never valid.
 A method that declares void as its return type, can either omit the
return statement altogether from its body or have an empty return
statement, i.e., return;

11
Difference between reference variables and
primitive variables

 In the case of a reference variable, the JVM interprets


the number as an address of another memory location
where the actual object is stored, but in the case of a
primitive variable, it interprets the raw number as a
primitive data type.

12
Difference between reference variables and primitive variables
public class Student{
int id;
}

13
Uninitialized variables and Default values
Try compiling the following code:
public class TestClass{
static int i;
int y;
public static void main(String[] name){
int p;
}
}

It compiles fine without any issues. It will run fine as well but
will not produce any output.
Java doesn’t have a problem if you have uninitialized variables
as long as you don’t try to use them. That is why the above code
compiles even though the variables have not been initialized.

14
Uninitialized variables and Default values
Now, try the same code with a print statement that prints i and y.
public class TestClass{
static int i;
int y;
public static void main(String[] name){
int p;
System.out.println(i+" "+new TestClass().y);
}
}

This also compiles fine. Upon running, it will print 0 0.


Java initializes static and instance variables to default values if
you don’t initialize them explicitly. That is why the above code
prints 0 0.

15
Uninitialized variables and Default values
Now, try the following code that tries to print p.
public class TestClass{
static int i;
int y;
public static void main(String[] name){
int p;
System.out.println(p);
}
}

This doesn’t compile. You will get an error message saying:


variable p might not have been initialized
Java doesn’t initialize local variables if you don’t initialize them
explicitly and it will not let the code to compile if you try to use
such a variable. That is why the third code doesn’t compile.
16
Type Conversion and Casting
• Automatic Type Conversion:
– Also called Widening Conversion or Implicit Type
Conversion or Promotion
– Take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
• Casting Incompatible Types:
– Also called Narrowing Conversion or Explicit Type
Conversion or Demotion
– If the source type is larger than the target type, explicit
type casting is needed

17
Type Casting
Conversion mistake

18
Automatic Type Conversion or Widening
Casting
Widening casting is done automatically when
passing a smaller size type to a larger size type:

public class MyClass{


public static void main(String[] args){
int i = 9;
double d = i; //Automatic casting: int to double
System.out.println(i); //Outputs 9
System.out.println(d); //Outputs 9.0
}
}

19
Narrowing Casting
Narrowing casting must be done manually by
placing the type in parentheses in front of the
value:

public class MyClass{


public static void main(String[] args){
double d = 9.78;
int i = (int) d; //Truncation: double to int
System.out.println(d); //Outputs 9.78
System.out.println(i); //Outputs 9
}
}

20
Casting Example

// Demonstrate casts
class MyClass {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
b = (byte) i;
System.out.println(i + " " + b);
i = (int) d;
System.out.println(d + " " + i);
b = (byte) d;
System.out.println(d + " " + b);
}
}

21
Casting Example
This program generates the following output:

257 1
323.142 323
323.142 67
Let’s look at each conversion.
When the value 257 is cast into a byte variable, the result is the
remainder of the division of 257 by 256 (the range of a byte),
which is 1 in this case.
When the d is converted to an int, its fractional component is
lost.
When d is converted to a byte, its fractional component is lost,
and the value is reduced modulo 256, which in this case is 67.

22
Automatic Type Promotion in Expressions

In addition to assignments, there is another place where certain


type conversions may occur in expressions. For example,

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. This
means that the subexpression a * b is performed using
integers—not bytes. Thus, 2,000, the result of the intermediate
expression, 50 * 40, is legal even though a and b are both
23
specified as type byte.
Automatic Type Promotion in Expressions

As useful as the automatic promotions are, they can cause


confusing compile-time errors. For example, this seemingly
correct code causes a problem:
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 the operands
were automatically promoted to int when the expression was
evaluated, the result has also been promoted to int. Thus, the
result of the expression is now of type int, which cannot be
assigned to a byte without the use of a cast. This is true even if,
as in this particular case, the value being assigned would still fit
in the target type.

24
Automatic Type Promotion in Expressions

In cases where you understand the consequences of overflow, you


should use an explicit cast, such as

byte b = 50;
b = (byte)(b * 2);

which yields the correct value of 100.

25
The Type Promotion Rules

Java defines several type promotion rules that apply to


expressions. They are as follows:
 First, all byte, short, and char values are promoted to int, as
just described. Then, if one operand is a long, the whole
expression is promoted to long. If one operand is a float, the
entire expression is promoted to float. If any of the operands is
double, the result is double.

26
The Type Promotion Rules
The following program demonstrates how each value in the
expression gets promoted to match the second argument to each
binary operator:
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("result = " + result);
}
}

27
The Type Promotion Rules
Let’s look closely at the type promotions that occur in this line
from the program:
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the
result of the subexpression is float.
Next, in the subexpression i / c, c is promoted to int, and the
result is of type int.
Then, in d * s, the value of s is promoted to double, and the type
of the subexpression is double.
Finally, these three intermediate values, float, int, and double,
are considered. 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.

28
Review Exercises
Exercise 1. Suppose we have the following declarations:

int i = 3, j = 4, k = 5;
float x = 34.5f, y = 12.25f;

Determine the value for each of the following expressions, or


explain why it is not a valid expression.
a. (x + 1.5) / (250.0 * (i/j))
b. x + 1.5 / 250.0 * i / j
c. -x * -y * (i + j) / k
d. (i / 5) * y
e. i / 5 * y

29
Review Exercises
Exercise 2. Suppose we have the following declarations:
int m, n, i = 3, j = 4, k = 5;
float v, w, x = 34.5f, y = 12.25f;
Determine the value assigned to the variable in each of the
following assignment statements, or explain why it is not a valid
assignment.
a. v = x / i;
b. n = (int) x / y * i / 2;
c. -x * -y * (i + j) / k
d. m = n + i * j;
e. n = k /(j * i) * x + y;
h. i = i + 1;
i. w = float(x + i);
j. x = x / i / y / j;
30
Programming Exercises
Exercise 1. Write a program to convert centimeters (input) to feet
and inches (output).
1 in = 2.54 cm.
Exercise 2.
Write a program that inputs temperature in degrees Celsius and
prints out the temperature in degrees Fahrenheit. The formula to
convert degrees Celsius to equivalent degrees Fahrenheit is
Fahrenheit = 1.8 × Celsius + 32
Exercise 3. Write a program that accepts a person’s weight and
displays the number of
calories the person needs in one day. A person needs 19 calories
per pound of body weight, so the formula expressed in Java is
calories = bodyWeight * 19;
(Note: We are not distinguishing between genders.)
31
Programming Exercises

32

Das könnte Ihnen auch gefallen