You are on page 1of 75

MTS 2023

Object Oriented
Programming
Basic of Java

1
The brief History of JAVA
 Around 1990 James Gosling , Bill Joy and others at Sun Microsystems
developing a language called Oak.

 Oak needed to be:


 Platform independent
 Extremely reliable
 Compact.
 As of 1993, interactive TV and PDA failed, Internet and Web explosion
began. JAVA emergence.

 By 1994 Sun's HotJava browser appeared. Power of applets

 Learn more in : http://www.javarss.com/java-timeline-10years.html

2
What is JAVA?
 A high level language - the Java language is a high level one that at a
glance looks very similar to C and C++ but offers many unique features
of its own.

 Java bytecode - a compiler, such as Sun's javac, transforms the Java


language source code to bytecode that runs in the JVM.

 Java Virtual Machine (JVM) - a program, such as Sun's java, that runs
on a given platform and takes the bytecode programs as input and
interprets them just as if it were a physical processor executing machine
code

3
Some of JAVA features
 Platform Independence
 The Write-Once-Run-Anywhere
 Object Oriented
 Object oriented throughout - no coding outside of class
definitions, including main( ).
 An extensive class library available in the core language
packages.

 Compiler/Interpreter Combo
 Code is compiled to bytecodes that are interpreted by a Java
virtual machines (JVM) .

 Robust
 Exception handling built-in, strong type checking), local variables
must be initialized.

4
JAVA vs C++

Number of significant differences, the most


significant of which include:

Data Types

References vs. Pointers

Automatic Variables

Boolean Expressions:

5
Coding using JAVA..
what do u need?
 JSDK
 IDE
 Computer.. 
 Reference books…

6
JSDK?
 2 Java SE family:
 Java SE Development Kit (JDK)
 Java SE Runtime Environment (JRE).
 The JRE provides the Java APIs, Java Virtual
Machine (HotSpot VM), and other components
necessary to run applets and applications
 The JDK = JRE, plus compilers and debuggers
necessary for developing applets and applications.

7
The First Java Program
 The fundamental OOP concept illustrated by
the program:
An object-oriented program uses
objects.
 This program displays a window on the
screen.
 The size of the window is set to 300 pixels
wide and 200 pixels high. Its title is set to My
First Java Program.

8
Program Ch2Sample1

import javax.swing.*;

class Sample {
public static void main(String[ ] args) {
JFrame myWindow; Declare a name

myWindow = new JFrame( ); Create an object

myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}
Use an object

9
Program Diagram for Ch2Sample1

Sample setSize(300, 200


)

setTitle(“My First Java Program”)


myWindow : JFrame
(true)
setVisible

10
Dependency Relationship

Sample

myWindow : JFrame

Instead of drawing all messages, we summarize it by showing


only the dependency relationship. The diagram shows that
Sample “depends” on the service provided by myWindow.

11
Object Declaration
Class Name
Object Name
This class must be
One object is declared
defined before this
here.
declaration can be stated.

JFrame myWindow;

Account customer;
More
Student jan, jim, jon;
Examples
Vehicle car1, car2;

12
Object Creation
Class Name Argument
Object Name
An instance of this class No arguments are used
Name of the object we
is created. here.
are creating here.

myWindow = new JFrame ( );

customer = new Customer( );


More jon = new Student(“John Java”);
Examples car1 = new Vehicle( );

13
Sending a Message
Object Name Method Name Argument
Name of the object to The name of the The argument we are
which we are sending a message we are sending. passing with the
message. message.

myWindow . setVisible ( true ) ;

account.deposit( 200.0 );
More student.setName(“john”);
Examples car1.startEngine( );

14
Program Components

 A Java program is composed of

 comments,

 import statements, and

 class declarations.

15
Program Component:
Comment
/*
Chapter 2 Sample Program: Displaying a Window

File: Ch2Sample2.java
*/

import javax.swing.*;

class Ch2Sample1 {
public static void main(String[ ] args) {
Comment
JFrame myWindow;

myWindow = new JFrame( );

myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}

16
Matching Comment Markers

/* This is a comment on one line */

/*
Comment number 1
*/
/*
Comment number 2
*/

These are part of the


/* comment.

/*
/*
This is a comment
*/ Error: No matching
beginning marker.
*/
17
Import Statement
/*
Chapter 2 Sample Program: Displaying a Window

File: Ch2Sample2.java
*/
Import
import javax.swing.*; Statement
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;

myWindow = new JFrame( );

myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}

18
Import Statement Syntax and
SemanticsPackage Name
Class Name
The name of the class we
Name of the package
want to import. Use
that contains the classes
asterisks to import all
we want to use.
classes.

<package name> . <class name>


;

e.g. dorm . Resident;

More import
import
javax.swing.JFrame;
java.util.*;
Examples import com.drcaffeine.simplegui.*;

19
Class Declaration
/*
Chapter 2 Sample Program: Displaying a Window
Class
Declaration
File: Ch2Sample2.java
*/

import javax.swing.*;

class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;

myWindow = new JFrame( );

myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}

20
Method Declaration
/*
Chapter 2 Sample Program: Displaying a Window

File: Ch2Sample2.java Method


*/ Declaration
import javax.swing.*;

class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;

myWindow = new JFrame( );

myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}

21
Method Declaration Elements
Modifier Modifier Return Type Method Name Parameter

public static void main( String[ ] args ){

JFrame myWindow; Method Body

myWindow = new JFrame( );

myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);

22
Template for Simple Java
Programs
/*
Chapter 2 Sample Program: Displaying a Window
Comment
File: Ch2Sample2.java
*/

import javax.swing.*; Import


Statements
class Ch2Sample1 {

public static void main(String[ ] args) {


Class Name
JFrame myWindow;

myWindow = new JFrame( );

myWindow.setSize(300, 200); Method Body


myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);

}
}

23
Why Use Standard Classes
 Don’t reinvent the wheel. When there are
existing objects that satisfy our needs, use
them.
 Learning how to use standard Java classes is
the first step toward mastering OOP. Before
we can learn how to define our own classes,
we need to learn how to use existing classes.
Example of standard class is JOptionPane

24
Sample
program
//My first Java program
public class HelloFTMK {
public static void main (String [ ] args ){
System.out.println(“Hello FTMK!”);
}
}

What to do next…?
Save file as : HelloFTMK.java
Compile : javac HelloFTMK.java
HelloFTMK.class

Run : java HelloFTMK

25
Identifiers
 Names of things such as variables, constants
and methods that appear in programs.
 An identifier must start with a letter, an
underscore, or a dollar sign.
 An identifier consists of letters, digits, underscore
and dollar sign.
 An identifier cannot contain operators, such as +,
-, and so on.
 An identifier cannot be a reserved word. An
identifier cannot be true, false, or
null.

26
Data Types
Category Data Values Memory
Type (bytes)
Integral char 0 to 65535 2

byte -128 to 127 1

short -32768 to 32767 2

Int -2147483648 to 2147483647 4

Long -922337203684547758808 to 8
922337203684547758807
Floating float -3.4E +38 to 3.4E+38 4
point
Double -1.7E+308 to 1.7E+308 8

Boolean True 1 bit

False 1 bit

27
Declaring Variables
Syntax:
dataType identifier1, identifier2,….. identifierN;

int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

28
Assignment Statements
Variable = expression;

x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;


a = 'A'; // Assign 'A' to a;

Declaring and Initializing


in One Step
int x = 1;
double d = 1.4;
float f = 1.4;

29
Variables
// Compute the first area
double radius = 1.0;
area = radius*radius*3.14159;
System.out.println("The area is “ + area +
" for radius "+radius);

// Compute the second area


double radius = 2.0;
area = radius*radius*3.14159;
System.out.println("The area is “ + area +
" for radius "+radius);

30
Constants
Syntax:
final datatype IDENTIFIER = value;

 Final : specifies that the value stored


in the identifier is fixed and cannot be
changed.
 Example:
final double PI = 3.14159;
final int SIZE = 3;

31
Operators

 5 arithmetic operators
 +, addition
 - , subtraction
 * , multiplication
 / , division
 % , mod
 Unary : an operator that has only one
operand
 Binary : an operator that has two operand
32
Arithmetic Operators

 The following table summarizes the


arithmetic operators available in Java.

This is an integer division


where the fractional part
is truncated.

33
The boolean Type and
Operators
boolean lightsOn = true;

boolean lightsOn = false;

 && (and) (1 < x) && (x < 100)


 || (or) (lightsOn) || (isDayTime)
 ! (not) !(isStopped)

34
Operator Precedence
Casting
++,--(preincrement,predecrement)
*, /, %
+, -
<, <=, >, >=
==, !=;
&&, &
||, |
LOW
=, +=, -=, *=, /=, %=
35
Operators
 Example of arithmetic operators
 5/2 yields an integer 2.
 5.0/2 yields a double value 2.5
 5 % 2 yields 1 (the remainder of the
division)
 -34 % -5 yields -4
 4 % 6 yields 4

36
Example program
public class MixedExpression
{
public static void main( String[] args )
{
System.out.println(“3 / 2 + 5.0 = ” +
(3 / 2 + 5.0));
System.out.println(“4 * 3 + 7 / 5 – 25.5 = ” +
(4 * 3 + 7 / 5 – 25.5 ));
}
} Sample Run:
3 / 2 + 5.0 = 6.0
4 * 3 + 7 / 5 – 25.5 = -12.5
37
Shortcut Operators
Operator Example Equivalent
+= i+=8 i = i+8
-= f-=8.0 f = f-8.0
*= i*=8 i = i*8
/= i/=8 i = i/8
%= i%=8 i = i%8

38
Increment and
Decrement Operators
 Pre-increment : ++variable
 Post-increment : variable++
 Pre-decrement : --variable
 Post-decrement : variable--
 Example:
 a = 5;
b = 2 + (++a); // a is 6, b is 8
 a = 5;
b = 2 + (a++); // a is 6, b is 7

39
Numeric Type Conversion
Consider the following statements:

byte i = 100;
long l = i*3+4;
double d = i*3.1+l/2;

int x = l; (Wrong)
long l = x; (fine, implicit casting)

40
Type Casting
 double Implicit casting
double d = 3; (type widening)
 float
 long Explicit casting
int i = (int)3.0; (type narrowing)
 int
 short
 byte

41
Example program
public class ExampleCasting
{
public static void main( String[] args )
{
System.out.println(“(int)(7.9) = ” +
(int)(7.9) );
System.out.println(“(int)(7.8 + (double)(15/2)) = ” +
((int)(7.8 + (double)(15/2))));
System.out.println(“(int)(7.8 + (double)(15) / 2 ) = ” +
((int)(7.8 + (double)(15)/2)));
}
}
Output:
(int)(7.9) = 7
(int)(7.8 + (double)(15/2)) = 14
(int)(7.8 + (double)(15) / 2 ) = 15
42
Type Mismatch

 Suppose we want to input an age. Will this


work?
int age;

age = JOptionPane.showInputDialog(
null, “Enter your age”);

• No.
String value cannot be assigned directly to an
int variable.

43
Type Conversion

 Wrapper classes are used to perform necessary


type conversions, such as converting a String
object to a numerical value.

int age;
String inputStr;

inputStr = JOptionPane.showInputDialog(
null, “Enter your age”);

age = Integer.parseInt(inputStr);

44
Other Conversion Methods

45
Sample Code Fragment

//code fragment to input radius and output


//area and circumference
double radius, area, circumference;

radiusStr = JOptionPane.showInputDialog(
null, "Enter radius: " );

radius = Double.parseDouble(radiusStr);

//compute area and circumference


area = PI * radius * radius;
circumference = 2.0 * PI * radius;

JOptionPane.showMessageDialog(null,
"Given Radius: " + radius + "\n" +
"Area: " + area + "\n" +
"Circumference: " + circumference);
46
Character Data Type

char letter = 'A'; (ASCII)


char numChar = '4'; (ASCII)
char letter = '\u000A'; (Unicode)
char letter = '\u000A'; (Unicode)

Special characters
char tab = ‘\t’;

47
Unicode Format
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000a
Carriage return \r \u000d

48
Strings and the operator +
 Concatenate operations allows a string to be
appended at the end of another string
 ‘+’ is used to concatenate two strings, a string and a
numeric value or a character.
 Example:
String str;
str = “Sunny”;
str = str + “ Day ”;

After the statements executes, the string assigned to str is:


Sunny Day

49
Example Program
public class ExampleString
{
public static void main (String[] args)
{
String str;
int num1,num2;
num1 = 12;
num2 = 26;
str = num1 + num2;
System.out.println(“str 1 : ” + str);
str = (num1 + num2);
System.out.println(“str 2 : ” + str); Output:
str1 : 1226
}
str2 : 38
}

50
Input

 To put data into variables from the standard


input device, you first create an input stream
object and associate it with the standard input
device
static Scanner console = new Scanner(System.in);

Scanner is a predefined Java class, console is the


object of this class.

51
Input
 The object console reads the next input as follows:
 If the next input can be interpreted as an integer
console.nextInt()
 If the next input can be interpreted as a floating-point
number
console.nextDouble()
 If the next input can be interpreted as a string
console.next()
 If the next input can be interpreted as a string until the end
of the line
console.nextLine()
 console.nextInt(), console.nextDouble() and
console.next() skip any whitespace characters

52
Output
 Standard output device is accomplished by using
standard output object System.out.
 It has two methods
 print - leaves the insertion point after the last character of
the value of expression
System.out.print (expression);
 println – insertion point at the beginning of the next line
System.out.println (expression);
System.out.println (); - only positions the insertion point at
the beginning of the next line

53
Example Program
import java.util.*; // required to use the class Scanner
public class InputOutput
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int feet, inches;
System.out.println(“Enter 2 integers :”); Output:
feet = console.nextInt(); Enter 2 integers:
inches = console.nextInt(); 23 7
Feet = 23
Inches = 7
System.out.println (“Feet = ” + feet);
System.out.println (“Inches = ” + inches);
}
}

54
Output using JOptionPane
 Using showMessageDialog of the
JOptionPane class is a simple way to
display a result of a computation to the user.
JOptionPane.showMessageDialog(null, “I Love Java”);

This dialog will appear


at the center of the
screen.

55
Displaying Multiple Lines of
Text
 We can display multiple lines of text by

separating lines with a new line marker \n.


JOptionPane.showMessageDialog(null,
“one\ntwo\nthree”);

56
Sample program

 Product.java - Calculate the product of three


integers.

57
// Product.java - Calculate the product of three integers.
Sample program (with
// Java packages
import javax.swing.JOptionPane; GUI)
public class Product {

public static void main( String args[] )


{
int x; // first number
int y; // second number
int z; // third number
int result; // product of numbers

String xVal; // first string input by user


String yVal; // second string input by user
String zVal; // third string input by user

xVal = JOptionPane.showInputDialog( "Enter first integer:" );


yVal = JOptionPane.showInputDialog( "Enter second integer:" );
zVal = JOptionPane.showInputDialog( "Enter third integer:" );

x = Integer.parseInt( xVal );
y = Integer.parseInt( yVal );
z = Integer.parseInt( zVal );

result = x * y * z;

JOptionPane.showMessageDialog( null, "The product is " + result );

System.exit( 0 );

} // end method main

} // end class Product

58
Programming Style and
Documentation
 Appropriate Comments
 Naming Conventions

 Proper Indentation and Spacing


Lines
 Block Styles

59
Appropriate Comments
 Include a summary at the beginning of the
program to explain what the program does, its
key features, its supporting data structures,
and any unique techniques it uses.
 Include your name, class section, instruction,
date, and a brief description at the beginning of
the program.

60
Naming Conventions
 Choose meaning and descriptive names.
 Variables and method names:
 Use lowercase. If the name consists of several words,

concatenate all in one, use lowercase for the first word, and
capitalize the first letter of each subsequent word in the
name. For example, the variables radius and area, and
the method computeArea.
 Class names:
 Capitalize the first letter of each word in the name. For

example, the class name ComputeArea.


 Constants:
 Capitalize all letters in constants. For example, the constant

PI.

61
Proper Indentation and
Spacing
 Indentation
 Indent two spaces.

 Spacing
 Use blank line to separate segments of the
code.

Block Styles
 Use next-line style for braces.

62
Programming Errors
 Syntax Errors
 Detected by the compiler
 Runtime Errors
 Causes the program to abort
 Logic Errors
 Produces incorrect result

63
Problem Statement
 Problem statement:
Write a loan calculator program that
computes both monthly and total payments
for a given loan amount, annual interest rate,
and loan period.
Overall Plan
 Tasks:
 Get three input values: loanAmount,
interestRate, and loanPeriod.
 Compute the monthly and total payments.
 Output the results. 64
Required Classes

65
Development Steps
We will develop this program in four steps:

2. Start with code to accept three input


values.
3. Add code to output the results.
4. Add code to compute the monthly and
total payments.
5. Update or modify code and tie up any
loose ends.

66
Step 1 Design
 Call the showInputDialog method to accept
three input values:
 loan amount,
 annual interest rate,
 loan period.
 Data types are
Input Format Data
loan amount dollars and cents Type
double
annual interest rate in percent double
(e.g.,12.5)
loan period in years int

67
Step 1 Code
Program source file is too big to list here. From now on, we ask
you to view the source files using your Java IDE.

Directory: Chapter3/Step1

Source File: Ch3LoanCalculator.java

68
Step 1 Test
 In the testing phase, we run the program
multiple times and verify that
 we can enter three input values
 we see the entered values echo-printed
correctly on the standard output window

69
Step 2 Design
 We will consider the display format for out.
 Two possibilities are (among many others)

70
Step 2 Test
 We run the program numerous times with
different types of input values and check
the output display format.
 Adjust the formatting as appropriate

71
Step 3 Design
 The formula to compute the geometric
progression is the one we can use to
compute the monthly payment.
 The formula requires the loan period in
months and interest rate as monthly
interest rate.
 So we must convert the annual interest
rate (input value) to a monthly interest rate
(per the formula), and the loan period to
the number of monthly payments.
72
Step 3 Test
 We run the program numerous times with
different types of input values and check
the results.

73
Step 4: Finalize
 We will add a program description
 We will format the monthly and total
payments to two decimal places using
DecimalFormat.

74
Exercises

1. Suppose you need to write a Java program


that calculates an employee's paycheck for
a given number of hours of work. Write
declarations for the variables you'll need.
2. Using the variables you declared in
exercise 1, write the program lines needed
to perform the paycheck calculations.

75