Beruflich Dokumente
Kultur Dokumente
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.
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 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++
Data Types
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.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}
Use an object
9
Program Diagram for Ch2Sample1
10
Dependency Relationship
Sample
myWindow : JFrame
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.
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.
account.deposit( 200.0 );
More student.setName(“john”);
Examples car1.startEngine( );
14
Program Components
comments,
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.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}
16
Matching Comment Markers
/*
Comment number 1
*/
/*
Comment number 2
*/
/*
/*
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.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.
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.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}
20
Method Declaration
/*
Chapter 2 Sample Program: Displaying a Window
class Ch2Sample1 {
public static void main(String[ ] args) {
JFrame myWindow;
myWindow.setSize(300, 200);
myWindow.setTitle(“My First Java Program”);
myWindow.setVisible(true);
}
}
21
Method Declaration Elements
Modifier Modifier Return Type Method Name Parameter
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
*/
}
}
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
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
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
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;
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);
30
Constants
Syntax:
final datatype IDENTIFIER = value;
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
33
The boolean Type and
Operators
boolean lightsOn = true;
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
age = JOptionPane.showInputDialog(
null, “Enter your age”);
• No.
String value cannot be assigned directly to an
int variable.
43
Type Conversion
int age;
String inputStr;
inputStr = JOptionPane.showInputDialog(
null, “Enter your age”);
age = Integer.parseInt(inputStr);
44
Other Conversion Methods
45
Sample Code Fragment
radiusStr = JOptionPane.showInputDialog(
null, "Enter radius: " );
radius = Double.parseDouble(radiusStr);
JOptionPane.showMessageDialog(null,
"Given Radius: " + radius + "\n" +
"Area: " + area + "\n" +
"Circumference: " + circumference);
46
Character Data Type
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 ”;
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
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”);
55
Displaying Multiple Lines of
Text
We can display multiple lines of text by
56
Sample program
57
// Product.java - Calculate the product of three integers.
Sample program (with
// Java packages
import javax.swing.JOptionPane; GUI)
public class Product {
x = Integer.parseInt( xVal );
y = Integer.parseInt( yVal );
z = Integer.parseInt( zVal );
result = x * y * z;
System.exit( 0 );
58
Programming Style and
Documentation
Appropriate Comments
Naming Conventions
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
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:
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
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
75