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
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
The Write-Once-Run-Anywhere
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;
myWindow = new JFrame( );
Declare a name 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”)
(true) setVisible
myWindow : JFrame
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 This class must be defined before this declaration can be stated.
Object Name One object is declared here.
JFrame
myWindow;
More Examples
Account Student Vehicle
customer; jan, jim, jon; car1, car2;
12
Object Creation Class Name An instance of this class is created.
Object Name Name of the object we are creating here.
myWindow
More Examples
= new JFrame (
Argument No arguments are used here.
);
customer = new Customer( ); jon = new Student(“John Java”); car1 = new Vehicle( );
13
Sending a Message Object Name Name of the object to which we are sending a message.
Method Name The name of the message we are sending.
myWindow
More Examples
.
setVisible
(
Argument The argument we are passing with the message.
true
) ;
account.deposit( 200.0 ); student.setName(“john”); 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) { JFrame
myWindow;
Comment
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 javax.swing.*;
Import 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 Semantics Class Name Package Name The name of the class we want to import. Use asterisks to import all classes.
Name of the package that contains the classes we want to use.
.
<package name> ; e.g.
More Examples
dorm import import import
.
Resident;
javax.swing.JFrame; java.util.*; 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
public
Modifier
static
Return Type
void
JFrame myWindow;
Method Name
main(
Parameter
String[ ] args
){
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 Statements
import javax.swing.*; class Ch2Sample1
{
public static void main(String[ ] args) { JFrame
myWindow;
Class Name
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 //My first Java program 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 Integral
Data Type
Values
Memory (bytes)
char
0 to 65535
2
byte
-128 to 127
1
short
-32768 to 32767
2
Int
-2147483648 to 2147483647
4
Long
-922337203684547758808 to 922337203684547758807
8
Floating point
float
-3.4E +38 to 3.4E+38
4
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) || (or) ! (not)
(1 < x) && (x < 100) (lightsOn) || (isDayTime) !(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 float long int short byte
Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing)
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 String
age; 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: Enter 2 integers: feet = console.nextInt(); 23 7 inches = console.nextInt(); System.out.println (“Feet = ” + feet); System.out.println (“Inches = ” + inches);
Feet = 23 Inches = 7
} } 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. // Java packages import javax.swing.JOptionPane;
Sample program (with 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 Lines Block Styles
Spacing
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
Runtime Errors
Detected by the compiler 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.
3. 4.
5.
Start with code to accept three input values. Add code to output the results. Add code to compute the monthly and total payments. 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 Type double
loan amount
dollars and cents
annual interest rate
in percent (e.g.,12.5)
double
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.
2.
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. Using the variables you declared in exercise 1, write the program lines needed to perform the paycheck calculations.
75