Java Object-Oriented Programming Course
Java Object-Oriented Programming Course
of
Information Technology
1
[Link] from one phase to another is difficult [Link] from one phase to another is easier
OO methods enables to create set of objects that work together to produce software that better
model the problem domains than similar systems produced by traditional techniques.
▪ Since objects encapsulate both data (attributes) and functions (methods), they work at a higher level of
abstraction.
▪ The development can proceed at the object level and ignore the rest of the system for as long as necessary.
▪ This makes designing, coding, testing, and maintaining the system much simpler.
REASONS FOR WHY OBJECT ORIENTATION WORKS?
• The traditional approach to software development requires different styles and methodologies for each step of the
process.
• Moving from one phase to another requires complex transition of perspective between models that almost can be in
different worlds.
• The transition not only can slow the development process but also increases the size of the project and the chance for
errors introduced in moving from one language to another.
• The object oriented approach essentially uses the same language to talk about analysis, design, programming, and
database design.
• This seamless approach reduces the level of complexity and redundancy and makes for clearer, more robust system
development.
REASONS FOR WHY OBJECT ORIENTATION WORKS?
▪ The routines and attributes within a class are held together tightly.
▪ In a properly designed system, the classes will be grouped into subsystems but remain independent; therefore, changing
one class has no impact on other classes and so the impact is minimized.
▪ By raising the level of abstraction from the function level to the object level and by focusing on the real-world aspects
of the system, the OO method tends to promote clearer designs; which are easier to implement, and provide for better
overall communication.
REASONS FOR WHY OBJECT ORIENTATION WORKS?
4. PROMOTION OF REUSABILITY.
• Objects are reusable because they are modeled directly out of a real-world problem domain.
• Each object stands by itself or within a small circle of peers (other objects).
• Within this framework, the class does not concern itself with the rest of the system or how it is going to be used within a
particular system.
• This means that classes are designed generically, with reuse as a constant background goal.
• The object orientation adds inheritance, which is a powerful technique that allows classes to be built from each other;
• Therefore, only differences and enhancements between the classes need to be designed and coded.
• All the previous functionality remains and can be reused without change.
What is Java?
• James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of Sun Microsystem engineers called Green
Team.
• Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt
• Initially it was designed for small, embedded systems in electronic appliances like
set-top boxes.
• After that, it was called Oak and was developed as a part of the Green project.
• In 1995, Oak was renamed as "Java"
Why Java Programming named "Java"?
• Java was callead Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
• Java is an island in indonesia where he first coffee was produced ( called java
coffee)
Java Version History
[Link] Alpha and Beta (1995) [Link] 1.0 (23rd Jan 1996)
[Link] 1.1 (19th Feb 1997) 4.J2SE 1.2 (8th Dec 1998)
5.J2SE 1.3 (8th May 2000) 6.J2SE 1.4 (6th Feb 2002)
7.J2SE 5.0 (30th Sep 2004) [Link] SE 6 (11th Dec 2006)
[Link] SE 7 (28th July 2011) [Link] SE 8 (18th Mar 2014)
[Link] SE 9 (21st Sep 2017) [Link] SE 10 (20th Mar 2018)
[Link] SE 11 (September 2018) [Link] SE 12 (March 2019)
[Link] SE 13 (September 2019) [Link] SE 14 (Mar 2020)
[Link] SE 15 (September 2020) [Link] SE 16 (Mar 2021)
[Link] SE 17 (September 2021) [Link] SE 18 (to be released by March 2022)
Features of Java
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic
Java Programming paradigms
• Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different
types of objects that incorporate both data and behavior.
• This is controlled by the following four paradigms
• OOPS concepts
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Bytecode
• The Java Virtual Machine (JVM) translates the byte code into machine language
The evolution of Java
• Java application program interface (API) contains the predefined classes and
interfaces for developing Java programs.
Java API
There are 3 editions of the Java API:
• Java 2 standard edition (J2SE)
Client‐side standalone applications or applets.
• Java 2 Enterprise Edition (J2EE)
Server‐side applications, such as Java servlets and JavaServer Pages.
• Java 2 Micro Edition (J2ME) Java 2 Micro Edition (J2ME)
Mobile devices, such as cell phones or pda.
Difference between JDK, JRE, and JVM
JVM
JVM (Java Virtual Machine) is an abstract machine.
It is a specification that provides a runtime environment in which Java bytecode can
be executed.
Loads code
Verifies code
Executes code
Provides runtime environment
JRE
The Java Runtime Environment is a set of software tools which are used for
developing Java applications.
It is used to provide the runtime environment.
It is the implementation of JVM.
JDK
The Java Development Kit (JDK) is a software development environment which is
used to develop Java applications and applets.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
• Its is a sequence of characters that consists of letters, digits, underscores (_), and
dollar signs ($).
• It must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a
digit.
• It cannot be a reserved word.
• It cannot be true, false, or null.
• It can be of any length.
• The syntax for declaring a variable is
datatype variableName;
int count;
double radius;
• int i, j, k;
• int count = 1;
• int count;
count = 1;
• int i = 1, j = 2;
Types of variables
• Local Variables
• Instance Variables
• Static Variables
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
• negating an expression ( ~ )
The Java left shift operator << is used to shift all of the bits in a value to
the left side of a specified number of times.
The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
public class OperatorExample{
public static void main(String args[]){
[Link](10<<2);
[Link](10<<3);
[Link](20<<2);
[Link](15<<4);
}}
public OperatorExample{
public static void main(String args[]){
[Link](10>>2);
[Link](20>>2);
[Link](20>>3);
}}
Relational Operators
• Comparison operators are used to compare two values:
public class OperatorExample{
public static void main(String[] args) {
int a = 7, b = 11;
[Link]("a is " + a + " and b is " + b);
// == operator
[Link](a == b);
// != operator
[Link](a != b);
// > operator
[Link](a > b);
// < operator
[Link](a < b);
// >= operator
[Link](a >= b);
// <= operator
[Link](a <= b);
}
}
Logical Operators
// && operator
[Link]((5 > 3) && (8 > 5));
[Link]((5 > 3) && (8 < 5));
// || operator
[Link]((5 < 3) || (8 > 5));
[Link]((5 > 3) || (8 < 5));
[Link]((5 < 3) || (8 < 5));
// ! operator
[Link](!(5 == 3));
[Link](!(5 > 3));
}
}
Bitwise operators
// bitwise and
// 0101 & 0111=0101 = 5
[Link]("a&b = " + (a & b));
// bitwise or
// 0101 | 0111=0111 = 7
[Link]("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
[Link]("a^b = " + (a ^ b));
}
}
Ternary Operator
Ternary operator is used as one line replacement for if-then-else
statement
Type conversion
A data type is automatically converted into another data type by a compiler at the compiler time. It is also called widening
conversion
int x=30;
float y;
y=x; // y==30.000000.
float x;
byte y;
... ...
y=(byte)x;
[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
}
}
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
• Simple if statement
• if-else statement
• if-else-if ladder
• Nested if-statement
• Simple if statement:
if(condition) {
statement 1; //executes when condition is true
• if-else statement
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
• if-else-if ladder:
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
• Nested if-statement
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
• Switch Statement:
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
• Loop Statements
• for loop
for(initialization, condition, increment/decrement) {
//block of statements
}
for-each loop
• The forEach() method is also used to loop through arrays, but it uses a function differently than the
classic “for loop”. It passes a callback function for each element of an array together with the below
parameters:
• Current Value (required): The value of the current array element
• Index (optional): The index number of the current element
• Array (optional): The array object the current element belongs to
while(condition){
//looping statements
}
• do-while loop
do
{
//statements
} while (condition);
• Jump Statements
break statement
Syntax :
datatype[ ] identifier;
or datatype identifier[ ];
Example:
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
Initialization of Array
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Syntax:
datatype[ ][ ] identifier;
or datatype identifier[ ][ ];
Example:
int[ ][ ] arr = new int[10][10];
Or
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
• Jagged Array
class Test {
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr) { [Link](x);
}}}
Read input from console in Java
import [Link];
nextByte()
nextShort()
nextInt()
nextLong()
nextFloat()
nextDouble()
next()
nextLine()
import [Link];
class GetInputFromUser {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner([Link]);
String s = [Link]();
[Link]("You entered string " + s);
int a = [Link]();
[Link]("You entered integer " + a);
float b = [Link]();
[Link]("You entered float " + b);
}
}
Class
class ClassName {
// fields // data member
// methods
}
INTRODUCTION
The main motivation of object oriented system design is to make software development easier and more natural by raising the
level of abstraction.
WHAT IS AN OBJECT?
A real world entity, identifiably separate from the surroundings.
An entity that has state and behavior is known as an object
Example: chair, bike, marker, pen, table, car, etc.
▪ Methods (properties or functions) define its behavior such as deposit, withdraw, etc.
OBJECTS
▪ Combination of data and logic that represents some real world entity.
▪ In the Car example the car’s attributes are: color, manufacturer, cost, owner, model, etc.
▪ In the Car example the car’s methods are: drive it, lock it, change mileage, stop, start, carry passenger in it.
▪ Programming in an object oriented system consist of adding new kinds of object to the system and defining how they
behave.
INTRODUCTION-OBJECT
Example 1:
INTRODUCTION-OBJECT
Example 2:
INTRODUCTION-OBJECT
Example 3:
INTRODUCTION-OBJECT
Example 5:
INTRODUCTION-OBJECT
Example 4:
Class defines common characteristics or properties of an object. Class is a template or blue print to define object.
Object is an instance of a class having specific values of common properties.
INTRODUCTION-OBJECT
▪ OBJECT’S ATTRIBUTES
▪ OBJECT’S METHODS
Methods define objects behavior and specify the way in which an Object’s data are manipulated.
In the Car example the car’s methods are: drive it, lock it, tow it, carry passenger in it.
Objects
• An entity that has state and behaviour is known as an object
}
public static void main(String[] args) {
Counter(){
count++;//incrementing value
[Link](count);
}
Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}
returnType methodName() {
// method body
}
int addNumbers() {
// code
}
// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
// create a method
public static int square(int num) {
// return statement
return num * num;
}
• The standard library methods are built-in methods in Java that are
readily available for use.
For example,
// method defined
private static int getSquare(int x){
return x * x;
}
// method call
int result = getSquare(i);
[Link]("Square of " + i + " is: " + result);
}
}
}
Passing Parameter by value
// method defined
private static void increment(int n){
n++;
[Link](“n inside the method is : “ + n);
}
}
How to initialize an object?
Constructor
// constructor
Main() {
[Link]("Constructor Called:");
name = "Program";
}
class Main {
int i;
// constructor with no parameter
private Main() {
i = 5;
[Link]("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
[Link]("Value of i: " + obj.i);
}
}
Parameterized Constructor
• A Java constructor can also accept one or more parameters. Such constructors are known as parameterized
constructors (constructor with parameters).
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
[Link](languages + " Programming Language");
}
public static void main(String[] args) {
class Main {
int a;
boolean b;
public static void main(String[] args) {
// A default constructor is called
Main obj = new Main();
[Link]("Default Value:");
[Link]("a = " + obj.a);
[Link]("b = " + obj.b);
}
}
JAVA Constructor vs Method
Constructor
1. Constructor is used to initialize the state of an object.
2. Constructor must not have return type.
3. Constructor is invoked implicitly.
4. The java compiler provides a default constructor if you don't have any
constructor.
5. Constructor name must be same as the class name.
Method
1. Method is used to expose behavior of an object.
2. Method must have return type.
3. Method is invoked explicitly
4. Method is not provided by compiler in any case.
5. Method name may or may not be same as class name.
Java Package
A package is simply a container that groups related types (Java classes,
interfaces, enumerations, and annotations).
❖Built-in package
❖User-defined package.
Built-in Packages
1) [Link]
2) [Link]
3) [Link]
4) [Link]
5) [Link]
6) [Link]
• Package, Sub-Package & Classes
• User-defined package
These are the packages that are defined by the user.
The package keyword is used to create a package in java.
//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}
⮚ import package.*;
⮚ import [Link];
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using [Link]
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using fully qualified name
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
What will happen now?
import [Link];
import [Link];
Java programming is that only one unique class name is allowed in a Java
project.
Name Conflicts
import [Link];
import [Link].*;
[Link] deadLine = new [Link]();
[Link] today = new [Link]();
Advantage of Java Package
Modifier Description
package defaultPackage;
class Logger {
void message(){
[Link]("This is a message");
}
}
Private Access Modifier
class Data {
// private variable
private String name;
}
// getter method
public String getName() {
return [Link];
}
// setter method
public void setName(String name) {
[Link]= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();
// public method
public void display() {
[Link]("I am an animal.");
[Link]("I have " + legCount + " legs."); }}
// [Link]
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();