[Go to site: main page, start]

0% found this document useful (0 votes)
2 views41 pages

Module I - Basic Java 1

The document provides an overview of Object-Oriented Programming (OOP) using Java, detailing the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). It explains Java's features, types of applications, and basic concepts of OOP, including classes, objects, inheritance, and polymorphism. Additionally, it covers Java's syntax, data types, operators, and control statements such as if-else.

Uploaded by

Chandramani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views41 pages

Module I - Basic Java 1

The document provides an overview of Object-Oriented Programming (OOP) using Java, detailing the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK). It explains Java's features, types of applications, and basic concepts of OOP, including classes, objects, inheritance, and polymorphism. Additionally, it covers Java's syntax, data types, operators, and control statements such as if-else.

Uploaded by

Chandramani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem.

CSE

MODULE I
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a
Javaprogram. There are three notions of the JVM: specification, implementation, and instance. The
specification is a document that formally describes what is required of a JVM implementation. Having a single
specification ensures all implementations are interoperable. A JVM implementation is a computer program that
meets the requirements of the JVM specification. An instance of a JVM is an implementation running in a
process that executes a computer program compiled into Java bytecode.
Java Runtime Environment (JRE) is a software package that contains what is required to run a Java program.
It includes a Java Virtual Machine implementation together with an implementation of the Java Class Library.
The Oracle Corporation, which owns the Java trademark, distributes a Java Runtime environment with their
Java Virtual Machine
called HotSpot.

Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers,
e.g. a javaccompiler. The Java Development Kit is provided free of charge either by OracleCorporation directly,
or by theOpenJDK open source project, which is governed by Oracle.
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a
Javaprogram. There are three notions of the JVM: specification, implementation, and instance. The
specification is a document that formally describes what is required of a JVM implementation. Having a single
specification ensures all implementations are interoperable. A JVM implementation is a computer program that
meets the requirements of the JVM specification. An instance of a JVM is an implementation running in a
process that executes a computer program compiled into Java bytecode.
Java Runtime Environment (JRE): is a software package that contains what is required to run a Java
program. It includes a Java Virtual Machine implementation together with an implementation of the Java Class
Library. The Oracle Corporation, which owns the Java trademark, distributes a Java Runtime environment with
their Java Virtual Machine
called HotSpot.

Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers,
e.g. a javaccompiler. The Java Development Kit is provided free of charge either by OracleCorporation directly,
or by theOpenJDK open source project, which is governed by Oracle.

By Er. RAHAMATULLA (Assistant Professor) Page 1 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

java
 Java is a programming language and a platform.
 Java is a high level, robust, secured and object-oriented programming language.
 Platform: Any hardware or software environment in which a program runs, is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform.
Java Example
class Simple{
public static void main(String args[])
{
[Link]("Hello Java");
}
}

Applications of java
There are many devices where java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as [Link], [Link] etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

Types of Java Applications


There are mainly 4 type of applications that can be created using java programming:
1) Standalone Application
It is also known as desktop application or window-based application. An application that weneed to install
on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone
applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application. Currently,
servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage of high level
security, load balancing and clustering. In java, EJB is used for creating enterprise applications.

4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used forcreating mobile
applications.

By Er. RAHAMATULLA (Assistant Professor) Page 2 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Features of Java
 Simple
 Object-Oriented
 Platform Independent
 secured
 Robust
 Architecture Neutral
 Portable
 High Performance
 Distributed
 Multi-threaded

Simple
There is given many features of java. They are also known as java [Link]

According to Sun, Java language is simple because:

Syntax is based on C++ (so easier for programmers to learn it after C++).java removed many confusing and/or rarely-
used features e.g., explicit pointers, operator overloading etc. No need toremove unreferenced objects because there is
Automatic Garbage Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types of objects thatincorporates both
data and [Link]-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.

Basic concepts of OOPs are:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Platform Independent :java is platform independent.A platform is the hardware or software


environment in which a [Link] are two types of platforms software-based and hardware-based. Java
provides software- based platform.

The Java platform differs from most other platforms in the sense that it is a software-based
platformthat runs on the top of other hardware-based platforms. It has two components:

 Runtime Environment
 API(Application Programming Interface)

Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).

By Er. RAHAMATULLA (Assistant Professor) Page 3 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Secured
Java is secured because:

 No explicit pointer
 Java Programs run inside virtual machine sandbox

how java is secured

Classloader: adds security by separating the package for the classes of the local file system from
those that are imported from network sources. Bytecode Verifier: checks the code fragments for
illegal codethat can violate access right to objects.

Security Manager: determines what resources a class can access such as reading and writing to the
[Link] security are provided by java language. Some security can also be provided by
application developer through SSL, JAAS, Cryptography etc.

Robust

Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security
problem. There is automatic garbage collection in java. There is exception handling andtype checking mechanism in java.
All these points makes java robust.

Architecture-neutral

There is no implementation dependent features e.g. size of primitive types is fixed.


In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes ofmemory for 64-bit
architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.

Portable

We may carry the java bytecode to any platform.

By Er. RAHAMATULLA (Assistant Professor) Page 4 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

High-performance

Java is faster than traditional interpretation since byte code is "close" to native code still somewhatslower than a
compiled language (e.g., C++)

Distributed

We can create distributed applications in java. RMI and EJB are used for creating distributedapplications. We may access
files by calling the methods from any machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at
once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media, Web applications etc.
Creating hello java example
class Simple{
public static void main(String args[]){
[Link]("Hello Java");4. }
}

Save this file as [Link]


To compile: javac [Link]

To execute: java Simple


Output: Hello Java
Understanding first java program

Let's see what is the meaning of class, public, static, void, main, String[],
[Link]().
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it means it is visibleto all.

 static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method. The
main method is executed by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.

 void is the return type of the method, it means it doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument..
 [Link]() is used print statement.

By Er. RAHAMATULLA (Assistant Professor) Page 5 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtimeenvironment
in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). It is:
The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

Variables and Data Types in Java


Variable is a name of memory location. There are three types of variables in java: local,
instanceand static. There are two types of data types in java: primitive and non-primitive.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of
memorylocation. It is a combination of "vary + able" that means its value can be changed.

variables in java

int data=50;//Here data is

variableTypes of Variable

There are three types of variables in java:

 local variable
 instance variable
 static

variable types of

variables in java

1) Local Variable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is called instance
variable .It is not declared as static.

By Er. RAHAMATULLA (Assistant Professor) Page 6 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

3) Static variable

A variable that is declared as static is called static variable. It cannot be local. Example to understand the types
of variables in java
class A{
int data=50;//instance
variable static int
m=100;//static variablevoid
method()
{
int n=90;//local variable
}
}//end of class

Data Types in Java


Data types represent the different values to be stored in the variable. In java, there are two
typesof data types:

 Primitive data types


 Non-primitive data types
 datatype in java

Data Type Default Value Default size


Boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

By Er. RAHAMATULLA (Assistant Professor) Page 7 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Operators in java
Operator in java is a symbol that is used to perform operations. There are many types of

operators in java such as unary operator, arithmetic operator, relational operator, shift
operator, bitwise operator, ternary operator and assignment operator.

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &

By Er. RAHAMATULLA (Assistant Professor) Page 8 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java If-else Statement


The Java if statement is used to test the condition. It checks boolean condition: true or
[Link] are various types of if statement in java.

 if statement
 if-else statement
 nested if statement
 if-else-if ladder
Java IF Statement

The Java if statement tests the condition. It executes the if block if condition is [Link]:

if(condition){

//code to be executed
}
if statement in javaExample:

public class IfExample {

public static void main(String[] args) {int age=20;


if(age>18)
{
[Link]("Age is greater than 18");
}
}
}

Output:

Age is greater than 18

By Er. RAHAMATULLA (Assistant Professor) Page 9 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Java IF-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is trueotherwise else
block is executed.
Syntax:

if(condition){
//code if condition is true

}else{
//code if condition is false

}
if-else statement in javaExample:
public class IfElseExample {
public static void main(String[] args) {int number=13;

if(number%2==0){ [Link]("even number");

}else{

[Link]("odd number");
}

}
}

Output: odd number

By Er. RAHAMATULLA (Assistant Professor) Page 10 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

11

Java IF-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple [Link]:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
... else{

//code to be executed if all the conditions are false


}

if-else-if ladder statement in javaExample:


public class IfElseIfExample {
public static void main(String[] args) {int marks=65;
if(marks<50){ [Link]("fail");
}
else if(marks>=50 && marks<60){[Link]("D grade");
}
else if(marks>=60 && marks<70){[Link]("C grade");

}
else if(marks>=70 && marks<80){[Link]("B grade");
}
else if(marks>=80 && marks<90){[Link]("A grade");
}else if(marks>=90 && marks<100){[Link]("A+ grade");
}else{
[Link]("Invalid!");
}
}
}

Output:C grade

By Er. RAHAMATULLA (Assistant Professor) Page 11 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Java Switch Statement


The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement.
Syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
default:
code to be executed if all cases are not matched;

By Er. RAHAMATULLA (Assistant Professor) Page 12 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Example:

public class SwitchExample {


public static void main(String[] args) {
int number=20;
switch(number){
case 10: [Link]("10");break;
case 20: [Link]("20");break;
case 30: [Link]("30");break;
default:[Link]("Not in 10, 20 or
30"); 9. }
}
}
Output: 20.

Java Switch Statement is fall-through


The java switch statement is fall-through. It means it executes all statement after first
match if break statement is not used with switch cases.
Example:
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: [Link]("10");
case 20: [Link]("20");
case 30: [Link]("30");
default:[Link]("Not in 10, 20 or 30");9.
}
}
}
Output: 20
30
Not in 10, 20 or 30

Java For Loop


The Java for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for [Link] are three types of for loop in java.

o Simple For Loop


o For-each or Enhanced For Loop
o Labeled For Loop

Java Simple For Loop


The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.

Syntax:

By Er. RAHAMATULLA (Assistant Professor) Page 13 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

for(initialization;condition;incr/decr){
//code to be executed 3.
}

Output:
1 2 3 4 5 6 7 8 9 10

Example:
public class ForExample {
public static void main(String[] args) {3.
for(int i=1;i<=10;i++){
[Link](i);
}

Java While Loop


The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:

while(condition){
//code to be executed 3.
}

By Er. RAHAMATULLA (Assistant Professor) Page 14 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Example:

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){

[Link](i); 6. i++;

Output:

1 2 3 4 5 6 7 8 9 10

Java do-while Loop


The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:

do{
//code to be executed
}while(condition);

By Er. RAHAMATULLA (Assistant Professor) Page 15 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Example:

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
[Link](i); 6. i++;
}while(i<=10);

Output:

1 2 3 4 5 6 7 8 9 10

By Er. RAHAMATULLA (Assistant Professor) Page 16 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Java Break Statement


The Java break is used to break loop or switch statement. It breaks the current flow of the program at
specified condition. In case of inner loop, it breaks only inner loop.
Syntax:

1. jump-statement;
2. break;

Java Break Statement with Loop


Example:

public class BreakExample {


public static void main(String[] args) { 3.
for(int i=1;i<=10;i++){
if(i==5){

break;

[Link](i); }

Output: 1 2 3 4

Java Break Statement with Inner Loop


It breaks inner loop only if you use break statement inside the inner loop.
Example:
public class BreakExample2 {
public static void main(String[] args) {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break;
}
[Link](i+" "+j); 8. }
}
}
}
Output: 1 1 1 2 1 3 2 1 3 1 3 2 3 3

By Er. RAHAMATULLA (Assistant Professor) Page 17 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

java Continue Statement

The Java continue statement is used to continue loop. It continues the current flow of the program and skips the
remaining code at specified condition. In case of inner loop, it continues only inner loop.
Syntax:
jump-statement; continue;
Java Continue Statement Example Example:
public class ContinueExample { public static void main(String[] args) {
for(int i=1;i<=10;i++){ if(i==5){
continue;
}
[Link](i);
}
}
}
Output:
1 2 3 4 6 7 8 9 10

Java Continue Statement with Inner Loop


It continues inner loop only if you use continue statement inside the inner loop. Example:
public class ContinueExample2 {
public static void main(String[] args) { for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){ if(i==2&&j==2){
continue;
}
[Link](i+" "+j);
}
}
}
}
Output:
11 12 13 21 22 23 31 32 33

Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The comments can
be used to provide information or explanation about the variable, method, class or any statement. It can also
be used to hide program code for specific time.

There are 3 types of comments in java.

By Er. RAHAMATULLA (Assistant Professor) Page 18 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

 Single Line Comment


 Multi Line Comment
 Documentation Comment

1) Java Single Line Comment

The single line comment is used to comment only one line. Syntax:

//This is single line comment Example:

public class CommentExample1 { public static void main(String[] args) {

int i=10;//Here, i is a variable [Link](i);

Output:

10

2) Java Multi Line Comment


The multi line comment is used to comment multiple lines of code. Syntax:

/* This is multi line comment */ Example:

public class CommentExample2 { public static void main(String[] args) {

/* Let's declare and print variable in java. */

int i=10; [Link](i);

}
}
Output:

10

3) Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you need to
use javadoc tool.

Syntax:

/** This is documentation comment */ Example:

/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/ public class

Calculator {

/** The add() method returns addition of given numbers.*/ public static int add(int a, int b){return a+b;}

By Er. RAHAMATULLA (Assistant Professor) Page 19 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

/** The sub() method returns subtraction of given numbers.*/ public static int sub(int a, int b){return a-b;}

Compile it by javac tool:

javac [Link]

Create Documentation API by javadoc tool:

javadoc [Link]

Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML files
and see the explanation of Calculator class provided through documentation comment.

By Er. RAHAMATULLA (Assistant Professor) Page 20 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Java OOPs Concepts


Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some
concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction

 Encapsulation
 Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

 Class

Collection of objects is called class. It is a logical entity

 Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.

 Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convince the
customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism. Another example
can be to speak something e.g. cat speaks meaw, dog barks woof etc.
 Abstraction
Hiding internal details and showing functionality is known as abstraction. Forexample: phone call, we don't know
the internal [Link] java, we use abstract class and interface to achieve abstraction.

By Er. RAHAMATULLA (Assistant Professor) Page 21 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Encapsulation
Binding (or wrapping) code and data together into a single unit is known asencapsulation. For
example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.

Advantage of OOP over Procedure oriented Programming Language.


 OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not
easy to manage if code grows as project size grows.
 OOPs provides data hiding whereas in Procedure-oriented programming language a global data can be accessed
from anywhere.
 OOPs provides ability to simulate real-world event much more effectively. We can provide the solution of real
word problem if we are using the Object-OrientedProgramming language.

Java Naming conventions


Name Convention

class name should start with uppercase letter and be a noun e.g. String, Color,
Button,System, Thread etc.
interfac should start with uppercase letter and be an adjective e.g. Runnable,
ename Remote,ActionListener etc.

method name should start with lowercase letter and be a verb e.g. actionPerformed(),
main(),print(), println() etc.

variable name should start with lowercase letter e.g. firstName, orderNumber etc.
packag should be in lowercase letter e.g. java, lang, sql, util etc.
ename
consta should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY
nts
name
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be
physical or logical (tengible and intengible). The example of integible object is banking system.

An object has three characteristics:


o state: represents data (value) of an object.
o behavior: represents the behavior (functionality) of an object such as deposit,withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value of theID is not visible to the
external user. But,it is used internally by the JVM to identify each object uniquely.

By Er. RAHAMATULLA (Assistant Professor) Page 22 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its [Link] is used to write,
so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects arecreated. So object is the instance(result) of
a class.

Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects are
created.

A class in java can contain:


 data member
 method
 constructor
 block
 class and interface
Syntax to declare a class:

class <class_name>{
data member;
method;
}
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We are creating the
object of the Student class by new keyword and printing the objects value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student1 s1=new Student1();//creating an object of Student
[Link]([Link]);
[Link]([Link]);
8. }
}

Output: 0 null

By Er. RAHAMATULLA (Assistant Professor) Page 23 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Instance variable in Java


A variable that is created inside the class but outside the method, is known as instance [Link]
variable doesn't get memory at compile [Link] gets memory at runtime when object(instance) is
[Link] is why, it is known as instance variable.

Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
o Code Reusability
o Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.

Example of Object and class that maintains the records ofstudents


In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method on it. Here, we are displayingthe state (data) of the objects
by invoking the displayInformation method.

class Student2{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}//method
public static void main(String args[]){
Student2 s1=new Student2();
Student2 s2=new Student2();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}

By Er. RAHAMATULLA (Assistant Professor) Page 24 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

OutPut:
111 Karan

222 Aryan

As you see in the above figure, object gets the memory in Heap area and reference variable refers to the
object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the
objects allocated in memory.

Other Example:
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}

void calculateArea(){[Link](length*width);}
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle(); 12. [Link](11,5);
[Link](3,15);

[Link]();
[Link]();
16. }

17. }

Output: 55

45

Different ways to create an object in Java

There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By factory method etc.

We will learn, these ways to create the object later.

By Er. RAHAMATULLA (Assistant Professor) Page 25 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Annonymous object
Annonymous simply means [Link] object that have no reference is known as annonymous
object.

If you have to use an object only once, annonymous object is a good approach.

class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){

fact=fact*i;
}
[Link]("factorial is "+fact);8. }
public static void main(String args[]){
new Calculation().fact(5);//calling method with annonymous object
}
}
Output:Factorial is 120

By Er. RAHAMATULLA (Assistant Professor) Page 26 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Creating multiple objects by one type only


We can create multiple objects by one type only as we do in case of primitives.
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objectsLet's see the example:

class Rectangle

{
int length;
int width;
void insert(int l,int w)
{
length=l;
width=w;
}
void calculateArea(){[Link](length*width);}
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
[Link](11,5);
[Link](3,15);
[Link]();
[Link]();
}
}
Output: 55
45
Method Overloading in Java
Different ways to overload the method

 By changing the no. of arguments


 By changing the datatype
 If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
 If we have to perform only one operation, having same name of the methods increases the readability of
the program.
 Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b (int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the behavior of the method because
its name differs. So, we perform method overloading to figure out the program quickly.

By Er. RAHAMATULLA (Assistant Professor) Page 27 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Advantage of method overloading

Method overloading increases the readability of the


[Link] ways to overload the method

 There are two ways to overload the method in java


 By changing number of arguments
 By changing the data type
 In java, Method Overloading is not possible by changing the return type of the method.

1. Example of Method Overloading by changing the no. of arguments


In this example, we have created two overloaded methods, first sum method performs addition oftwo
numbers and second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b){[Link](a+b);}

void sum(int a,int b,int c)


{
[Link](a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
[Link](10,10,10);
[Link](20,20);
}
}

Output: 30 40

By Er. RAHAMATULLA (Assistant Professor) Page 28 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

2. Example of Method Overloading by changing data type of argument


In this example, we have created two overloaded methods that differs in data type. The first
summethod receives two integer arguments and second sum method receives two double
arguments.

class Calculation2{

void sum(int a,int b){[Link](a+b);}

void sum(double a,double b)

{[Link](a+b);}

public static void main(String args[]){

Calculation2 obj=new Calculation2();


[Link](10.5,10.5);

[Link](20,20);
}
}

Output:
21.
0
40

In java, method overloading is not possible by changing the return type of the method
becausethere may occur ambiguity. Let's see how ambiguity may occur: because there was
problem:

By Er. RAHAMATULLA (Assistant Professor) Page 29 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

class Calculation3{

int sum(int a,int b)

{[Link](a+b);}

double sum(int a,int b)

{[Link](a+b);}

public static void main(String args[])

Calculation3 obj=new Calculation3();

int result=[Link](20,20); //Compile Time Error


}
}

int result=[Link](20,20); //Here how can java determine which sum() method should be called

Main overloading class Overloading1{


public static void main(int a){
[Link](a);
}
public static void main(String args[]){
[Link]("main() method invoked");
main(10);
}
}
Output:

main() method invoked

10

Method Overloading and Type Promotion


One type is promoted to another implicitly if no matching datatype is found. Let's
understand theconcept by the figure given below:

Method overloading with type promotion


As displayed in the above diagram, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.

By Er. RAHAMATULLA (Assistant Professor) Page 30 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Example of Method Overloading with TypePromotion


class OverloadingCalculation1{void
sum(int a,long b)
{

[Link](a+b);
}

void sum(int a,int b,int c)


{

[Link](a+b+c);
}

public static void main(String args[]){ OverloadingCalculation1


obj=new OverloadingCalculation1(); [Link](20,20);//now second int
literal will be promoted to long
[Link](20,20,20);

}
}

Output: 40 60

Example of Method Overloading with Type Promotion if matching found If there are matching type arguments
in the method, type promotion is not performed.
class OverloadingCalculation2{
void sum(int a,int b)
{
[Link]("int arg method invoked");
}
void sum(long a,long b)
{
[Link]("long arg method invoked");
}
public static void main(String args[])

{ OverloadingCalculation2 obj=new OverloadingCalculation2();


[Link](20,20);//now int arg sum() method gets invoked
}
}
Output: int arg method invoked

By Er. RAHAMATULLA (Assistant Professor) Page 31 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Constructor in Java:
Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked
at the time of object creation. It constructs the values [Link] data for the object that is why it is
known as constructor.
Rules for creating java constructor

There are basically two rules defined for the constructor.


1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg
arg constructor in the Bike class. It will be invoked at the time of object creation.
class Bike1{
Bike1()
{[Link]("Bike is created");}

public static void main(String args[]){


Bike1 b=new Bike1();
}
}

Output:

Bike is created

By Er. RAHAMATULLA (Assistant Professor) Page 32 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Purpose of default constructor


Default constructor provides the default values to the object like 0, null etc. dependingon the type.

Example of default constructor that displays the defaultvalues


class Student3{
int id;
String name;
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
[Link]();
[Link]();
}
}

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides
you a default [Link] 0 and null values are provided by default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Use parameterized constructor


Parameterized constructor is used to provide different values to the distinct objects.

By Er. RAHAMATULLA (Assistant Professor) Page 33 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan 222 Aryan

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter [Link] compiler differentiates these
constructors by taking into account the number of parameters in the list and their
type.

By Er. RAHAMATULLA (Assistant Professor) Page 34 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Example of Constructor Overloading


class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}

Output:

111 Karan 0 222 Aryan 25

By Er. RAHAMATULLA (Assistant Professor) Page 35 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = [Link];
name =[Link];
}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
[Link]();
[Link]();
}
}
Output:

111 Karan 111 Karan

By Er. RAHAMATULLA (Assistant Professor) Page 36 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to another object. In this
case, there is no need to create the constructor.

class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
[Link]=[Link];
[Link]=[Link];
[Link]();
[Link]();
}
}

Output:

111 Karan
111 Karan

Access Modifiers in java


There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specify accessibility (scope) of a data member, method, constructoror class.
There are 4 types of java access modifiers:
 Private
 Default
 Protected
 Public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile,transient etc.
Here, we will learn access modifiers.
1) private access modifier
The private access modifier is accessible only within [Link]
example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is compile time error.

By Er. RAHAMATULLA (Assistant Professor) Page 37 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

class A{
private int data=40;

private void msg(){[Link]("Hello java");}

public class Simple{

public static void main(String args[]){A obj=new


A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}

1) Role of Private Constructor


If you make any class constructor private, you cannot create the instance of that class
fromoutside the class. For example:
class A{
private A(){}//private constructor
void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
2) default access modifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessibleonly within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
package pack;
class A{
void msg(){[Link]("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
By Er. RAHAMATULLA (Assistant Professor) Page 38 of 41
OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

A obj = new A();//Compile Time Error


[Link]();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it
cannot beaccessed from outside the package.
3) protected access modifier
The protected access modifier is accessible within package and outside the package but
throughinheritance only.
The protected access modifier can be applied on the data member, method and
constructor. Itcan't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output:Hello
4) public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all
othermodifiers.
Example of public access modifier
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
package mypack;
import pack.*;
class B{

By Er. RAHAMATULLA (Assistant Professor) Page 39 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

public static void main(String args[]){


A obj = new A();
[Link]();
}

Output:Hello

Access Modifier within class within package outside package by subclass only
outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

By Er. RAHAMATULLA (Assistant Professor) Page 40 of 41


OBJECT ORIENTED PROGRAMMING (IT301) KKCEM B. Tech 3rd Sem. CSE

Java access modifiers with method overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.

class A{

protected void msg(){[Link]("Hello java");}

public class Simple extends A{

void msg(){[Link]("Hello java");}//[Link]


public static void main(String args[]){
Simple obj=new Simple();
[Link]();
}

The default modifier is more restrictive than protected. That is why there is compile time error.

By Er. RAHAMATULLA (Assistant Professor) Page 41 of 41

You might also like