Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

OBJECT ORIENTED PROGRAMMING

Chapter 1: Fundamentals of Programming using Java


Handout #2
1. Displaying Text in a Dialog Box
The program in the first lecture displays the text on the console (command widow). Since Java
applications can also use windows or dialog boxes (also called dialogs) to display output, you can
rewrite the program to display the text in a message dialog box. A dialog box is a smaller graphical
window that displays a message to the user or requests input. A variety of dialog boxes can be
displayed using the JOptionPane class. Two of the dialog boxes are message dialog and input
dialog. Message dialog is to display a message and input dialog is to prompt the user for input.

One of the great strengths of Java is its rich set of predefined classes that programmers can reuse
rather than “reinventing the wheel.” Java’s numerous predefined classes are grouped into
categories of related classes called packages. The packages are referred to collectively as the Java
class library, or the Java applications programming interface (Java API). The packages of the
Java API are split into core packages and extension packages. The names of the packages begin
with either “java” (core packages) or “javax” (extension packages). Many of the core and
extension packages are included as part of the Java 2 Software Development Kit.

The JOptionPane class is not automatically available to your java programs. Hence, the following
statement must be before the program class header:

import javax.swing.JOptionPane;

This statement tells the compiler where to find the JOptionPane class. The compiler uses
import statements to identify and load classes used in a Java program. The import statements
help the compiler locate the classes you intend to use. It tells the compiler to load the
JOptionPane class from the javax.swing package. This package contains many classes that help
Java programmers define graphical user interfaces (GUIs) for their application. GUI components
facilitate data entry by the user of your program and formatting or presentation of data outputs to
the user of your program.

The JOptionPane class provides the method showMessageDialog to display any text in a
message dialog box. The showMessageDialog method is a static method. Such a method should
be invoked by using the class name followed by a dot operator (.) and the method name with
arguments, as in, as in ClassName.methodName( arguments ). Static methods will be discussed
in detail in the next Chapters. The showMessageDialog method can be invoked with four
arguments, as:
JOptionPane.showMessageDialog(null, "Welcome to Java Programming”, “Display
Message", JOptionPane.INFORMATION_MESSAGE);

The first argument can always be null. null is a Java keyword. When the first argument is null,
the dialog box appears in the center of the computer screen. Most applications you use on your
computer execute in their own window (e.g.,email programs, Web browsers and word processors).
When such an application displays a dialog box, it normally appears in the center of the application
window, which is not necessarily the center of the screen. The second argument can be a string

October 1, 2017 1
OBJECT ORIENTED PROGRAMMING

for text to be displayed. The third argument is the title of the message box. The fourth argument is
the message type argument, can be one of these: JOptionPane.INFORMATION_MESSAGE,
JOptionPane.ERROR_MESSAGE,JOptionPane.WARNING_MESSAGE,
JOptionPane.QUESTION_MESSAGE , and JOptionPane.PLAIN_MESSAGE

Note
There are several ways to use the showMessageDialog method. For the time being, all you need
to know are two ways to invoke it. One is to use a statement, as shown in the example:
JOptionPane.showMessageDialog(null, x, y, JOptionPane.INFORMATION_MESSAGE);
where x is a string for the text to be displayed, and y is a string for the title of the message box.
The other is to use a statement like this one: JOptionPane.showMessageDialog(null, x); where x
is a string for the text to be displayed.

Example
/** This application program displays Welcome to Java!
* in a message dialog box.
*/
import javax.swing.JOptionPane;

public class WelcomeInMessageDialogBox {


public static void main(String[] args) {
// Display Welcome to Java Programming in a message dialog box
JOptionPane.showMessageDialog(null, "Welcome to Java Programming", "Display Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
When this program is run, a window appears on the screen that contains the message
“Welcome to Java Programming”. The title bar of the dialog contains the string Display Message,
to indicate that the dialog is presenting a message to the user. The dialog box automatically
includes an OK button that allows the user to dismiss (hide) the dialog by pressing the button after
reading the message. This is accomplished by positioning the mouse cursor (also called the mouse
pointer) over the OK button and clicking the left mouse button.

Note:
Prior to JDK 1.5, you have to invoke System.exit(0); to terminate the program if the program uses
JOptionPane dialog boxes. System.exit( 0 ); // terminate application
uses static method exit of class System to terminate the application. In any application
that displays a graphical user interface, this line is required in order to terminate the
application. Notice once again the syntax used to call the method—the class name (System),
a dot (.) and the method name (exit). Remember that identifiers starting with capital letters
normally represent class names. So, you can assume that System is a class. Class System is part
of the package java.lang. Notice that class System is not imported with an import statement at
the beginning of the program. By default, package java.lang is imported in every Java program.
Package java.lang is the only package in the Java API for which you are not required to provide
an import statement.

October 1, 2017 2
OBJECT ORIENTED PROGRAMMING

The argument 0 to method exit indicates that the application has terminated successfully. (A
nonzero value normally indicates that an error has occurred.)

Exercise
Write a very simple GUI “Hello World” program that says “Hello” to the user, does it by
opening a window where the greeting is displayed.

2. Identifiers
Just as every entity in the real world has a name, so you need to choose names for the things you
will refer to in your programs. Programming languages use special symbols called identifiers to
name such programming entities as variables, constants, methods, classes, and packages. Each
language has its own rules for naming these identifiers. Here are the rules for naming identifiers:

· An identifier is a sequence of characters that consists of letters, digits, underscores (_), and
dollar signs ($).
· An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with
a digit.
· An identifier cannot be a reserved word.
· An identifier cannot be true, false, or null.
· An identifier can be of any length.
· Upper and lower case letters are distinct. That is, Java is case sensitive language. For example,
area, Area, and AREA are all different identifiers.
Note
Identifiers are for naming variables, constants, methods, classes, and packages. Descriptive
identifiers make programs easy to read. Avoid using abbreviations for identifiers. Using complete
words is more descriptive. For example, numberOfStudents is better than numStuds,
numOfStuds, or numOfStudents. Do not name identifiers with the $ character. By convention,
the $ character should be used only in mechanically generated source code.

Exercise: Which of the following identifiers are valid? Which are Java keywords?
miles, Test, a++, ––a, 4#R, $4, #44, apps class, public, int, x, y, radius
3. Variables
Variables are used to represent values that may be changed in the program. A variable is an entity
whose value can be changed during program execution and is known to the program by a name. It
is the content of a memory location that stores a certain value. A variable can hold only one value
at a time during program execution. Its value can be changed during the execution of the program.

Variables are for representing data of a certain type. To use a variable, you declare it by telling
the compiler its name as well as what type of data it can store. The variable declaration tells the

October 1, 2017 3
OBJECT ORIENTED PROGRAMMING

compiler to allocate appropriate memory space for the variable based on its data type. The syntax
for declaring a variable is:
datatype variableName;
Here are some examples of variable declarations:
int count; // Declare count to be an integer variable
double radius; // Declare radius to be a double variable
double interestRate; // Declare interestRate to be a double variable
If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2, ..., variableN;
The variables are separated by commas. For example,
int i, j, k; // Declare i, j, and k as int variables
Variables often have initial values. You can declare a variable and initialize it in one step.
Consider, for instance, the following code:
int count = 1;
This is equivalent to the next two statements:
int count;
count = 1;
You can also use a shorthand form to declare and initialize variables of the same type together.
For example, int i = 1, j = 2;

Note
A variable must be declared before it can be assigned a value. A variable declared in a method
must be assigned a value before it can be used. Whenever possible, declare a variable and assign
its initial value in one step. This will make the program easy to read and avoid programming errors.

Exercise: Consider the following code:


int interestRate = 0.05;
int interest = interestrate * 45;
What is the value of interest? Justify your answer.

4. Assignment Statements and Assignment Expressions


An assignment statement designates a value for a variable. An assignment statement can be used
as an expression in Java. After a variable is declared, you can assign a value to it by using an
assignment statement. In Java, the equal sign (=) is used as the assignment operator. The syntax
for assignment statements is as follows:
variable = expression;
An expression represents a computation involving values, variables, and operators that, taking
them together, evaluates to a value. For example, consider the following code:
int y = 1; // Assign 1 to variable y
double radius = 1.0; // Assign 1.0 to variable radius
int x = 5 * (3 / 2); // Assign the value of the expression to x
x = y + 1; // Assign the addition of y and 1 to x
area = radius * radius * 3.14159; // Compute area
You can use a variable in an expression. A variable can also be used in both sides of the
operator. For example, x = x + 1;

October 1, 2017 4
OBJECT ORIENTED PROGRAMMING

In this assignment statement, the result of x + 1 is assigned to x. If x is 1 before the statement is


executed, then it becomes 2 after the statement is executed. To assign a value to a variable, you
must place the variable name to the left of the assignment operator. Thus, the following
statement is wrong: 1 = x; // Wrong
Note
In Java, an assignment statement is essentially an expression that evaluates to the value to be
assigned to the variable on the left side of the assignment operator. For this reason, an
assignment statement is also known as an assignment expression. For example, the following
statement is correct:
System.out.println(x = 1);
which is equivalent to
x = 1;
System.out.println(x);
If a value is assigned to multiple variables, you can use this syntax:
i = j = k = 1;
which is equivalent to
k = 1;
j = k;
i = j;
5. Constants
The value of a variable may change during the execution of the program, but a constant represents
permanent data that never changes. Here is the syntax for declaring a constant:
final datatype CONSTANTNAME = value;
A constant must be declared and initialized in the same statement. The word final is a Java
keyword for declaring a constant. For example, you can declare π as a constant as follows:
final double PI = 3.14159;

Note
By convention, constants are named in uppercase: PI, not pi or Pi. There are three benefits of using
constants: (1) You don’t have to repeatedly type the same value if it is used multiple times; (2) if
you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to change it
only in a single location in the source code; and (3) a descriptive name for a constant makes the
program easy to read.

Exe rcise: What are the benefits of using constants? Declare an int constant SIZE with value 20.
Exercise:
6. Keywords
Keywords are certain words reserved by Java. They have special meaning to the java compiler.
All keywords have fixed meaning which cannot be changed. All keywords must be written in
lowercase and cannot be used as identifiers. The list of keywords supported in Java language is
given in Chapter 1 slide.

October 1, 2017 5
OBJECT ORIENTED PROGRAMMING

7. Data Types
When programming, we store the variables in our computer's memory, but the computer has to
know what kind of data we want to store in them. Since it is not going to occupy the same amount
of memory to store a simple number than to store a single letter or a large number, and they are
not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of memory
that we can manage in Java. A byte has 8 bits.
Every data type has a range of values. The compiler allocates memory space to store each variable
or constant according to its data type. Java provides eight primitive data types:
· Logical – boolean: Logical values are represented using the boolean type, which takes one
of two values: true or false.
· Textual - char: Single character are represented using a char type. A char represents a 16-
bit, unsigned Unicode character.
· Integral - byte, short, int and long: There are four integral types in java programming
language. Each type is declared using one of the keywords byte, short, int or long. Choose
the type that is most appropriate for your variable. For example, if you know an integer
stored in a variable is within a range of byte, declare the variable as a byte.
· Floating point - double and float: Java uses two types for floating-point numbers: float and
double. The double type is twice as big as float. So, the double is known as double
precision, while float is known as single precision. Normally, you should use the double
type because it is more accurate than the float type.

The String Type: The char type only represents one character. To represent a string of characters,
use the data type called String. For example, the following code declares the message to be a string
that has an initial value of "Welcome to Java".
String message = "Welcome to Java";
String is actually a predefined class in the Java library just like the System class and
JOptionPane class. The String type is not a primitive type. It is known as a reference type. Any
Java class can be used as a reference type for a variable.

Two strings can be concatenated. The plus sign (+) is the concatenation operator if one of the
operands is a string. If one of the operands is a non-string (e.g., a number), the nonstring value is
converted into a string and concatenated with the other string. Here are some examples:
// Three strings are concatenated
String message = "Welcome" + "to" + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
String s1 = "Supplement" + 'B'; // s becomes SupplementB
If neither of the operands is a string, the plus sign (+) is the addition operator that adds two
numbers.
The shorthand += operator can also be used for string concatenation. For example, the following
code appends the string "and Java is fun" with the string "Welcome to Java" in message.
message += " and Java is fun";

October 1, 2017 6
OBJECT ORIENTED PROGRAMMING

So the new message is "Welcome to Java and Java is fun".


Suppose that i = 1 and j = 2, what is the output of the following statement?
System.out.println("i + j is " + i + j);
The output is "i + j is 12" because "i + j is” is concatenated with the value of i first. To force i +
j to be executed first, enclose i + j in the parentheses, as follows:
System.out.println("i + j is " + (i + j));
Numeric Type Conversions (Casting): Can you perform binary operations with two operands
of different types? Yes. If an integer and a floating-point number are involved in a binary
operation, Java automatically converts the integer to a floating-point value. So, 3 * 4.5 is same as
3.0 * 4.5. You can always assign a value to a numeric variable whose type supports a larger
range of values; thus, for instance, you can assign a long value to a float variable. You cannot,
however, assign a value to a variable of a type with a smaller range unless you use type casting.

Casting is an operation that converts a value of one data type into a value of another data type.
Casting a type with a small range to a type with a larger range is known as widening a type.
Casting a type with a large range to a type with a smaller range is known as narrowing a type.
Java will automatically widen a type, but you must narrow a type explicitly. The syntax for
casting a type is to specify the target type in parentheses, followed by the variable’s name or the
value to be cast. For example, the following statement
System.out.println((int)1.7);
displays 1. When a double value is cast into an int value, the fractional part is truncated.
The following statement
System.out.println((double)1 / 2);
displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided by 2. However, the statement
System.out.println(1 / 2);
displays 0, because 1 and 2 are both integers and the resulting value should also be an integer.
Note
Casting is necessary if you are assigning a value to a variable of a smaller type range, such as
assigning a double value to an int variable. A compile error will occur if casting is not used in
situations of this kind. However, be careful when using casting, as loss of information might lead
to inaccurate results. Casting does not change the variable being cast. For example, d is not
changed after casting in the following code:
double d = 4.5;
int i = (int)d; // i becomes 4, but d is still 4.5
In Java, an augmented expression of the form x1 op= x2 is implemented as x1 = (T)(x1 op x2),
where T is the type for x1. Therefore, the following code is correct.
int sum = 0;
sum += 4.5; // sum becomes 4 after this statement
sum += 4.5 is equivalent to sum = (int)(sum + 4.5).
Exercise:
Can the following conversions involving casting be allowed? If so, find the converted result.
a. boolean b = true;
i = (int)b;
b. int i = 1;
boolean b = (boolean)i;

October 1, 2017 7
OBJECT ORIENTED PROGRAMMING

8. Operators
Operators are symbols that tell the computer to perform certain mathematical or logical
manipulation. An operator is a symbol that operates on one or more expressions, producing a value
that can be assigned to a variable. Java provides many built-in operators for composing
expressions. An expression, by the way, is any computation which yields a value. It is a
combination of variables, constants and operators written according to the syntax of the language.
The several Java operators can be classified in to:

1) Arithmetic operators 2) Assignment operator

3) Relational operators 4) Increment and Decrement operators

5) Logical operators 6) Conditional operators


Exercise:
1. Write a Java statement to accomplish each of the following tasks:
a. Declare variables sum and x to be of type int.
b. Assign 1 to variable x.
c. Assign 0 to variable sum.
d. Add variable x to variable sum, and assign the result to variable sum.
e. Print "The sum is: ", followed by the value of variable sum.
2. Determine the value of each variable after the calculation is performed. Assume that when
each statement begins executing, all variables have the integer value 5.
a. product *= x++;
b. quotient /= ++x;
3. Show and explain the output of the following code:
a. int i = 0;
System.out.println(--i + i + i++);
System.out.println(i + ++i);
b. int i = 0;
i = i + (i = 1);
System.out.println(i);
4. Write a conditional expression that evaluates to even number if a number stored in variable
number is even otherwise the number is odd number.
5. Show the output of the following program:
public class Test {
public static void main(String[] args) {
Program Output
char x = 'a';
char y = 'c';
System.out.println(++y);
System.out.println(y++);
System.out.println(x > y);
System.out.println(x - y);
}
}

October 1, 2017 8

You might also like