You are on page 1of 68

ISB 16003 Object Oriented

Programming
Learning Outcomes:
Upon completion of this course students should be able to:
Define the features of the OO language; encapsulation,
inheritance and polymorphism
Examine the UML notations (class diagram) before
translate it to the program source codes
Design the interface using GUI components such as panels,
buttons, labels, text field and text areas.
Develop a comprehensive project that will implement I/O
functionality to read and write to data and text files
Discuss on exception handling, and multithreading.
Construct a simple Transmission Control Protocol/Internet
Protocol (TCP/IP) client that communicates through
sockets
Chapter 1

Creating Your First Java


Classes
Objectives
Be introduced to object-oriented programming concepts
Learn about Java such as :
Analyze a Java application that uses console output
Add comments to a Java class
Save, compile, run, and modify a Java application
Create a Java application using GUI output
Correct errors and find help
Write arithmetic statements
Understand numeric-type conversion
Work with the char data type
Use the Scanner class to accept keyboard input
Use the JOptionPane class for GUI input

Java Programming, Fifth


4
Edition
Introducing Object-Oriented
Programming Concepts
Procedural programming
Sets of operations executed in sequence
Variables
Named computer memory locations that hold values
Procedures
Individual operations grouped into logical units
Object-oriented programs
Create classes
Create objects from classes
Create applications

Java Programming, Fifth


5
Edition
Introducing Object-Oriented
Programming Concepts
(continued)
GUI system
Allows you to treat files as objects
Not all object-orientated programs written to use GUI
Object-oriented programming differs from traditional procedural
programming
Basic concepts
Encapsulation
Inheritance
Polymorphism

Java Programming, Fifth


6
Edition
Understanding Objects and
Classes
Objects
Made up of attributes and methods
Attributes
Characteristics that define object
Differentiate objects of same class
Value of attributes is objects state
Class
Describes objects with common properties
Definition
Instance

Java Programming, Fifth


7
Edition
Understanding Objects and
Classes (continued)

Java Programming, Fifth


8
Edition
Understanding Objects and
Classes (continued)
Method
Self-contained block of program code
Similar to procedure
Encapsulation
Refers to hiding of data and methods within object
Provides security
Keeps data and methods safe from inadvertent changes

Java Programming, Fifth


9
Edition
Understanding Inheritance and
Polymorphism
Inheritance
Important feature of object-oriented programs
Classes share attributes and methods of existing classes but have more
specific features
Helps you understand real-world objects
Polymorphism
Means many forms
Allows same word to be interpreted correctly in different situations
based on context

Java Programming, Fifth


10
Edition
Learning About Programming
Program
Set of written instructions that tells computer what to do
Machine language
Most basic circuitry-level language
Low-level programming language
High-level programming language
Allows you to use vocabulary of reasonable terms
Syntax
Rules of language
Program statements
Similar to English sentences
Carry out tasks of program

Java Programming, Fifth


11
Edition
Learning About Programming
(continued)
Compiler or interpreter
Translates language statements into machine code
Syntax error
Misuse of language
Misspelled programming language word
Debugging
Freeing program of all errors
Logic errors
Also called semantic errors
Incorrect order or procedure

Java Programming, Fifth


12
Edition
Why Java?
The answer is BECAUSE..
Java enables users to develop and deploy applications on the
Internet for servers, desktop computers, and small hand-held
devices. The future of computing is being profoundly
influenced by the Internet, and Java promises to remain a big
part of that future.
Java is a general purpose programming language.
Java is the Internet programming language.
Learning About Java
Java
Developed by Sun Microsystems
Object-oriented language
General-purpose
Advantages
Security features
Architecturally neutral

Java Programming, Fifth


14
Edition
Learning About Java (continued)
Java (continued)
Can be run on wide variety of computers
Does not execute instructions on computer directly
Runs on hypothetical computer known as Java virtual machine (JVM)
Source code
Programming statements written in high-level programming language
Bytecode
Statements saved in file
Java compiler converts source code into binary program
Java interpreter
Checks bytecode and communicates with operating system
Executes bytecode instructions line by line within Java virtual machine

Java Programming, Fifth


15
Edition
Learning About Java (continued)

Java Programming, Fifth


16
Edition
Java Program Types
Applets
Programs embedded in Web page
Java applications
Called Java stand-alone programs
Console applications
Support character output
Windowed applications
Menus
Toolbars
Dialog boxes

Java Programming, Fifth


17
Edition
Examples of Javas Versatility

Standalone Application: TicTacToe

Applet: TicTacToe

Servlets: SelfTest Web site

Mobile Computing: Cell phones(J2ME),


Smart Phones (Android)
Analyzing a Java Application That
Uses Console Output
Even simplest Java application
Involves fair amount of confusing syntax
Print First Java application on screen

Literal string
Will appear in output exactly as entered
Written between double quotation marks
Arguments
Pieces of information passed to method
Method
Requires
Java Programming, Fifth information to perform its task
19
Edition
Understanding the Statement
That Prints the Output (continued)

Java Programming, Fifth


20
Edition
Understanding the First Class
(continued)

Java Programming, Fifth


21
Edition
Understanding the main() Method
static
Reserved keyword
Means method is accessible and usable
Even though no objects of class exist
void
Use in main() method header
Does not indicate main() method empty
Indicates main() method does not return value when called
Doesnt mean main() doesnt produce output

Java Programming, Fifth


22
Edition
Adding Comments to a Java Class
Program comments
Nonexecuting statements added to program for documentation
Use to leave notes for yourself or others
Include author, date, classs name or function
Comment out a statement
Turn it into a comment
Compiler does not translate and the JVM does not execute its command
Types of Java comments
Line comments
Start with two forward slashes (//)
Continue to end of current line
Do not require ending symbol
Block comments
Start with forward slash and asterisk (/*)
End with asterisk and forward slash (*/)
Types of Java comments (continued)
Javadoc comments
Special case of block comments
Begin with slash and two asterisks (/**)
End with asterisk and forward slash (*/)
Use
Java Programming, to generate documentation
Fifth
23
Edition
Saving, Compiling, and Running
and Modifying a Java Application
Saving a Java class
Save class in file with exactly same name and.java extension
For public classes
Class name and filename must match exactly
Compiling a Java class
Compile source code into bytecode
Translate bytecode into executable statements
Using Java interpreter
Type javac First.java

Java Programming, Fifth


24
Edition
Creating a Java Application
Using GUI Output
JOptionPane
Produce dialog boxes
Dialog box
GUI object resembling window
Messages placed for display
Package
Group of classes
import statement
Use to access built-in Java class

Java Programming, Fifth


25
Edition
Creating a Java Application
Using GUI Output (continued)

Java Programming, Fifth


26
Edition
Using Constants and Variables
Constant
Cannot be changed while program is running
Variable
Might change while program is running
Literal constant
Value taken literally at each use

Java Programming, Fifth


27
Edition
Using Constants and Variables
(continued)
Variable
Named memory location
Use to store value
Can hold only one value at a time
Value can change
Data type
Type of data that can be stored
How much memory item occupies
What types of operations can be performed on data

Java Programming, Fifth


28
Edition
Using Constants and Variables
(continued)
Primitive type
Simple data type
Reference types
More complex data types

Java Programming, Fifth


29
Edition
Declaring Variables (continued)
Assignment operator
Equal sign (=)
Value to right assigned to variable on left
Initialization
Assignment made when declaring variable
Assignment
Assignment made after variable declared
Associativity
Order in which operands used with operators

Java Programming, Fifth


30
Edition
Declaring Variables (continued)
Declare multiple variables of same type in separate statements on
different lines
int myAge = 25;
int yourAge = 19;
Declare variables of different types
Must use separate statement for each type

Java Programming, Fifth


31
Edition
Declaring Named Constants
Named constant
Should not change during program execution
Has data type, name, and value
Data type preceded by keyword final
Can be assigned a value only once
Conventionally given identifiers using all uppercase letters

Java Programming, Fifth


32
Edition
Declaring Named Constants
(continued)
Reasons for using named constants
Makes programs easier to read and understand
Change value at one location within program
Reduces typographical errors
Stands out as separate from variables

Java Programming, Fifth


33
Edition
Pitfall: Forgetting That a Variable
Holds One Value at a Time
Each constant can hold only one value
For duration of program
Switch values of two variables
Use third variable

Java Programming, Fifth


34
Edition
Learning About the int Data Type
Type int
Store integers, or whole numbers
Value from 2,147,483,648 to +2,147,483,647
Variations of the integer type
byte
short
long
Choose appropriate types for variables

Java Programming, Fifth


35
Edition
Learning About the int Data Type
(continued)

Java Programming, Fifth


36
Edition
Displaying Data
print() or println() statement
Alone or in combination with string
Concatenated
Numeric variable concatenated to String using plus sign
Entire expression becomes String
println() method can accept number or String

Java Programming, Fifth


37
Edition
Displaying Data (continued)
Use dialog box to display values
JOptionPane.showMessageDialog()
Does not accept single numeric variable
Null String
Empty string:

Java Programming, Fifth


38
Edition
Displaying Data (continued)

Java Programming, Fifth


39
Edition
Writing Arithmetic Statements
Arithmetic operators
Perform calculations with values in programs
Operand
Value used on either side of operator
Integer division
Integer constants or integer variables
Result is integer
Fractional part of result lost

Java Programming, Fifth


40
Edition
Writing Arithmetic Statements
(continued)

Java Programming, Fifth


41
Edition
Writing Arithmetic Statements
(continued)
Operator precedence
Rules for order in which parts of mathematical expression are
evaluated
First multiplication, division, and modulus
Then addition or subtraction

Java Programming, Fifth


42
Edition
Writing Arithmetic Statements
Efficiently
Avoid unnecessary repetition of arithmetic statements
Example of inefficient calculation
stateWithholding = hours * rate * STATE_RATE;
federalWithholding = hours * rate * FED_RATE;
Example of efficient calculation
grossPay = hours * rate;
stateWithholding = grossPay * STATE_RATE;
federalWithholding = grossPay * FED_RATE;

Java Programming, Fifth


43
Edition
Using the Boolean Data Type
Boolean logic
Based on true-or-false comparisons
Boolean variable
Can hold only one of two values
true or false
boolean isItPayday = false;
Relational operator
Compares two items

Java Programming, Fifth


44
Edition
Using the Boolean Data Type
(continued)

Java Programming, Fifth


45
Edition
Learning About Floating-Point
Data Types
Floating-point number
Contains decimal positions
Floating-point data types
float
double
Significant digits
Refers to mathematical accuracy

Java Programming, Fifth


46
Edition
Learning About Floating-Point
Data Types (continued)

Java Programming, Fifth


47
Edition
Understanding Numeric-Type
Conversion
Arithmetic with variables or constants of same type
Result of arithmetic retains same type
Arithmetic operations with operands of unlike types
Java chooses unifying type for result
Unifying type
Type to which all operands in expression are converted for
compatibility

Java Programming, Fifth


48
Edition
Understanding Numeric-Type
Conversion (continued)
Order for establishing unifying types between two variables
1. double
2. float
3. long
4. int
Type casting
Forces value of one data type to be used as value of another type

Java Programming, Fifth


49
Edition
Understanding Numeric-Type
Conversion (continued)
Cast operator
Place desired result type in parentheses
Explicit conversion
Do not need to perform cast when assigning value to higher unifying type

Java Programming, Fifth


50
Edition
Working with the char Data Type
char data type
Holds any single character
Place constant character values within single quotation marks
char myMiddleInitial = 'M';
String
Built-in class
Store and manipulate character strings
String constants written between double quotation marks

Java Programming, Fifth


51
Edition
Working with the char Data Type
(continued)
Escape sequence
Begins with backslash followed by character
Represents single nonprinting character
char aNewLine = '\n';
Produce console output on multiple lines in command window
Use newline escape sequence
Use println() method multiple times

Java Programming, Fifth


52
Edition
Working with the char Data Type
(continued)

Java Programming, Fifth


53
Edition
Using the Scanner Class for
Keyboard Input
System.in object
Standard input device
Normally the keyboard
Access using Scanner class
Scanner object
Breaks input into units called tokens

Java Programming, Fifth


54
Edition
Using the Scanner Class for
Keyboard Input (continued)

Java Programming, Fifth


55
Edition
Using the Scanner Class for
Keyboard Input (continued)

Java Programming, Fifth


56
Edition
Pitfall: Using nextLine()
Following One of the Other
Scanner Input Methods
Problem when using one numeric Scanner class retrieval method or
next()method
Before using nextLine()method
Keyboard buffer
After any numeric or next() input
Add extra nextLine()method call
Will retrieve abandoned Enter key character

Java Programming, Fifth


57
Edition
Using the JOptionPane
Class for GUI Input
Dialog boxes used to accept user input
Input dialog
Confirm dialog
Input dialog box
Asks question
Provides text field in which user can enter response
showInputDialog() method
Six overloaded versions
Returns String representing users response
Prompt
Message requesting user input

Java Programming, Fifth


58
Edition
Using Input Dialog Boxes
(continued)

Java Programming, Fifth


59
Edition
Using Input Dialog Boxes
(continued)
showInputDialog()
Version requires four arguments
Parent component
Message
Title
Type of dialog box
Convert String to int or double
Use methods from built-in Java classes Integer and Double
Type-wrapper classes
Each primitive type has corresponding class contained in java.lang
package
Include methods to process primitive type values
Integer.parseInt()
Double.parseDouble()

Java Programming, Fifth


60
Edition
Using Confirm Dialog Boxes
Confirm dialog box
Displays options Yes, No, and Cancel
showConfirmDialog() method in JOptionPane class
Four overloaded versions available
Returns integer containing either:
JOptionPane.YES_OPTION
JOptionPane.NO_OPTION
JOptionPane.CANCEL_OPTION
Create confirm dialog box with five arguments
Parent component
Prompt message
Title
Integer that indicates which option button to show
Integer that describes kind of dialog box

Java Programming, Fifth


61
Edition
Using Confirm Dialog Boxes (continued)
Create confirm dialog box with five
arguments
Parent component
Prompt message
Title
Integer that indicates which option
button to show
Integer that describes kind of dialog
box

Java Programming, Fifth


62
Edition
You Do It
Your first application
Adding comments to a class
Modifying a class
Creating a dialog box

Java Programming, Fifth


63
Edition
Summary
Computer program
Set of instructions that tells a computer what to do
Object-oriented programs
Classes
Objects
Applications
Java virtual machine (JVM)
Standardized hypothetical computer
Everything in a Java program must be part of a class

Java Programming, Fifth


64
Edition
Summary (continued)
Access modifier
Word that defines circumstances under which class can be accessed
All Java applications must have method named main()
Program comments
Nonexecuting statements
Add to file for documentation
javac
Compile command

Java Programming, Fifth


65
Edition
Summary (continued)
java
Execute command
JOptionPane
GUI
Provides methods for creating dialogs

Java Programming, Fifth


66
Edition
Summary
Variables
Named memory locations
Primitive data types
Standard arithmetic operators for integers
+, _, *, /, and %
Boolean type
true or false value
Relational operators
>, <, ==, >=, <=, and !=

Java Programming, Fifth


67
Edition
Summary (continued)
Floating-point data types
float
double
char data type
Scanner
Access keyboard input
JOptionPane
Confirm dialog
Input dialog

Java Programming, Fifth


68
Edition

You might also like