OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 01: INTRODUCTION TO OOP
3.) POLYMORPHISM
OBJECT ORIENTED PROGRAMMING
→Ability to exist in various forms.
→ Is an extension of procedural programming
in which you take slightly different approach to 4.) ABSTRACTION
writing computer programs. → Ability to represent data at a very
conceptual level without any details.
→ When you program without using OOP It hides information to other class.
(Object-Oriented Programming), you are 5.) MESSAGE PASSING
programming procedurally. A procedural → Objects communicates through invoking
program is a step-by-step program that methods and sending data to them. This
guides the application through sequence of feature of sending and receiving
instructions. information among objects through
function parameters.
→ A procedural program executes each
statement in the literal order of its commands,
BRIEF HISTORY OF JAVA
even if those commands cause the program to
branch into all directions. → Java, having been developed in 1991, is a
relatively new programming language.
Examples of procedural program:
-C
→ At that time, James Gosling from Sun
- Pascal
Microsystems and his team began designing
- Qbasis
the first version of Java aimed at
- COBOL
programming home appliances which are
controlled by a wide variety of computer
→ Writing object-oriented programs involves processors.
both creating objects and creating
applications that use those objects. → Gosling's new language needed to be
accessible by a variety of computer
→ Better suited to most tasks because most processors.
problems are complex and multifaceted and
do not conform easily to linear approach. → In 1994, he realized that such a language
would be ideal for use with web browsers and
→ Thinking in an object-oriented manner Java's connection to the internet began.
involves envisioning program components as
objects that are similar to concrete objects in → In 1995, Netscape Incorporated released its
the real world. latest version of the Netscape browser which
was capable of running Java programs.
SOME FEATURES OF OOP
WHY IS IT CALLED JAVA?
1.) ENCAPSULATION → It is customary for the creator of a
→ Capturing data and keeping it safely and programming language to name the language
securely from outside interface. anything he/she chooses.
2.) INHERITANCE
→ Process by which a class can be derived → Original name of this language was Oak
from a base class with all features of
base class and some of its own.it → The development team went out for coffee
increases code reusability. and the name Java was born.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 01: INTRODUCTION TO OOP
WHAT IS JAVA? → Every Java interpreter, whether it's a Java
development tool or a Web browser that can
→ Java programming language was run Java applets, is an implementation of the
developed by SUN (Stanford University Java VM
Network) Microsystems as an object-oriented
language that is used both for general- → The Java VM can also be implemented in
purpose business programs and interactive hardware.
World Wide Web-based internet programs.
→ Java bytecodes help make "write once, run
→ Java programming language so popular in anywhere" possible. You can compile your
recent years are its security features, and the Java program into bytecodes on any platform
fact that it is architecturally neutral that has a Java compiler. The bytecodes can
then be run on any implementation of the
→ You can use Java to write program that will Java VM.
run on any platform.
→ For example, the same Java program can
run on Windows NT, Solaris, and Macintosh
→ Java is also unusual in that each Java
program is both compiled and interpreted. THE JAVA PLATFORM
→ A platform is the hardware or software
→ With a compiler, you translate a Java environment in which a program runs.
program into an intermediate language called
Java bytecodes or simply bytecode-- the → The Java platform differs from most other
platform-independent codes interpreted by platforms in that it's a software-only platform
the Java interpreter. that runs on top of other, hardware-based
platforms.
→ Compilation happens just once;
interpretation occurs each time the program is → Other platforms are described as a
executed. This figure illustrates how this works. combination of hardware and operating
system.
The Java Platform has two components:
1.) Java Virtual Machine (Java VM)
2.)Java Application Programming Interface
(Java API)
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 01: INTRODUCTION TO OOP
Parts of a Java Program
JAVA VIRTUAL JAVA MACHINE
1. Class name
→ The Java VM the base for the Java platform 2. Method main
and is ported onto various hardware-based
platforms to name a few common in the 1./**
market are Microsoft Internet Explorer and 2. *The HelloWorld class implements an
Netscape Navigator. application that
JAVA APPLICATION PROGRAMMING INTERFACE 3. *simply displays "Hello Java!" to the standard
output.
→ Java API is a large collection of ready-made
4.*/
software components that provide many
useful capabilities, such as graphical user
interface (GUI) widgets. The Java API is Line 1 to 4: Are what we call doc comments. The
grouped into libraries (packages) of related program simply ignores any statements that are
components. inside a comments.
5. public class HelloWorld
Line 5: Is the class heading. Everything that you
use must be a part of a class. When you write
public class HelloWorld, you are defining a class
named HelloWorld. The reserved word public is
an access modifier. An access modifier defines
the circumstances under which a class can be
accessed. Public access is the most liberal type
of access.
WHAT JAVA CAN DO?
6. {
→ Most well-known Java programs are Java
applets. Line 6: Begins the body of the program with the
use of open brace {
→ An applet is a Java program that adheres to
certain conventions that allow it to run within a 7. public static void main(String args[])
Java-enabled browser.
Line 7: The first method that java program executes is
the main(). In the method header, static means
showing little change or stationary. Static also means
unchanging and indicates that every member
created for the HelloWorld class will have an identical,
unchanging main(). (String[] args) is an argument.
An argument consist of information that a method
requires to perform its task. String represents a Java
class that can be used to represent character strings.
The identifier args is used to hold any Strings that
might be sent to main(). The main() method could do
something with those arguments such as printing
them but in line 7, the main() does not actually use
the args identifier. Nevertheless, you must place an
identifier within the main() method’s parenthesis. The
identifier need not be named args. It could be any
legal Java identifier but by convention, we use the
args identifier.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 01: INTRODUCTION TO OOP
8. { DATA TYPES
→ All variables in the Java language must
Line 8: Begins the body of the main() with the
have a data type.
use of the symbol {
→ A variable's data type determines the
values that the variable can contain and the
9. System.out.println("Hello World!");
operations that can be performed on it.
Line 9: This statement displays Hello World! on For example:
the screen. Within the statement The declaration int count declares that count
System.out.println(“Hello World”); System is a is an integer (int). Integers can contain only
class. Out is an object. The out object represents integral values (both positive and negative),
the screen. One of the System’s object is the out and you can use the standard arithmetic
object. Println is a method that prints a line of operators (+, -, *, and /) on integers to perform
output on the screen then positions the cursor on the standard arithmetic operations (addition,
the next line. The dots in the statement subtraction, multiplication, and division,
System.out.println are used to separate Class, respectively).
object and method. Classes, objects and
methods are further discussed in the next module
10. }
Line 10: Ends method main()
11. }
Line 11: Ends class HelloWorld
RULES OF JAVA PROGRAMMING
→ Java is just like its predecessor C is case-
sensitive language. Always check for the
proper casing when writing and encoding java
program. Statements must terminate with ;
VARIABLES NAMES
VARIABLES AND DATA TYPES → A program refers to a variable's value by its
name.
→ Variables are the nouns of a programming → It must be a legal Java identifier comprised
language-that is, they are the entities (values of a series of Unicode characters. Unicode is a
and data) that act or are acted upon. character-coding system designed to
→ A variable declaration always contains two support text written in diverse human
components: the type of the variable and its languages.
name. → It allows for the codification of up to 65,536
→ The location of the variable declaration, characters, currently 34,168 have been
that is, where the declaration appears in assigned.
relation to other code elements, determines
its scope.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 01: INTRODUCTION TO OOP
VARIABLES NAMES
final int blankfinal;
→ This allows you to use characters in your
. . . blankfinal = 0;
Java programs from various alphabets, such
as Japanese, Greek, Cyrillic, and Hebrew. This A final variable that has been declared but not
is important so that programmers can write yet initialized is called a blank final. Again,
code that is meaningful in their native once a final variable has been initialized it
languages. cannot be set and any later attempts to
→ It must not be a keyword or a boolean literal assign a value to blankfinal result in a
(true or false). compile-time error.
→ Must not have the same name as another
variable whose declaration appears in the
same scope.
OPERATORS
ARITHMETIC OPERATORS
→ The Java language supports various
arithmetic operators for all floating-point and
integer numbers
→ These includes:
+ (addition)
VARIABLE INITIALIZATION
- (subtraction)
Local variables and member variables can be * (multiplication)
initialized with an assignment statement / (division)
when they're declared. The data type of both % (modulo).
sides of the assignment statement must
match.
int count = 0;
The value assigned to the variable must
match the variable's type.
FINAL VARIABLES
→ You can declare a variable in any scope to
be final, including parameters to methods and
constructors.
→ The value of a final variable cannot change
after it has been initialized.
final int aFinalVar = 0;
Previous statement declares a final variable
and initializes it, all at once. Subsequent
attempts to assign a value to aFinalVar result
in a compiler error. You may, if necessary, defer
initialization of a final variable. Simply declare
the variable and initialize it later, like this:
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 01: INTRODUCTION TO OOP
RELATIONAL AND CONDITIONAL OPERATORS
→ A relational operator compares two values
and determines the relationship between
them.
Relational operators often are used with the
conditional operators to construct more
complex decision-making expressions. One
such operator is &&, which performs the
boolean and operation. You can use two
different relational operators along with && to
determine if both relationships are true.
Java supports one other conditional operator
the ?: operator. This operator is a ternary
operator and is basically short-hand for an if-
else statement.
The ?: operator evaluates expression and
returns op1 if it's true and op2 if it's false
example: int x = 5, y = 6, z = 0; x > y ? z=x : z=y;
since the expression x > y evaluates to false x++
operator is performed.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 02: Input statements and Control Flow Statements
JAVA INPUT STATEMENTS SCANNER
→ To put data into variables from the standard → Used to get user input of the primitive types.
input device (keyboard) we can use the
Syntax:
predefined Java class such as BufferedReader
static Scanner console = new
and Scanner.
Scanner (System.in);
BUFFERED READER Statement creates the input stream object
console and associates it with the standard
→ A java class to read the text from an input
input device. (Note that the Scanner is a
stream by buffering characteristics that
predefined Java class and theabove
seamlessly reads characters, arrays or lines.
statement creates console to be an object of
Syntax: this class). The object console reads the next
BufferedReader buffread = new input as follows:
BufferedReader(new
InputStreamReader(System.in));
a. for integer
Statement creates the input stream object console.nextInt()
buffread (user-defined word) and associates it
with the standard input device. (Note that the b. for floating-point number
BufferedReader is a predefined Java class and console.nextDouble()
the above statement creates buffread to be an
object of this class). The object buffread reads c. for strings
the input as follows: console.next()
a. for integer d. for string with a line
Integer.parseInt(buffread.readLine()) console.nextLine()
b. for floating-point number Note: When using Scanner, import java.util.*;
Double.parseDouble(buffread.readLine()) (java utilities package) must be declared
before the class declaration.
c. for strings
buffread.readLine()
PARSING (Parse Method)
→ Static method and can have one argument
or two that reads the value of one object to
convert it to another type.
Note: When using BufferedReader, import
java.io.*; (java input/output package) must
be declared before the class declaration and Note: When using parsing/parse, you must
throws IOException keywords must be included input the value/s when executing the program.
in the main declaration. Example: InputData3 juan cruz 20 110.00.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 02: Input statements and Control Flow Statements
INPUT DIALOG BOX
Line 2 tells the compiler to load the
→ Used to get input from the user.
JOptionPane class from javax.swing package.
Example: This package contains many classes that help
import javax.swing.JOptionPane; in defining graphical user interfaces (GUIs). GUI
public class InputData4 components facilitate data entry by the user of
{ public static void main(String args[]) your program and formatting or presentation
{ String name; of data outputs to the user of your own
name=JOptionPane.showInputDialog("Enter program.
your name ");
System.exit(0); Line 6 indicate a call to method
} showMessageDialog of class JOptionPane. The
} method in line 6 contains 2 arguments. The first
argument helps the Java application
DISPLAYING TEXT IN A DIALOG BOX determine where to position the dialog box.
When the first argument is “null”, the dialog box
appears at the center of the screen. The title
Java’s numerous predefined classes are
bar of the dialog box contains the string
grouped into categories of related classes
Message, to indicate that the dialog box is
called packages. The packages are referred
presenting a message to the user. The dialog
collectively as the Java class library, or Java
box automatically contains the OK button that
applications programming interface (API). The
allows the user to dismiss (hide) the dialog box
packages of the Java API are split into core
by clicking the button.
packages and extension packages. The names
of the packages begin with either “java” (core
Line 7 uses a static method exit of class System
packages) or “javax” (extension packages).
to terminate the application. The argument 0
Java’s class JOptionPane provides
to method exit indicates that the application
prepackaged dialog boxes that enable
has terminated successfully. A non-zero value
programs to display messages to users.
normally indicates that an error has occurred.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 02: Input statements and Control Flow Statements
The program in the previous page uses
another predefined dialog box from
JOptionPane called an input dialog that allows
the user to input a value for use in the program.
The program also uses a message dialog to
display the value entered in the input dialog
box.
Line 4 declares a string variable named
“name” that will hold whatever value is entered
in the input dialog.
Line 5 reads from the user a string value.
Method JOptionPane.showInputDialog displays
the input dialog in the previous page. The
argument to showInputDialog indicates what
the user should type in the textfield. The result
of JOptionPane method showInputDialog is CONTROL FLOW STATEMENTS
assigned to variable name. After the input has → Control flow statements determine the order
been made. in which other statements are executed.
Line 6 displays the message dialog box. In this
example, the method showMessageDialog
contains four arguments. The first argument
indicates that the message dialog will appear
at the center, the second argument is the
message to display. In this case the second
argument is : “Hello “ + name The third and
fourth arguments represent the string that
should appear in the dialog box’s title bar and
dialog box type respectively. The fourth
argument – JOptionPane.PLAIN_MESSAGE is a
value indicating the type of message dialog to
display. This type of message does not display
an icon to the left of the message.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 02: Input statements and Control Flow Statements
IF-ELSE STATEMENT DO-WHILE LOOP
→ Provides your programs with the ability to → Runs at least once, even if condition is false.
selectively execute other statements based
on some criteria.
→ Simplest version of the if statement: the
statement governed by the if is executed if
some condition is true. Generally, the simple
form of if can be written like this:
if (expression)
FOR LOOP
statement to do if expression is true;
→ Best for counted/known repetitions.
If the expression is false. You can use
the else statement for that.
if (expression)
statement to do if expression is true;
else
statement to do if expression is false;
LOOP CONTROL STATEMENT
SWITCH STATEMENT
Break
→ Perfect when testing a variable against
→ Exits the loop immediately
multiple possible values.
Continue
→ Skips the current iteration and goes to the
next.
NESTED LOOPS
→ A loop inside another loop – often used for
printing patterns.
Note: Don’t forget break; to avoid fall-through.
LOOPING STATEMENT
WHILE LOOP
→ Keeps running while condition is true.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 03: Arrays and Strings
ARRAYS DECLARING STRINGS
→ A collection of elements with the same data
type
→ Stored in contiguous memory locations
→ Elements are accessed using indexes,
starting from 0 COMMON STRING METHODS
DECLARING AND INITIALIZING ARRAYS
Note: All elements are automatically initialized
to 0.
ACCESSING ARRAY ELEMENTS
USING LOOP TO TRAVERSE AN ARRAY STRING COMPARISON
→ You're comparing two Strings, a and b.
COMMON ARRAY OPERATIONS
STRINGS
→ A sequence of characters Output:
→ In Java, it's an object of the String class
→ Strings are immutable (cannot be changed
once created)
Note: a.equals(b) → false (because "hello" ≠
"HELLO")
a.equalsIgnoreCase(b) → true (because
"hello" = "HELLO" if case is ignored)
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 03: Arrays and Strings
ARRAYS OF STRING
→ You're creating an array of Strings with 3
names. Then you're using a for loop to display
each one.
Output:
Note: names.length
length - gives the total number of
elements in the array
In this case, names.length=3 because
there are 3 heroes
CONVERT STRING TO INT
→ You have a String (like text) with digits: "123"
You use Integer.parseInt() to convert it into an
actual integer.
s was “123“ → a string
x becomes “123“ → an int
Note: Always make sure the string is only digits
before parsing because if not it’s going to
crash.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 04: Methods
2. With Parameters, No Return
METHODS
→ Use this to perform actions with input data,
→ Block code that performs a task
but not return anything back.
→ Java version of functions in other languages
→ Promotes reusability and modularity
WHY SHOULD WE USE METHOD
→ Avoid repeating code
→ Organize logic in to small parts
→ To make code readable and maintainable 3. With Parameters, With Return
→ Reuse logic with different values → Use this when you need to process input and
give back a result (value).
BASIC METHOD STRUCTURE
4. No Parameters, With Return
CALLING A METHOD
→ You call or invoke a method inside main() or
another method:
METHOD OVERLOADING
→ You can have multiple methods with the
TYPES OF METHOD same name, but different parameters:
1. No Parameter, No Return
→ Use this when you just want to do something,
not compute or send back a result.
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 04: Methods
PASSING ARRAYS TO METHOD
→ Arrays are passed by reference, so if you
modify the array inside the method —
the original gets changed too
RETURNING A VALUE
CALLING METHODS FROM ANOTHER CLASS
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 05: Class and Objects
CLASS CREATING AND USING AN OBJECT
→ A class is like a blueprint or template used to
create objects.
Output:
INSTANCE VARIABLES AND METHODS
Note: Think of a class as a "design" for a thing —
like a plan for a car or a cellphone. It doesn’t do Term Description
anything until you create an object from it
Belongs to the
OBJECT
object; each
→ An object is an instance of a class. Instance variable
object has its own
copy
Can access and
Instance method modify instance
variables
Note: It’s the real-world version made from the
blueprint (the class). If Dog is the blueprint, ACCESS MODIFIERS
myDog is the actual dog.
Modifier Meaning
STRUCTURE OF A CLASS
public Accessible anywhere
Accessible only within the
private
class
Accessible within the same
protected
package or subclass
Package-private (default
(no modifier)
access)
OBJECT ORIENTED PROGRAMMING | Second Semester
Comp 009
UNIT 06: OVERLOADING CONSTUCTORS
CONSTRUCTOR PARAMETERIZED CONSTRUCTOR
→ A special method in Java used to initialize
objects when they are created.
💡 It has:
The same name as the class
No return type (not even void)
Automatically called when an object is
instantiated (new)
WHY DO WE NEED TO USE CONSTRUCTORS Usage:
To automatically set values when
creating objects
To reduce repetitive code CONSTRUCTOR OVERLOADING
To ensure that objects start in a valid
state
TYPES OF CONSTRUCTORS
Type Description
Takes no
Default
arguments, sets
Constructor
default values
Parameterized Takes arguments
Constructor to initialize fields
Usage:
DEFAULT CONSTRUCTOR
Note:
Constructors can initialize multiple fields
They are not inherited, but you can call parent
constructors using super()
Usage:
If you don’t write a constructor, Java provides a
default one
If you write at least one constructor, the default
is no longer available unless you define it
explicitly