0% found this document useful (0 votes)
148 views134 pages

Java Object-Oriented Programming Basics

The document provides an overview of Object Oriented Programming (OOP) using Java, detailing its history, features, and comparisons with C++. It covers key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and the Java Virtual Machine (JVM). Additionally, it explains data types, variables, and Java comments, while emphasizing Java's platform independence and security features.

Uploaded by

nvk189686
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)
148 views134 pages

Java Object-Oriented Programming Basics

The document provides an overview of Object Oriented Programming (OOP) using Java, detailing its history, features, and comparisons with C++. It covers key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and the Java Virtual Machine (JVM). Additionally, it explains data types, variables, and Java comments, while emphasizing Java's platform independence and security features.

Uploaded by

nvk189686
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 Using Java MMC202

MODULE 1
Object Oriented Programming Using Java
The Java Language:
• Java was initiated by James Gosling and others at Sun Microsystems in 1991.
• Team: Mike Sheridan and Patrick Naughton
• This language was initially called “OAK”.
• Later it was renamed as “JAVA” in 1995.
• It is one of the world’s most widely used computer language.
• From practical point of view, it is an excellent language to learn.
• Java was perfect for the Web.

C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.

C++ supports goto statement. Java doesn't support goto statement.

C++ supports multiple inheritance. Java doesn't support multiple


inheritance through class. It can be
achieved by interfaces in java.

C++ supports operator overloading. Java doesn't support operator


overloading.
C++ supports pointers. You can java has restricted pointer support in
write pointer program in C++. java.

C++ supports both call by value and Java supports call by value only.
call by reference. There is no call by reference in java.

C++ doesn't support >>> operator. Java supports unsigned


right shift >>> operator

Features of Java
The Java Features are:
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 1
Object Oriented Programming Using Java MMC202
\

Simple
• Java is very easy to learn, and its syntax is simple,clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarelyused features, for example, explicit
pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
• 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.

Portable
• Java is portable because it facilitates you to carry the Java bytecode to any
platform.
• It doesn't require any implementation.

Platform Independent:
• Java is platform independent because it is different from other languages like C,
C++, etc. which are compiled into platform specific machines while Java is a write
once, run anywhere language.

Secured
• Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox

Robust
• Java provides automatic garbage collection which runs on the Java Virtual Machine
to get rid of objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 2
Object Oriented Programming Using Java MMC202
\

Compiled and Interpreted:


• Java code is compiled to bytecode.
• Bytecode are interpreted on any platform by JVM.

High Performance
• Bytecode is highly optimised.
• JVM execute Bytecode much faster

Multithreaded
• Multithreading means handling more than one job at a time.
• The main advantage of multi-threading is that it shares the same memory.

Distributed
• Java programs can be shared over the internet

The Key attributes of OOP’s


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:

The key attributes of OOP’s are:


1. Inheritance
2. Polymorphism
3. Encapsulation

• Inheritance:
o When one object acquires all the properties and behaviors of parent
object i.e. known as inheritance.
• Polymorphism:
o we can perform a single action in different ways.
o Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
o There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
o We can perform polymorphism in java by method overloading and
method overriding.
• Encapsulation:
o Binding (or wrapping) code and data together into a single unit is
known as encapsulation.

Advantages of Inheritance

Minimizing duplicate code: Key benefits of Inheritance include minimizing the


identical code as it allows sharing of the common code among other subclasses.

Flexibility: Inheritance makes the code flexible to change, as you will adjust only in
one place, and the rest of the code will work smoothly.

Overriding: With the help of Inheritance, you can override the methods of the base
class.

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 3
Object Oriented Programming Using Java MMC202
\

Data Hiding: The base class in Inheritance decides which data to be kept private,
such that the derived class will not be able to alter it.

Data Abstraction
Data abstraction is the process of hiding certain details and showing only essential
information to the user.

JVM
• JVM (Java Virtual Machine) is an abstract machine
• It is called a virtual machine because it doesn't physically exist.
• It is a specification that provides a runtime environment in which Java bytecode
can be executed.
• It can also run those programs which are written in other languages and compiled
to Java bytecode.
• JVMs are available for many hardware and software platforms.
• JVM, JRE, and JDK are platform dependent because the configuration of each OS
is different from each other. However, Java is platform independent.

JRE
• JRE is an acronym for Java Runtime Environment.
• It is also written as Java RTE. 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.
• It physically exists. It contains a set of libraries + other files that JVM uses at
runtime.

JDK
JDK (Java Development Kit) is a software development kit required to develop
applications in Java.
• you download JDK, JRE is also downloaded with it.
• In addition to JRE, JDK also contains a number of development tools (compilers,
JavaDoc, Java Debugger, etc).
How Java Code Runs?

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 4
Object Oriented Programming Using Java MMC202
\

Introducing Classes:
• A class is a group of objects which have common properties.
• It is a template or blueprint from which objects are created. It is a logical entity. It
can't be physical.
• A class in Java can contain:
- Fields
- Methods
- Constructors
- Blocks
- Nested class and interface
• An object is an instance of a class.

The general form of a class:


A class is created by using the keyword class.
The general form of a class is,
class classname{
type instance-variable1;
type instance-variable2;
…….
type instance-variableN;

type method1(parameters){
//body of the method
}
type method2(parameters){
//body of the method
}
//…..
type methodN(parameters){
//body of the method
}
}

Objects
• A Java object is a member (also called an instance) of a Java class.
• Each object has an identity, a behavior and a state. The state of an object is stored
in fields (variables), while methods (functions) display the object's behavior.

Creating an Object
There are three steps when creating an object from a class
• Declaration - A variable declaration with a variable name with an object type.
• Instantiation - The 'new' keyword is used to create the object.
• Initialization - The 'new' keyword is followed by a call to a constructor. This
call initializes the new object.
• To create a simple java program, you need to create a class that contains main
method.
Ex1:
class Simple {
public static void main(String args[]) {
[Link]("Hello Java");
}
}

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 5
Object Oriented Programming Using Java MMC202
\

• save this file as [Link]


• To compile:javac [Link]
• To execute: java Simple
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility, it means it is
visible to 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. 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.

Example:
class Vehicle {
int passengers; // number of passengers
int fuelCap; // fuel capacity in litres
int mpg; // fuel consumption in miles per litres
}
• A class definition creates a new data type. In this case, the new data type is called
Vehicle.
• You will use this name to declare objects of type Vehicle.
• To create a Vehicle object, you will use a statement such as the following:
• Vehicle minivan= new Vehicle();
• After this statement executes, minivan will be an instance of Vehicle.
• The dot operator(.) links the name of an object with the name of a member.
• The general form of the dot operator is
[Link]
Ex:
[Link]=16;
• In general the dot(.)operator is used to access both instance variables and
methods.

class Vehicle {
int passengers; int fuelCap; int mpg;
}
class VehicleDemo {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
int range;
[Link] = 7;
[Link] = 16;
[Link] = 21;
range = [Link] * [Link];
[Link]("Minivan can carry " + [Link] + " with
a range of " + range);
}
}

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 6
Object Oriented Programming Using Java MMC202
\

Java Comments
The java comments are statements that are not executed by the compiler and
interpreter.

Types of Java Comments


There are 3 types of comments in java.
• Single Line Comment
• Multi Line Comment
• Documentation Comment

Java Single Line Comment:
The single line comment is used to comment only one line.
Syntax:
//This is single line comment

Example:
class CommentExample1 {
public static void main(String[] args) {
int i=10; //Here, i is a variable
[Link](i);
}
}

Java Multi Line Comment:


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

Example:
class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
[Link](i);
}
}

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
*/

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 7
Object Oriented Programming Using Java MMC202
\

Data Types in Java


• Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
• Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
• Non-primitive data types: The non-primitivedata types include Classes,
Interfaces, and Arrays.

Java’s built in primitive data types

Type Meaning
boolean Represents true/false values

byte 8-bit integer


char Character
short Short Integer
int Integer
long Long Integer
float Single-precision floating point

double Double-precision floating point

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 8
Object Oriented Programming Using Java MMC202
\

JAVA KEYWORDS
• In the Java programming language, a keyword is any one of 55 reserved words
that have a predefined meaning in the language; because of this, programmers
cannot use keywords as names for variables, methods, classes, or as any other
identifier.

The Java Keywords

Although const and goto are reserved words, they are not currently part of the
Java language.

Mr. Mohammed Maaz Pasha, Assistant Professor, MCA Dept | GMIT, Mandya Page 9
Object Oriented Programming Using Java MMC202
\

Java Variables
• A variable is a container which holds the value while the java program is executed.
• A variable is assigned with a datatype.
• There are three types of variables in java: local, instance and static.

Local Variable:
• A variable declared inside the body of the method is called local variable.
• You can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.
• A local variable cannot be defined with "static" keyword.

Instance Variable
• A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.

Static variable
• A variable which is declared as static is called static variable. It cannot be local.
You can create a single copy of static variable and share among all the instances of
the class.

class A {
int data=50;//instance variable
static int m=100;//static variable
void method() {
int n=90;//local variable }
}//end of class

class Student8 {
int rollno; String name; static String college =“RNSIT";
Student8(int r,String n) {
rollno = r; name = n;
}
void display () {
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[]) {
Student8 s1 = new Student8(100,"Kiran");
Student8 s2 = new Student8(222,"Arya");
[Link]();
[Link]();
}
}
• Variables are declared using this form of statement.
type var-name;
• Here type is the date type of the variable and varname is its name.
• The type of the variable cannot be change during its lifetime.
Ex:
an int variable cannot turn into a char variable

• All the variables in java must be declared prior to their use.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 10


Object Oriented Programming Using Java MMC202
\

Initializing a variable:
• follow the variable’s name with an equal sign and the value being assigned.
- The general form of initialization is shown here
type var=value;
Ex:
int count=10;
char ch =‘a’;
float f=1.2;
• When declaring two or more variables of the same type using a comma-separated
list.
Ex: int a,b=10,c,d=15;

The scope and lifetime of variables


• Java allows variables to be declared within any block. A block is begin with an
opening brace and ended by a closed brace.
• A block defines a scope.
• Each time you start a new block, you are creating a new scope.
• A scope determines what objects are visible to other parts of your program.
• It also determines the lifetime of those objects.
class Demo {
public static void main ( String [ ] args )
{
int x =10; if (true)
{
int y = 20;
[Link] ( y ); // OK
}
[Link] ( y ); // ERROR, not in scope
[Link] ( x ); // OK
}
}

Operators
• Operators in Java are the symbols used for performing specific operations in
Java. Operators make tasks like addition, multiplication, etc which look easy
although the implementation of these tasks is quite complex.

Types of Operators in Java


• There are multiple types of operators in Java all are mentioned below:
• There are many types of operators in Java which are given below:
- Unary Operator,
- Arithmetic Operator,
- Shift Operator,
- Relational Operator,
- Bitwise Operator,
- Logical Operator,
- Ternary Operator and
- Assignment Operator.

1. Arithmetic Operators
• Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra.
• The operands of the arithmetic operators must be of a numeric type.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 11


Object Oriented Programming Using Java MMC202
\

• You cannot use them on boolean types, but you can use them on char
types, since the char type in Java is a subset of int.
• The following table lists the arithmetic operators:
Operator Result
+ Addition
- Substraction(Also unary minus)
* Multiplication
/ Division
% Modulus

The Basic Arithmetic Operators


• The basic arithmetic operations—addition, subtraction, multiplication, and
division— all behave as you would expect for all numeric types.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
[Link]("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
[Link]("a = " + a); // 2
[Link]("b = " + b); // 6
[Link]("c = " + c); // 1
[Link]("d = " + d); // -1
[Link]("e = " + e); // 1
}
}

The Modulus Operator:


• The modulus operator, %, returns the remainder of a division operation.
It can be applied to floating-point types as well as integer types.
• The following example program demonstrates the %:
EX:
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
[Link]("x mod 10 = " + x % 10); // 2
[Link]("y mod 10 = " + y % 10); // 2.25
}
}
Arithmetic Compound Assignment Operators:
• Java provides special operators that can be used to combine an arithmetic
operation with an assignment.
• EX:
o a = a + 4;
• In Java, you can rewrite this statement as shown here:
o a += 4;
• This version uses the += compound assignment operator. Both statements
perform the same action.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 12


Object Oriented Programming Using Java MMC202
\

• Here is another example,


o a = a % 2;
• which can be expressed as
o a %= 2;

2. Increment and Decrement or Unary Operator


• The ++ and the – – are Java’s increment and decrement operators.
• The increment operator increases its operand by one. The decrement operator
decreases its operand by one.
EX1:
x = x + 1;
• can be rewritten like this by use of the increment operator:
x++;
• Similarly, this statement:
x = x - 1;
is equivalent to
x--;

EX:2
x = 42;
y = ++x;
• In this case, y is set to 43 as you would expect, because the increment
occurs before x is assigned to y. Thus, the line y = ++x; is the equivalent
of these two statements:
x = x + 1; y = x;
• However, when written like this,
x = 42;
y = x++;
• the value of x is obtained before the increment operator is executed, so
the value of y is 42.
• Of course, in both cases x is set to 43. Here, the line y = x++; is the
equivalent of these two statements:
y = x;
x = x + 1;

3. The Bitwise Operators


• Java defines several bitwise operators that can be applied to the integer types,
long, int, short, char, and byte.
• These operators act upon the individual bits of their operands.
Opereator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR

• Since the bitwise operators manipulate the bits within an integer, it is


important to understand what effects such manipulations may have on a
value.
• All of the integer types are represented by binary numbers of varying bit
widths.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 13


Object Oriented Programming Using Java MMC202
\

• each position represents a power of two, starting with 2 power 0 at the


rightmost bit. The next bit position to the left would be 2 power 1 or 2 and so
on..
• The bitwise operators are &, |, ^, and ~. The following table shows the
outcome of each operation. • the bitwise operators are applied to each
individual bit within each operand.

The "Binary OR operator"


returns 1 if one of its
| Binary OR Operator operands evaluates as 1. if
either or both operands
evaluate to 1, the result is 1.
It stands for "exclusive OR"
and means "one or the
other", but not both. The
"Binary XOR operator"
^ Binary XOR Operator returns 1 if and only if
exactly one of its operands is
1. If both operands are 1, or
both are 0, then the result is
0.

The "Binary AND operator"


returns 1 if both operands
& Binary AND Operator are equal to 1.

The Bitwise NOT:


• Also called the bitwise complement, the unary NOT operator, ~, inverts all of
the bits of its operand.
• For example, the number 42, which has the following bit pattern:
• 00101010 becomes 11010101 after the NOT operator is applied.
The Bitwise AND:
• The AND operator, &, produces a 1 bit if both operands are also 1. A zero
is produced in all other cases. Here is an

Example:
00101010 42
& 00001111 15

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 14


Object Oriented Programming Using Java MMC202
\

----------------------------------
00001010 10

The Bitwise OR:


• The OR operator, |, combines bits such that if either of the bits in the operands
is a 1, then the resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
- - - - - -------------------------
00101111 47

The Bitwise XOR:


• The XOR operator, ^, combines bits such that if exactly one operand is 1,
then the result is 1.
• Otherwise, the result is zero.
EX:
00101010 42
^ 00001111 15
-----------------------------
00100101 37

4. Shift Operators

The Left Shift:


• The left shift operator, <<, shifts all of the bits in a value to the left a
specified number of times.
• It has this general form:
value << num
• Here, num specifies the number of positions to leftshift the value in value.
• That is, the << moves all of the bits in the specified value to the left by the
number of bit positions specified by num.
class OperatorExample {
public static void main(String args[]) {
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80
[Link](15<<4);//15*2^4=15*16=240
}
}
The Right Shift:
• The right shift operator, >>, shifts all of the bits in a value to the right a
specified number of times. Its general form is shown here:
value >> num
• Here, num specifies the number of positions to rightshift the value in value.
• That is, the >> moves all of the bits in the specified value to the right the
number of bit positions specified by num.
EX:
int a = 32;
a = a >> 2; // a now contains 8
• When a value has bits that are “shifted off,” those bits are lost. For example,
the next code fragment shifts the value 35 to the right two positions, which
causes the two loworder bits to be lost, resulting again in a being set to 8.
int a = 35;

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 15


Object Oriented Programming Using Java MMC202
\

a = a >> 2; // a still contains 8


• Looking at the same operation in binary shows more clearly how this happens:
00100011 35
>> 2
00001000 8
class OperatorExample {
public static void main(String args[]) {
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
}
}

The Unsigned Right Shift(>>>)


• you will generally want to shift a zero into the highorder bit no matter what
its initial value was.
• This is known as an unsigned shift. To accomplish this, you will use Java’s
unsigned, shift-right operator(>>>), which always shifts zeros into the high-
order bit.
• The >>> operator is often not as useful as you might like, since it is only
meaningful for 32- and 64-bit values.
EX:
int a = -1;
a = a >>> 24;
[Link](a);
• The above code fragment demonstrates the >>>.
• Here, a is set to –1, which sets all 32 bits to 1 in binary.
• This value is then shifted right 24 bits, filling the top 24 bits with zeros,
ignoring normal sign extension.
• This sets a to 255.
• int a = -1;
• a = a >>> 24;
• Here is the same operation in binary form to further illustrate what is
happening:
• 11111111 11111111 11111111 11111111 –1 in binary as an int >>> 24
• 00000000 00000000 00000000 11111111 255 in binary as an int

5. Relational Operators:
• The relational operators determine the relationship that one operand has to the
other.
• Specifically, they determine equality and ordering. The relational operators are
shown here:
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Lessthan
>= Greaterthan or equal to
<= Lessthan or equal to
6. Logical Operators:
• The Boolean logical operators shown here operate only on boolean
operands.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 16


Object Oriented Programming Using Java MMC202
\

Operator Result
& Logical AND
| Logical OR
! Logical NOT
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
• The logical Boolean operators, &, |, and ^, operate on boolean values in
the same way that they operate on the bits of an integer.
• The logical ! operator inverts the Boolean state:
o !true == false and !false == true.

boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a; int a=10; int b=5;
int c=20;
[Link](a<b&&a<c);
[Link](a<b&a<c);

Short-Circuit Logical Operators (&& and ||):


• The logical && operator doesn't check second condition if first condition is false.
• It checks second condition only if first one is true.
• The bitwise & operator always checks both conditions whether first condition is
true or false.
class OperatorExample {
public static void main(String args[]) {
int a=10,b=5,c=20;
[Link](a<b&&a<c);
[Link](a<b&a<c);
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 17


Object Oriented Programming Using Java MMC202
\

EX:
class OperatorExample {
public static void main(String args[])
{
int a=10; int b=5;
int c=20; [Link](a<b&&a++<c); [Link](a);
[Link](a<b&a++<c); [Link](a);
}
}
• The logical || operator doesn't check second condition if first condition is true.
• It checks second condition only if first one is false.
• The bitwise | operator always checks both conditions whether first condition is
true or false.
EX:
class OperatorExample {
public static void main(String args[]) {
int a=10, b=5, c=20;
[Link](a>b||a<c);
[Link](a>b|a<c);
[Link](a>b||a++<c);
[Link](a);
[Link](a>b|a++<c);
[Link](a);
}
}

7. The ? Operator or ternary operator:


• Java includes a special ternary (three-way) operator that can replace certain types
of if-then-else statements.
• The ? has this general form:
expression1 ? expression2 : expression3
• Here, expression1 can be any expression that valuates to a boolean value.
• If expression1 is true, then expression2 is evaluated; otherwise, expression3 is
evaluated.
EX:
public class Test {
public static void main(String args[]) {
int a, b; a = 10;
b = (a == 1) ? 20: 30;
[Link]( "Value of b is : " + b ); b = (a == 10) ? 20: 30;
[Link]( "Value of b is : " + b );
}
}

8. The Assignment Operator:


• The assignment operator is the single equal sign, =.
• The assignment operator works in Java much as it does in any other computer
language.
• It has this general form:
var = expression;
• Here, the type of var must be compatible with the type of expression.
EX:
int x, y, z;
x = y = z = 100;

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 18


Object Oriented Programming Using Java MMC202
\

• The value of z = 100 is 100, which is then assigned to y, which in turn is


assigned to x.

Expressions
•An expression is a syntactic construction that has a value.
•Expressions are formed by combining variables, constants, and method
returned values using operators.
The Type Promotion Rules:
• With in expression, it is possible to mix two or more different types of data
as long as they are compatible with each other.
• you can mix short and long within an expression because they are both
numeric types.
• When different types of data are mixed an expression, they are all
converted to the same type.
• All char, byte and short values are promoted to int.
• If one operand is a long, the whole expression is promoted to long.
• If one operand is a float operand, the entire is promoted to float.
• If one operand is double, the result is double
Ex:
class rnsit {
public static void main(String[] args)
{
byte b; int i; b=10;
char ch1=‘a’,ch2=‘b’; ch1=(char)(ch1 + ch2);
i=b * b; // no cast needed [Link](“ i and b:” +i+ “ “
+b);
[Link](ch1);
}
}
• No cast is needed when b*b=i, because b is promoted to int when the
expression is evaluated.
• The same sort of situation also occurs when performing operations on
char.
• Without the cast, the resulting of adding ch1 and ch2 would be int, which
can’t be assigned to a char.

Type conversion in assignments


• Booleans cannot be converted to other types.
• For the other primitive types (char, byte, short, int, long, float, and double), there
are two kinds of conversion:
1. Implicit or Widening or Automatic Type Conversion
2. Explicit or Narrowing or Type casting Implicit conversions: An implicit
conversion means that a value of one type is changed to a value of another type
without any special directive from the programmer.
• A data type of lower size (occupying less memory) is assigned to a data type
of higher size. This is done implicitly by the JVM.
• The lower size is widened to higher size. This is also named as automatic type
conversion.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 19


Object Oriented Programming Using Java MMC202
\

EX:
public class Test {
public static void main(String[] args) {
int i = 100; //occupies 4 bytes
long l = i; // occupies 8 bytes
double f = l; // occupies 8 bytes
[Link]("Int value "+i); [Link]("Long value "+l);
[Link]("Float value "+f);
}
}

OUTPUT
Int value 100
Long value 100 Float value 100.0

Explicit conversions:
• If we want to assign a value of larger data type to a smaller data type we perform
explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be
done.
• The general form of cast is (target-type)expression
• Here, target-type specifies the desired type to convert the specified value to.
• The thumb rule is, on both sides, the same data type should exist.
• EX:
class Test
{
public static void main(String[] args) {
double d = 100.04;
long l = (long)d; int i = (int)l;
[Link]("Double value "+d); //100.04
[Link]("Long value "+l); // 100
[Link]("Int value "+i); // 100
}
}

Control Statements
• There are three types of control statements:
o Selection statements
o Iteration statements
o Jump statements
• Selection statements allow your program to choose different paths of execution
based upon the outcome of an expression or the state of a variable.
• Iteration statements enable program execution to repeat one or more statements.
• Jump statements allow your program to execute in a nonlinear fashion.

Selection statements:
Java if Statement:
• The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition)
{
//code to be executed
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 20


Object Oriented Programming Using Java MMC202
\

EX:
public class IfExample {
public static void main(String[] args) {
int age=20; if(age>18)
{
[Link]("Age is greater than 18");
}
}
}

Java if-else Statement


• The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition)
{
//code if condition is true
}
else {
//code if condition is false
}
EX:
public class IfElseExample {
public static void main(String[] args) {
int number=13; if(number%2==0)
{
[Link](“MBA");
}
else{
[Link](“MCA");
}
}
}

Java if-else-if ladder Statement


• The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(test_expression)
{
//execute your code
}
else if(test_expression n) {
//execute your code }
else {
//execute your code
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 21


Object Oriented Programming Using Java MMC202
\

Ex:
public class Sample {
public static void main(String args[]) {
int a = 30, b = 30;
if (b > a){
[Link](“BANGALORE");
}
elseif(a>b){
[Link](“DELHI");
} else {
[Link](“HYDERABAD");
}
}
}

Nested if statement:
public class Test {
public static void main(String args[]) {
int x = 30; int y = 10;
if( x == 30 )
{
if( y == 10 )
{
[Link](“BANGALORE"); }
}
}
}

Switch Statement
• The switch statement is Java’s multiway branch statement.
• It provides an easy way to dispatch execution to different parts of your code based
on the value of an expression.
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only.
• The case value must be literal or constant.
Here is the general form of a switch statement:
switch (expression)
{
case value1:
// statement sequence break;
case value2:
// statement sequence break;
..
case valueN:
// statement sequence
break; default:
// default statement sequence
}

EX:
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<5; i++) switch(i)

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 22


Object Oriented Programming Using Java MMC202
\

{
case 0:
[Link](“JAVA"); break;
case 1:
[Link](“DBMS"); break;
case 2:
[Link](“WEB");
break; case 3:
[Link](“UID"); break;
default:
[Link](“SOFWARE");
}
}
}
EX2:
• The break statement is optional.
• If you omit the break, execution will continue on into the next case.
• It is sometimes desirable to have multiple cases without break statements between
them.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++) switch(i)
{
case 0:
case 1:
case 2:
case 3:
case 4: [Link](“MOBILE"); break;
case 5:
case 6:
case 7:
case 8:
case 9:
[Link](“APPLICATIONS"); break;
default:
[Link](“ENGINEERING"); }
}
}

EX3:
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month)
{
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 23


Object Oriented Programming Using Java MMC202
\

season = "Spring"; break;


case 6:
case 7:
case 8:
season = "Summer"; break;
case 9:
case 10:
case 11:
season = "Autumn"; break;
default:
season = "Bogus Month";
}
[Link]("April is in the " + season + ".");
}
}

Nested Switch Statements


public class NestedSwitchExample {
public static void main(String[] args) {
int i = 0; int j = 1;
switch(i) {
case 0: switch(j) {
case 0: [Link](“KIRAN");
break;
case 1: [Link](“SHIVA");
break;
default: [Link](“BANGALORE");
}
break;
default:
[Link](“MCA");
}
}
}

Iteration statements:
• Java’s iteration statements are for, while, and do-while.
• These statements create what we commonly call loops.

while
• The while loop is Java’s most fundamental loop statement.
• It repeats a statement or block while its controlling expression is true.
• Here is its general form:
while(condition)
{
// body of loop
}
• The condition can be any Boolean expression.
• The body of the loop will be executed as long as the conditional expression is true.
• When condition becomes false, control passes to the
• next line of code immediately following the loop.
• The curly braces are unnecessary if only a single statement is being repeated.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 24


Object Oriented Programming Using Java MMC202
\

EX:
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0)
{
[Link]("tick " + n); n--;
}
}
}
• The body of the while (or any other of Java’s loops) can be empty.
• This is because a null statement (one that consists only of a semicolon) is
syntactically valid in Java.

EX2 :
class NoBody {
public static void main(String args[]) {
int i, j; i = 100; j = 200;
while(++i < --j) ; // no body in this loop
[Link]("Midpoint is " + i);
}
}
OUTPUT
It generates the following output:
Midpoint is 150

do-while:
• The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop.
• Its general form is
do
{
// body of loop
} while (condition);
• Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression.
• If this expression is true, the loop will repeat. Otherwise, the loop terminates
EX:
class DoWhileExample {
public static void main(String[] args) {
int i=11;
do
{
[Link](i);
i++;
}while(i<=10);
}
}

The for loop:


• The for loop will continue to execute as long as the condition tests true.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 25


Object Oriented Programming Using Java MMC202
\

• Once the condition becomes false, the loop will exit and program execution will
resume on the statement following of for.
• A for loop is most commonly used when you know that a loop will execute a
predetermined number of times.
• The general form of the for loop for repeating a single statement is

for(initialization; condition; increment/decrement )


statement
Ex:
class example {
public static void main(String[] args) {
for(int i=1; i<5; i++) {
[Link]("Count is: " + i);
}
}
}

Using the Comma:


Ex:
class mca{
public static void main(String[] args) {
int i,j; for(i=0,j=10;i<j ; i++,j--)
{
[Link](“i and j: “ + i + “ “ + j);
}
}
}

• Missing pieces:
• Some interesting for loop variations are created by leaving pieces of the loop
definition empty .
• In java, it is possible for any or all of the initialization, condition or iteration portions
of the for loop to be blank.

EX:
int i; for(i=0,i<10;)
{
[Link](“value of i:“ + i ); i++;
}

Java Infinitive For Loop:


• If you use two semicolons( ;;) in the for loop, it will be infinitive for loop.
EX:
class ForExample {
public static void main(String[] args) {
for(;;)
{
[Link]("infinitive loop");
}
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 26


Object Oriented Programming Using Java MMC202
\

The for-each style for loop


• A for-each loop cycles through a collection of objects, such as an array, in strictly
sequential fashion from start to finish.
• The general form of the for-each style is
for(type itr-var:collection)
statement-block
• Here, type specifies the type.
• itr-val specifies the name of an iteration variable that will receive the elements from
a collection, one at a time, from beginning to end.
• The collection being cycled through is specified by collection.
Ex:1
class ForEach {
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0;
for(int x : nums) {
[Link]("Value is: " + x); sum += x;
}
[Link]("Summation: " + sum);
}
}

Ex2:
class Big {
public static void main (String [] arg) {
int [] myArr = { 45, 5, 34, 8 } ;
int big = myArr[0];
for( int num : myArr)
if ( big<num )
big = num;
[Link](“Bigest = ” + big) ;
}
}

EX:
class ForEachExample {
public static void main(String[] args)
{
int arr[]={12,23,44,56,78};
for(int i:arr)
{
[Link](i);
}
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 27


Object Oriented Programming Using Java MMC202
\

Nested for Loops: EX:


class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<5; i++) {
for(j=i; j<5; j++) {
[Link](".");
}
[Link]();
}
}
}

Jump Statements:
• Java supports three jump statements: break, continue, and return.
• These statements transfer control to another part of your program. Break:
• In Java, the break statement has three uses.
• First, as you have seen, it terminates a statement sequence in a switch statement.
• Second, it can be used to exit a loop.
• Third, it can be used as a “civilized” form of goto.

Using break to Exit a Loop:


• When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
Ex:
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10)
break;
[Link]("i: " + i);
}
[Link]("Loop complete.");
}
}
EX:
class BreakLoop3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
[Link]("Pass " + i + ": ");
for(int j=0; j<100; j++)
{
if(j == 10) break; [Link](j + " ");
}
[Link]();
}
[Link]("Loops complete.");
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 28


Object Oriented Programming Using Java MMC202
\

Use break as a form of goto


• Java does not have a goto statement.
• Java defines an expanded form of the break statement.
• By using this form of break, you can break out of one or more blocks of code.
• These blocks need not be part of a loop or a switch. They can be any block.
• You can specify precisely where execution will resume, because this form of break
works with a label.
• The general form of the labeled break statement is:
• break label;
• Here label is the name of a label that identifies a
statement or a block of code.
• When this form of break executes, control is
transferred out of the labeled statement or block.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
[Link]("Before the break.");
if(t)
break second;
[Link]("This won't execute");
}
[Link]("This won't execute");
}
[Link]("This is after second block.");
}
}
}

--------------------------------------------------
class BreakLoop4 {
public static void main(String args[]) {
outer:
for(int i=0; i<3; i++) {
[Link]("Pass " + i + ": "); for(int j=0; j<100; j++)
{
if(j == 4) break outer; [Link](j + " ");
}
[Link]("This will not print");
}
[Link]("Loops complete.");
}
}

------------------------------------------------
• Keep in mind that you cannot break to any label which is not defined for an
enclosing block.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 29


Object Oriented Programming Using Java MMC202
\

class BreakErr {
public static void main(String args[]) {
one: for(int i=0; i<3; i++) {
[Link]("Pass " + i + ": "); }
for(int j=0; j<100; j++) {
if(j == 10)
break one; // WRONG
[Link](j + " ");
}
}
}

Using continue
• The continue statement is used in loop control structure when you need to jump
to the next iteration of the loop immediately.
• It can be used with for loop or while loop.
• The Java continue statement is used to continue the loop.
• It continues the current flow of the program and skips the remaining code at the
specified condition.

EX1:
class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++) {
if(i==5) {
continue;
}
[Link](i);
}
}
}

EX2:
class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 )
{
continue;
}
[Link]( x );
[Link]("\n");
}
}
}
• As with the break statement, continue may specify a label to describe which
enclosing loop to continue.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 30


Object Oriented Programming Using Java MMC202
\

EX3:
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<6; i++) {
for(int j=0; j<6; j++) {
if(j > i) {
[Link](); continue outer;
}
[Link](" " + (i * j));
}
}
[Link]();
}
}
• The continue statement in this example terminates the loop counting j and
continues with the next iteration of the loop counting i.

Return:
• The last control statement is return.
• The return statement is used to explicitly return from a method.
• That is, it causes program control to transfer back to the caller of the
method.
• At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method.
• Thus, the return statement immediately terminates the method in
which it is executed.
EX:
public class SampleReturn1 {
public int CompareNum() {
int x = 3; int y = 8;
[Link]("x = " + x + "\ny = " + y);
if(x>y)
return x;
else
return y;
}
public static void main(String ar[]) {
SampleReturn1 ob = new SampleReturn1();
int result = [Link]();
[Link]("The greater number am ong x and y is: " + result);
}
}

Java Identifiers:
• All Java components require names. Names used for classes, variables and
methods are called identifiers.
• In Java, there are several points to remember about identifiers. They are as follows:
• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
• After the first character identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, 1_value

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 31


Object Oriented Programming Using Java MMC202
\

• Examples of illegal identifiers: 123abc, -salary

Ex:
public class Test {
public static void main(String[] args) {
int a = 20;
}
}
• In the above java code, we have 5 identifiers namely :
Test : class name.
main : method name.
String : predefined class name.
args : variable name.
a : variable name.

Literals
• In java, literals refer to fixed values that are represented in their human-readable
form.
• Literals are also commonly called constants.
• Java literals can be any of the primitive data types.
• The way each literal is represented depends on its type.
• Character constants are enclosed in single quotes.

Ex:
• char g=‘a’
• char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
• In java, single and double quotes have special meaning is there. So you cannot
use them directly.
• You have to refer backslash(\) character constants.
Ex:
char ch=‘\’’;
• Java supports other type of literal: the string
• The string literal is a set of characters enclosed by double quotes.
Ex:
String s=“mca rnsit”;
String a= "he said \"Hello\" to me."

Input Characters from the Keyboard:


• To read a character from the keyboard we will use [Link]().
• System. in is the complement to System. out
• It is the input object attached to the keyboard.
• The read() method waits until the user presses a key and then returns the result.
• The character is returned as an integer, so it must be

cast into a char to assign it to a char variable.


Ex
import [Link].*; class ex13
{
public static void main(String[] args) {
char c;
[Link]("enter a key");
c=(char)[Link]();
[Link]("your key is="+c);

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 32


Object Oriented Programming Using Java MMC202
\

}
}

Reference variables and assignment


• We can assign value of reference variable to another reference variable.
• This means that you are changing the object that the reference variable refers to,
not making a copy of the object.
Ex:
• Rectangle r1 = new Rectangle();
• Rectangle r2 = r1;
• r1 is reference variable which contain the address of Rectangle Object.
• r2 is another reference variable
• r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it
does not create duplicate object , nor does it allocate extra memory.

class Rectangle {
double length;
double breadth;
}

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
Rectangle r3 = r2;
[Link] = 20;
[Link] = 25;
[Link]("Value of R1's Length : " + [Link]);
[Link]("Value of R2's Length : " + [Link]);
[Link]("Value of R2's Length : " + [Link]);
}
}

Methods
• A method contains the statements that define its actions.
• In well-written java code, each method performs only one task.
• You can give a method whatever name you please as long as it is a valid identifier.
• Remember that main() is reserved for the method that begins execution of your
program.
• A method will have parentheses after its name.
• For example, if a method’s name is getval,it will written getval() when its name is
used in a sentence
• The general form of a method is,
return-type name(parameter-list) {
//body of method }
• Here, ret-type specifies the type of data returned by the method.
• This can be any valid type, including class types that you can create.
• If the method does not return a value, its return type must be void.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 33


Object Oriented Programming Using Java MMC202
\

Adding a Method to the class


class Vehicle {
int passengers;
int fuelCap;
int mpg;
void range() {
[Link]("Range is " + fuelCap * mpg); }
}
class AddMeth {
public static void main(String[] args) { Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
[Link] = 7;
[Link] = 16;
[Link] = 21;
[Link] = 2;
[Link] = 14;
[Link] = 12;
[Link]("Minivan can carry " + [Link] + ". ");
[Link]();
[Link]("Sportscar can carry " + [Link] + ". ");
[Link]();
}
}

Returning a value
• Returns values are used for a variety of purposes in programming.
• In some cases, such as sqrt(), the return value contains the outcome of some
calculation.
• In other cases, the return value simply indicate success or failure.
• In still others, it may contain a status code.
• Methods return a value to the calling routine using this form of return:

return value:
class Vehicle {
int passengers;
int fuelCap; int mpg;
int range() {
return mpg * fuelCap;
}
}
class RetMeth {
public static void main(String[] args) {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
[Link] = 7;
[Link] = 16;
[Link] = 21;
[Link] = 2;
[Link] = 14;
[Link] = 12;

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 34


Object Oriented Programming Using Java MMC202
\

range1 = [Link]();
range2 = [Link]();
[Link]("Minivan can carry " + [Link] + " with
range of " + range1 + " miles");
[Link]("Sportscar can carry " + [Link] + "
with range of " + range2 + " miles");
}
}

Constructors
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides and is syntactically similar
to a method.
• Once defined, the constructor is automatically called immediately after the object
is created, before the new operator completes.
• Constructors look a little strange because they have no return type, not even void.
• This is because the implicit return type of a class constructor is the class type itself.
• It constructs the values i.e. provides data for the object that is why it is known as
constructor.
• Typically ,you will use a constructor to give initial values to the instance variables
defined by the class.
Types of java constructors
• There are two types of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor
Java Default Constructor
• A constructor that have no parameter is known as

Default constructor
class Bike1 {
Bike1() {
[Link]("Bike is created");
}
public static void main(String args[]) {
Bike1 b=new Bike1();
}
}
Default constructor provides the default values to the object like 0, null etc.
depending on the type.
Ex:
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]();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 35


Object Oriented Programming Using Java MMC202
\

• Java parameterized constructor


• A constructor that have parameters is known as parameterized constructor.
• Parameterized constructor is used to provide different values to the distinct objects.

Ex1:
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,"Kiran");
Student4 s2 = new Student4(222,"Arya");
[Link]();
[Link]();
}
}

EX2:
class Box {
double width; double height; double depth;
Box(double w, double h, double d) {
width = w; height = h;
depth = d;
}
double volume() {
return width * height * depth; }
}
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = [Link]();
[Link]("Volume is " + vol);
vol = [Link]();
[Link]("Volume is " + vol);
}
}

this keyword in java


• There can be a lot of usage of java this keyword.
• In java, this is a reference variable that refers to the current object.
• this keyword can be used to refer current class instance variable.
• this keyword can be used to invoke current class method (implicitly)
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this keyword can also be used to return the current class instance.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 36


Object Oriented Programming Using Java MMC202
\

Ex:1
class Student10{
int id; String name;
Student10(int id,String name){
id = id;
name = name;
}
void display(){
[Link](id+" "+name);
}
public static void main(String args[]){
Student10 s1 = new Student10(111,“kiran");
Student10 s2 = new Student10(321,"Ajay");
[Link]();
[Link]();
}
}
• In the above example, parameters(formal arguments) and instance variables are
same that is why we are using this keyword to distinguish between local variable
and instance variable.

Ex 1:
class Student11
{
int id; String name;
Student11(int id,String name) {
[Link] = id; [Link] = name;
}
void display() {
[Link](id+" "+name);
}
public static void main(String args[]) {
Student11 s1 = new Student11(111,"Kiran");
Student11 s2 = new Student11(222,"Ajay");
[Link]();
[Link]();
}
}

Ex2:
class A {
void m() {
[Link]("hello m");
}
void n() {
[Link]("hello n"); this.m();
}
}
class TestThis4 {
public static void main(String args[]){
A a=new A();
a.n();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 37


Object Oriented Programming Using Java MMC202
\

Arrays:
• array is a collection of similar type of elements that have contiguous memory
location.
• Java array is an object that contains elements of similar data type.
• It is a data structure where we store similar elements. We can store only fixed set
of elements in a java array.
• Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array


• Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
• Random access: We can get any data located at any index position.

Disadvantage of Java Array


• Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime.

There are two types of array.


Single or One Dimensional Array Multidimensional Array

A One Dimensional Array is a list of related variables. Such lists are common in
programming .
• To declare a one-dimensional array, you will use this general form:
type[] array-name=new type[size];
• Here, type declares the element type of the array.(The element type is also
sometimes referred to as the base type).
• The element type determines the data type of each element contained in the array.
• The number of elements that the array will hold is determined by size.
• Since arrays are implemented as objects,
• The creation of array is two-step process.
• First, you declare an array reference variable.
• Second, you allocate memory for the array, assigning the reference to that memory
to the array variable.
• Thus, arrays are dynamically allocated using the new operator.
Ex:
int[] sample=new int[10];
• This declaration works like an object declaration.
• The sample variable hold a reference to the memory allocated by new.
• This memory is large enough to hold 10 elements of type int.
• It is possible to break the preceding declaration in two.
int[] sample;
sample=new int[10];
Ex:
class ArrayDemo {
public static void main(String[] args) {
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1) {
sample[i] = i;
[Link]("This is sample[" + i + "]: " + sample[i]);
}
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 38


Object Oriented Programming Using Java MMC202
\

• Ex2:
class MinMax {
public static void main(String[] args) {
int[] nums = new int[5];
int min, max;
nums[0] = 99;nums[1] = 200;nums[2] = 100; nums[3] = 18;nums[4] = -978;
min = nums[0]; max = nums[0];
for(int i=1; i < 5; i++) { if(nums[i] < min) min = nums[i]; if(nums[i] > max) max =
nums[i];
}
[Link]("min and max: " + min + " " + max); }
}
Contd….
• Arrays can be initialized when they are created.
• The general form for initializing a one-dimensional
array is,
type[] array-name={val1,val2,val3…..valN}
• Here, the initial value are specified by val1 through
valN.
• They are assigned in sequence, left to right, in index
order.
• Java automatically allocates an array large enough to
hold the initializers that you specify.
• There is no need to explicitly use the new operator.
• Ex:
class MinMax2 {
public static void main(String[] args) {
int[] nums = { 99,5623, 463, 287, 49 };
int min, max; min = nums[0]; max = nums[0];
for(int i=1; i < 5; i++) {
if(nums[i] < min) min = nums[i]; if(nums[i] > max) max = nums[i];
}
[Link]("Min and max: " + min + " " + max); }
}
Multidimensional arrays
• In java, multidimensional array or two dimensional
array is a array of arrays.
• A two-dimensional array can be thought of as
creating a table of data, with the data organized by
row and column.
• An individual item of data is accessed by specifying
its row and column position.
• To declare a two-dimensional array, you must specify
the size of both dimensions.
• int [][] table=new int[10][20];
Here table is declared to be a two-dimensional array of int with the size 10 and
20.
Ex:
class TwoD {
public static void main(String[] args) { int t, i;
int[][] table = new int[3][4]; for(t=0; t < 3; t++) {
for(i=0; i < 4; i++) {
table[t][i] = (t*4)+i+1; [Link](table[t][i] + " ");
} [Link]();

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 39


Object Oriented Programming Using Java MMC202
\

Initializing multidimensional Arrays


• A multidimensional array can be initialized by enclosing each dimension’s initializer
list within its own set of braces.
• The general form is
type[][] array-name= { {val,val,val…..val},
{val,val,val…..val},
…. …..
{val,val,val…..val}
};
• Here, val indicates an initialization value.
• Each inner block designates a row.
• Within each row, the first value will be stored in the first position of the subarray,
the second value in the second array, and so on…
• Notice that commas separate the initializer blocks and that a semicolon follows the
closing }.

class Testarray3 {
public static void main(String args[]) {
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++) {
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
----------------------------
class Test5 {
public static void main(String args[]) {
int[][] a={{1,3,4},{3,4,5}};
int[][] b={{1,3,4},{3,4,5}}
int c[][]=new int[2][3];
for(int i=0;i<2;i++) {
for(int j=0;j<3;j++) {
c[i][j]=a[i][j]+b[i][j]; [Link](c[i][j]+" ");
}
[Link]();//new line
}
}
}

Using the length MEMBER


• Arrays are implemented as objects, each array has associated with it a length
instance variable that contains the number of elements that the array can hold.
• In other words, length contains the size of the array.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 40


Object Oriented Programming Using Java MMC202
\

Ex:
class LengthDemo {
public static void main(String[] args) {
int[] list = new int[10];
int[] nums = { 1, 2, 3 };
int[][] table = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
[Link]("length of list is " + [Link]);
[Link]("length of nums is " + [Link]);
[Link]("length of table is " + [Link]);
[Link]("length of table[0] is " + table[0].length);
[Link]("length of table[1] is " + table[1].length);
[Link]("length of table[2] is " + table[2].length);
[Link]();
}
}

Irregular arrays or Jagged arrays


• When you allocate memory for a multidimensional array, you need to specify only
the memory for the first (leftmost) dimension.
• You can allocate the remaining dimensions separately.
• Each row can have different number of columns.
Ex:
int table[][] = new int[3][];
table[0] = new int[1];
table[1] = new int[2];
table[2] = new int[3];
Ex:
class CheckEquality {
public static void main (String [] arg) {
int [][] jagged = { { 10, 8 }, { 40, 88, 20, 18 }, { 90, 28, 50 } };
int big = jagged[0][0];
for ( int row = 0 ; row < [Link] ; row++)
for ( int col = 0 ; col < jagged[row].length ; col++)
if ( big< jagged[row][col] ) big = jagged[row][col];
[Link](“Biggest = ” + big) ;
}
}

Alternative array declaration systax


• There is a second form that can be used to declare an array.
type var-name[];
• Here the square brackets follows the name of the array variable, not the type
specifier.
Ex: int rnsit[]=new int[5];
int[] rnsit=new int[5];
• This alternative declaration lets you declare both array and nonarray variables of
the same type in a single declaration.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 41


Object Oriented Programming Using Java MMC202
\

Ex: int alpha,beta[],gamma;

Assigning array references


• As with other objects, when you assign one array reference variable to another, you
are simply changing what objects that variables refers to.
Ex:
class AssignARef {
public static void main(String[] args) {
int i;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for(i=0; i < 10; i++)
nums1[i] = i; for(i=0; i < 10; i++)
nums2[i] = -i;
[Link]("Here is nums1: ");
for(i=0; i < 10; i++)
[Link](nums1[i] + " ");
[Link]();
[Link]("Here is nums2: ");
for(i=0; i < 10; i++)
[Link](nums2[i] + " ");
[Link]();
nums2 = nums1;
[Link]("Here is nums2 after assignment: ");
for(i=0; i < 10; i++)
[Link](nums2[i] + " ");
[Link]();
}
}

Overloading Methods
• If a class have multiple methods by same name but different parameters, it is
known as Method Overloading.
• There are two ways to overload the method in java By changing number of
arguments By changing the data type

EX:1
class OverloadDemo {
void test()
{
[Link]("No parameters");
}
void test(int a)
{
[Link]("a: " + a);
}
void test(int a, int b)
{
[Link]("a and b: " + a + " " + b);
}
void test(double a)
{
[Link]("double a: " + a*a);

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 42


Object Oriented Programming Using Java MMC202
\

}
}

class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
[Link]();
[Link](10);
[Link](10, 20);
[Link](123.25);
}
}
• In some cases, Java’s automatic type conversions can play a role in overload
resolution.

EX:2
class OverloadDemo {
void test()
{
[Link]("No parameters");
}
void test(int a, int b)
{
[Link]("a and b: " + a + " " + b);
}
void test(double a)
{
[Link]("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
[Link]();
[Link](10, 20);
[Link](i);
[Link](123.2);
}
}

EX:3
class mca10 {
int arun(int a)
{
return a;
}
double arun(double a, double b)
{
return a*b;
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 43


Object Oriented Programming Using Java MMC202
\

class mca85 {
public static void main(String args[]) {
mca10 s=new mca10();
[Link]([Link](10));
[Link]([Link](20.6, 12.5));
}
}

Overloading Constructors
• In addition to overloading normal methods, you can also overload constructor
methods.

EX:
class Box {
double width; double height; double depth;
Box(double w, double h, double d)
{
width = w; height = h;
depth = d; }
Box()
{
width = -1; height = -1; depth = -1;
}
Box(double len)
{
width = height = depth = len; }
double volume()
{
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}

Recursion
• Java supports recursion. Recursion is the process of defining something in terms of
itself.
• As it relates to Java programming, recursion is the attribute that allows a method
to call itself.
• A method that calls itself is said to be recursive.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 44


Object Oriented Programming Using Java MMC202
\

Ex 1:
class Factorial {
int fact(int n) {
I nt result; if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
[Link]("Factorial of 3 is " + [Link](3));
[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}

Ex 2:
class StarDrawer {
void drawStars(int n) {
if(n == 1)
[Link]("*");
else {
[Link]("*");
drawStars(n-1);
}
}
}
class StarDrawingDemo {
public static void main(String[] args) {
StarDrawer d = new StarDrawer();
[Link](1);
[Link]();
[Link](2);
[Link]();
[Link](3);
[Link]();
[Link](10);
[Link]();
}
}

Understanding static
• Normally, a class member must be accessed only in conjunction with an object of
its class.
• However, it is possible to create a member that can be used by itself, without
reference to a specific instance.
• To create such a member, precede its declaration with the keyword static.
• We can apply java static keyword with variables, methods, blocks.
• The static can be: variable (also known as class variable) method (also known as
class method) block
• Methods declared as static have several restrictions:

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 45


Object Oriented Programming Using Java MMC202
\

• They can only call other static methods.


• They must only access static data.
• They cannot refer to this or super in any way.

Ex 1:
Static variables
class Student8 {
int rollno; String name; static String college =“RNSIT";
Student8(int r,String n) {
rollno = r; name = n;
}
void display () {
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[]) {
Student8 s1 = new Student8(100,"Kiran");
Student8 s2 = new Student8(222,"Arya"); //[Link]="BBDIT";
[Link](); [Link]();
}
}

Static Methods
• If you apply static keyword with any method,it is known as static method.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.

Ex:2 //[Link]
class Student9 {
int rollno; String name;
static String college = “BMSIT";
static void change()
{
college = “RNSIT";
}
Student9(int r, String n) {
rollno = r; name = n;
}
void display () {
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[])
{
[Link]();
Student9 s1 = new Student9 (111,"Kiran");
Student9 s2 = new Student9 (222,“Ravi");
Student9 s3 = new Student9 (333,“Ajay");
[Link]();
[Link]();
[Link]();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 46


Object Oriented Programming Using Java MMC202
\

Java static block


• Is used to initialize the static data member.
• It is executed before main method at the time of classloading.
Ex 1:
class A2
{
static{
[Link]("static block is invoked");
}
public static void main(String args[]) {
[Link]("Hello main");
}
}

Ex 2:
class UseStatic {
static int a = 3; static int b;
static void meth(int x)
{
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + b);
}
static
{
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}

Garbage Collection
• In java, garbage means unreferenced objects.
• Garbage Collection is process of reclaiming the runtime unused memory
automatically.
• In other words, it is a way to destroy the unused objects.
• To do so, we were using free() function in C language and delete() in C++.
• But, in java it is performed automatically.
• So, java provides better memory management.
• when no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by the object can be reclaimed.

How can an object be unreferenced?


• There are many ways:
• By nulling the reference
Employee e=new Employee();
e=null;
• By assigning a reference to another
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2; //now the first object referred by e1 is available e for garbage collection

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 47


Object Oriented Programming Using Java MMC202
\

• By anonymous object. new Employee();

finalize() method
• The finalize() method is invoked each time before the object is garbage collected.
• This method is called finalize(),and it can be used in very specialized case to ensure
that an object terminates cleanly.
• To add a finalizer to class, you must define the finalize() method.
• The general form:
protected void finalize()
{
//code
}
• It is important to understand that finalize( ) is only called just prior to garbage
collection.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 48


Object Oriented Programming Using Java MMC202
\

MODULE-2
MULTIPLE INHERITANCE

Inheritance
• Java, Inheritance is an important pillar of OOP(Object-Oriented
Programming).
• It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class.
• In Java, Inheritance means creating new classes based on existing ones.
• A class that inherits from another class can reuse the methods and fields of
that class.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.

Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is common to all
subclasses.
• Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.

Terms used in Inheritance


• Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that
derives from an existing class
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 1


Object Oriented Programming Using Java MMC202
\

public static void main(String args[]){


Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}

Types of inheritance in java


• On the basis of class, there can be three types of inheritance in java:
o Single,
o Multilevel
o Hierarchical.
• In java programming, multiple and hybrid inheritance is supported through
interface only.

• When one class inherits multiple classes, it is known as multiple


inheritance.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 2


Object Oriented Programming Using Java MMC202
\

• Java does not support Multiple Inheritance by extending a class.


• Multiple inheritance can be achieved using implementing a interface.

extends

Single Inheritance
• When a class inherits another class, it is known as a single inheritance.
Example:
class Animal
{
void run()
{
[Link]("MCA");
}
}
class Dog extends Animal
{
void display()
{
[Link]("MBA");
}
}
class Single
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 3


Object Oriented Programming Using Java MMC202
\

Multilevel Inheritance
• When there is a chain of inheritance, it is known as multilevel inheritance.
Example
class Animal
{
void run()
{
[Link]("MCA");
}
}
class Dog extends Animal
{
void display()
{
[Link]("MBA");
}
}
class Cat extends Dog
{
void ball()
{
[Link]("BCA");
}
}
class multilevel
{
public static void main(String args[])
{
Cat d=new Cat();
[Link]();
[Link]();
[Link]();
}
}

Hierarchical Inheritance
• When two or more classes inherits a single class, it is known as
hierarchical inheritance.
Example
class Animal
{
void run()
{
[Link]("MCA");
}
}
class Dog extends Animal
{
void display()
{
[Link]("MBA");
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 4


Object Oriented Programming Using Java MMC202
\

class Cat extends Animal


{
void ball()
{
[Link]("BCA");
}
}
class hierarchical
{
public static void main(String args[])
{
Cat d=new Cat();
[Link]();
[Link]();

}
}

Access Modifiers in Java


• There are four types of Java access modifiers:
• Private: The access level of a private modifier is only within the class.
• It cannot be accessed from outside the class.
• Default: The access level of a default modifier is only within the package.
• It cannot be accessed from outside the package.
• If you do not specify any access level, it will be the default.
• Protected: The access level of a protected modifier is within the package and
outside the package through child class.
• If you do not make the child class, it cannot be accessed from outside the
package.
• Public: The access level of a public modifier is everywhere.
• It can be accessed from within the class, outside the class, within the
package and outside the package.

Example for private
class Employee
{
private float salary=400;
}
class privatee extends Employee
{
int bonus=100;
public static void main(String args[])
{
privatee p=new privatee();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
} //compile time error

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 5


Object Oriented Programming Using Java MMC202
\

Class member access

having default access modifier are accessible only within the same package.

Using super to call super class constructors


• The super keyword in java is a reference variable that is used to refer
immediate parent class object.
• Whenever you create the instance of subclass, an instance of parent class is
created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
• super is used to refer immediate parent class instance variable.
• super() is used to invoke immediate parent class constructor.
• super is used to invoke immediate parent class method.
Ex:1
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
[Link](color); //black
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 6


Object Oriented Programming Using Java MMC202
\

Ex:1 Using super (super using access instatnce variable)


class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
[Link]([Link]); //white
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}

EX:2 for constructor


class Animal
{
Animal()
{
[Link]("BANGALORE");
}
}
class Dog extends Animal
{
Dog()
{
super(); //invoke parent class constructor
[Link]("HYDERABAD");
}
}
class Bike5
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

Example3 for super method


class Animal
{
void eat()
{
[Link]("delhi");
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 7


Object Oriented Programming Using Java MMC202
\

class Dog extends Animal


{
void eat()
{
[Link]("hyderabad");
}
void bark()
{
[Link]("bangalore");
}
void work()
{
[Link]();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}

Final Keyword In Java


• The final keyword in java is used to restrict the user. The java final keyword
can be used in many context. Final can be:
- variable
- method
- class
- final variable
• If you make any variable as final, you cannot change the value of final
variable(It will be constant).

final method
• If you make any method as final, you cannot override it.

final class
• If you make any class as final, you cannot extend it.

Example for final variable


class Bike9
{
final int speedlimit=90;
void run()
{
speedlimit=400;
[Link](speedlimit);
}
public static void main(String args[])
{
Bike9 obj=new Bike9();

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 8


Object Oriented Programming Using Java MMC202
\

[Link]();
}
}
//compile time error

Example for final method


class Bike
{
final void run()
{
[Link]("running");
}
}
class Honda10 extends Bike
{
void run()
{
[Link]("running safely with 100kmph");
}
}
class Honda10
{
public static void main(String args[])
{
mca a= new mca();
[Link]();
}
}
//compile time error

Example for final class


final class Bike
{
int a=10;
}
class Honda1 extends Bike
{
int b;
}
class finalc
{
public static void main(String args[])
{
Honda1 a= new Honda1();
a.b=25;
}
}

//compile time error

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 9


Object Oriented Programming Using Java MMC202
\

Object class in Java


• The Object class is the parent class of all the classes in java by default. In
other words, it is the topmost class of java.
• Object class is present in [Link] package.
• Every class in Java is directly or indirectly derived from the Object class.
• If a class does not extend any other class then it is a direct child class
of Object and if extends another class then it is indirectly derived.
• Therefore the Object class methods are available to all Java classes.
class Vehicle
{
//body of class Vehicle
}
• Here we can see that the class Vehicle is not inheriting any class, but it
inherits the Object class. It is an example of the direct inheritance of object
class.
class Vehicle
{
//body of class Vehicle
}
class Car extends Vehicle
{
//body of class Car
}
• Here we can see that the Car class directly inherits the Vehicle class. the Car
indirectly inherits the Object class.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 10


Object Oriented Programming Using Java MMC202
\

Object Class Methods


• The Object class provides multiple methods which are as follows:
o toString() method
o hashCode() method
o equals(Object obj) method
o finalize() method
o getClass() method
o clone() method
o wait(), notify() notifyAll() methods

toString() method
• If you want to represent any object as a string, toString() method comes into
existence.
• The toString() method returns the String representation of the object.
• If you print any object, Java compiler internally invokes the toString()
method on the object. So overriding the toString() method, returns the
desired output, it can be the state of an object etc. depending on your
implementation.

Example

class Student12
{
int rollno;
String name;
String city;
Student12(int rollno, String name, String city)
{
[Link]=rollno;
[Link]=name;
[Link]=city;
}
public String toString()
{
return rollno+" "+name+" "+city;
}

public static void main(String args[])


{
Student12 s1=new Student12(101,"Raj","lucknow");
Student12 s2=new Student12(102,"Vijay",“Delhi");
[Link](s1);
[Link](s2);
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 11


Object Oriented Programming Using Java MMC202
\

hashCode() Method
• The hashCode() method is a Java Integer class method which returns the
hash code for the given inputs.

public class Hash


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

Integer i = new Integer("12");


int b = [Link]();
[Link]("Hash code Value for object is: " + b);
}
}

equals(Object obj) method



equals(Object obj) is the method of Object class. This method is used to
compare the given objects.
Syntax
public boolean equals(Object obj)

It returns true if this object is same as the obj argument else it returns false
otherwise.

class kiran
{
int a=25;
}
class bangaluru
{
public static void main(String[] args)
{
kiran s1 = new kiran();
kiran s2 = new kiran();
[Link]([Link](s2)); //false
kiran s3=s1;
[Link]([Link](s3)); //true
}
}

getClass() Method
• getClass() is the method of Object class. This method returns the runtime
class of this object.
public class Objectget
{
public static void main(String[] args)
{
Object obj = new String("23");
Class a = [Link]();
[Link]("Class of Object obj is : " + [Link]());
}
}
Output: Class of Object obj is : [Link]

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 12


Object Oriented Programming Using Java MMC202
\

Polymorphism in Java
• Polymorphism in Java is a concept by which we can perform a single action
in different ways.
• Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means
many forms.
• There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
• If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
• Runtime polymorphism or Dynamic Method Dispatch is a process in which a
call to an overridden method is resolved at runtime rather than compile-
time.
• In this process, an overridden method is called through the reference
variable of a superclass.
• The determination of the method to be called is based on the object being
referred to by the reference variable.
Upcasting
• If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting.
Example
class Bike
{
void run()
{
[Link]("running");
}
}
class Splendor extends Bike
{
void run()
{
[Link](“RNSIT");
}
public static void main(String args[])
{
Bike b = new Splendor(); //upcasting
[Link]();
}
}

Method overriding
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
Usage of Java Method Overriding
• Method overriding is used to provide specific implementation of a method
that is already provided by its super class.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• method must have same name as in the parent class
• method must have same parameter as in the parent class.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 13


Object Oriented Programming Using Java MMC202
\

EX:
class Vehicle
{
void run()
{
[Link]("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
[Link]("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
[Link]();
}
}

EX:2
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
[Link]("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
[Link]("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B sub = new B(1, 2, 3);
[Link]();

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 14


Object Oriented Programming Using Java MMC202
\

}
}
EX:3
class Animal
{
void move()
{
[Link]("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
[Link]();
[Link]("Dogs can walk and run");
}
}
public class TestDog
{
public static void main(String args[])
{
Animal b = new Dog(); // Animal reference but Dog object
[Link](); // runs the method in Dog class
}
}

Difference between method overloading and method overriding in java

Method Overloading Method Overriding

Method overloading is used to increase Method overriding is used to provide


the readability of the program. the specific implementation of the
method that is already provided by its
super class.

Method overloading is performed within Method overriding occurs in two


class. classes.

In case of method overloading, In case of method overriding,


parameter must be different parameter must be same.

Method overloading is the example of Method overriding is the example of run


compile time polymorphism. time polymorphism.

Return type can be same or different Return type must be same

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 15


Object Oriented Programming Using Java MMC202
\

Abstract classes
• A class that is declared with abstract keyword, is known as abstract class in
java. It can have abstract and non-abstract methods (method with body).
• Before learning java abstract class, let's understand the abstraction in java
first.
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
• Another way, it shows only important things to the user and hides the
internal details.
• A method that is declared as abstract and does not have implementation is
known as abstract method.
Ex:1
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
[Link]("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
[Link]();
}
}

Ex: 2
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
[Link]("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
[Link]("drawing circle");
}
}
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 16


Object Oriented Programming Using Java MMC202
\

[Link]();
}
}

Example of abstract class that have method body


abstract class Bike
{
Bike()
{
[Link]("bike is created");
}
abstract void run();
void changeGear()
{
[Link]("gear changed");
}
}
class Honda extends Bike
{
void run()
{
[Link]("running safely..");
}
}
class TestAbstraction3
{
public static void main(String args[])
{
Bike obj = new Honda();
[Link]();
[Link]();
}
}

String class in Java


• String is a sequence of characters.
• In java, objects of String are immutable which means a constant and cannot
be changed once created.
• Creating a String
• There are two ways to create string in Java:
• String literal
String s = “RNSIT”;
• Using new keyword
String s = new String (“BANGALORE);

String class has a variety of methods for string manipulation.


1. charAt(int index)
• This method requires an integer argument that indicates the position of
the character that the method returns.
• This method returns the character located at the String's specified index.
Example: //[Link]
String x = "airplane";
[Link]( [Link](2) ); // output is 'r'

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 17


Object Oriented Programming Using Java MMC202
\

2. concat(String s)
• This method returns a String with the value of the String passed in to the
method appended to the end of the String used to invoke the method.
Example
String x = "book";
[Link]( [Link]("author") );
// output is "bookauthor"
The overloaded + and += operators perform functions similar to the
concat()method
Example,
String x = "library";
[Link]( x + " card");
// output is "library card"
String x = "United";
x += " States”
[Link]( x );
// output is "United States"

3. equalsIgnoreCase(String s)
• This method returns a boolean value (true or false) depending on whether
the value of the String in the argument is the same as the value of the String
used to invoke the method.
Example
String x = "Exit"; [Link]([Link]("EXIT")); // is "true"
[Link]([Link]("tixe")); // is "false"

4. length()
• This method returns the length of the String used to invoke the method.
Example,
String x = "01234567";
[Link]( [Link]() ); // returns "8“

5. replace(char old, char new)


• This method returns a String whose value is that of the String used to
invoke the method, updated so that any occurrence of the char in the first
argument is replaced by the char in the second argument
Example
class stringg
{
public static void main(String args[])
{
String x = "RNSNT";
[Link]( [Link]('N', 'n') );
}
}

Output
RnSnT

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 18


Object Oriented Programming Using Java MMC202
\

5. String substring(int begin)


Syntax
substring(int begin, int end)
• The substring() method is used to return a part (or substring) of the String
used to invoke the method.
• The first argument represents the starting location (zero-based) of the
substring. If the call has only one argument, the substring returned will
include the characters to the end of the original String.
• If the call has two arguments, the substring returned will end with the
character located in the nth position of the original String where n is the
second argument.
Example
class SubStr
{
public static void main(String[] args)
{
String orgstr = "RNSIT BANGALORE";
String k= [Link](3); //IT BANGALORE
String substr = [Link](7,11); //ANGA
[Link](k);
[Link]("substr: " + substr);
}
}

6. toLowerCase()
• This method returns a String whose value is the String used to invoke the
method, but with any uppercase characters converted to lowercase.
Example,
String x = "A New Java Book";
[Link]( [Link]() );
// output is "a new java book"

7. toUpperCase()
• This method returns a String whose value is the String used to invoke the
method, but with any lowercase characters converted touppercase.
Example,
String x = "A New Java Book"; [Link]( [Link]());
// output is"A NEW JAVA BOOK"

8. trim() method
• The String class trim() method eliminates white spaces before and after the
String.
Example
class Stringoperation2
{
public static void main(String ar[])
{
String s=" Sachin ";
[Link]([Link]());//Sachin
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 19


Object Oriented Programming Using Java MMC202
\

9. char[ ] toCharArray( )
• This method will produce an array of characters from characters of String
object.
Example
String s = “Java”;
Char [] mca = [Link]();

10. boolean contains(“searchString”)


• This method returns true of target String is containing search String
provided in the argument.
Example-
String x = “Java is programming language”;
[Link]([Link](“Amit”)); // false
[Link]([Link](“Java”)); // true
Complete program
[Link]

Parameter Passing
• People usually take the pass by value and pass by reference terms together.
• It is really confusing and overhear questions in interviews, Is java pass by
value or passes by reference, or both? So the answer to this question is Java
is strictly pass by value.
• There is no pass by reference in Java.
• People usually take the pass by value and pass by reference terms together.
• It is really confusing and overhear questions in interviews, Is java pass by
value or passes by reference, or both? So the answer to this question is Java
is strictly pass by value.
• There is no pass by reference in Java.
• Pass by Value: In the pass by value concept, the method is called by passing
a value.
• So, it is called pass by value. It does not affect the original parameter.
• Pass by Reference: In the pass by reference concept, the method is called
using an alias or reference of the actual parameter.
• So, it is called pass by reference. It forwards the unique identifier of the
object to the method.
• If we made changes to the parameter's instance member, it would affect the
original value.
Example1:
class Test
{
void display(int i, int j)
{
i *= 2;
j += 2;
}
}

class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 20


Object Oriented Programming Using Java MMC202
\

[Link]("a and b before call: " +a + " " + b);


[Link](a, b);
[Link]("a and b after call: " +a + " " + b);
}
}
Output
a and b before call: 15 20
a and b after call: 15 20

Example2:
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
void Display(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 10);
[Link]("ob.a and ob.b before call: " + ob.a+ " " + ob.b);
[Link](ob);
[Link]("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}
Output
ob.a and ob.b before call: 15 10
ob.a and ob.b after call: 30 5

ENUMERATION:
• Enumeration is a list of named constants that define a new data type.
• An object of an enumeration type can hold only the values that are defined
by the list.
• Thus , an enumeration gives you a way to precisely define a new type of data
that has a fixed number of valid values.
• An enumeration is created using the enum keyword.
Ex:
enum Transport
{
CAR, TRUNK, TRAIN, BUS
}
• The identifiers CAR, TRUNK and so on are called enumeration constants or
enum constants.
• Each is implicitly declared as a public, static member of Transport.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 21


Object Oriented Programming Using Java MMC202
\

• Once you have declared an enumeration, you can create a variable of that
type.
• Even though enumerations define a class type, you do not instantiate an
enum using new.
Ex:
Transport tp;
• Because tp is of type of Transport, the only values that it can be assigned
are those constants defined by the enumeration or null.
Ex:
tp= [Link];
• Here BUS is assiged to tp.
• Two enumeration constant can be compared for equality by using the ==
relational operator.
Ex:
if(tp==[Link])
• Here this statement compares the value in tp with the CAR.
• An enumeration value can also be used to control a switch statement.

Example for switch


class MCA
{
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY }
public static void main(String args[])
{
Day a=[Link];
switch(a)
{
case SUNDAY:
[Link](“hello");
break;
case MONDAY:
[Link](“hello java");
break;
default: [Link]("other day");
}
}
}
• The enum can be defined within or outside the class because it is similar to
a class.

enum Season
{
WINTER, SPRING, SUMMER, FALL
}
class EnumExample2
{
public static void main(String[] args)
{
Season s=[Link];
[Link](s);
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 22


Object Oriented Programming Using Java MMC202
\

Example
enum NAMES
{
RAGHU, PRASAD, DEVA, SHIVA,KIRAN
}
class EnumExample3
{
public static void main(String[] args)
{
NAMES s=[Link];
[Link](s);
}
}
D:\raghu java practice>javac [Link]
[Link]: cannot find symbol
symbol : variable RAJ
location: class NAMES
NAMES s=[Link];
^
1 error

The values() AND valueOf() methods OR the built-in enumeration methods:


• All enumerations automatically have two predefined methods:
values()
valuesOf()
• Their general forms are
public static enum-type[] values()
public static enum-type valueOf(String str)
• The java compiler internally adds the values() method when it creates an
enum.
• The values() method returns an array containing all the values of the enum.
• The valuesOf() returns the enumeration value associated with the name of
the constant represented as a string.

Example for values():

class hello{
public enum Season
{
WINTER, SPRING, SUMMER, FALL
}
public static void main(String[] args)
{
for (Season s : [Link]())
[Link](s);
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 23


Object Oriented Programming Using Java MMC202
\

Example for valuesOf():

class EnumExample1{
public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
public static void main(String[] args)
{
for (Season s : [Link]())
[Link](s);
Season a = [Link]("SUMMER");
[Link]("the value of a is");
[Link](a);
}
}

OUTPUT WINTER
SPRING
SUMMER
FALL
the value of a is
SUMMER

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 24


Object Oriented Programming Using Java 22MCA22

MODULE 3

INTERFACES AND PACKAGES

Interfaces
Interface fundamentals
• In java, an interface defines a set of methods that will be implemented
by class.
• Interfaces are similar to abstract classes, except that no method can
include a body.
• This means an interface provides no implementation whatsoever of the
methods it defines.
• Once an interface is defined, any number of classes can implement it.
• One class can implement any number of class.
• An interface is defined by use of the interface keyword.
• General form of interface is access
interface name{
ret-type method-name1(param-list);
ret-type method-name2(param-list);
…… ……
ret-type method-nameN(param-list);
}
• Here, access is either public or not used. Implementing an interface
• Once an interface has been defined, one or more classes can implement
the interface.
• To implement an interface, follow these two steps.
1. In a class declaration, include an implements clause that specifies
the interface being implemented.
2. Inside the class, implement the methods defined by the interface.
General form of implements is
class classname implements interface {
//class body
}
Creating an interface
interface printable
{
void print();
}
class A6 implements printable {
public void print() {
[Link]("Hello");
}
public static void main(String args[])
{
A6 obj = new A6(); [Link]();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |1


Object Oriented Programming Using Java 22MCA22

Example2
interface Drawable {
void draw();
}
class Rectangle implements Drawable {
public void draw() {
[Link]("drawing rectangle");
}
}
class Circle implements Drawable {
public void draw() {
[Link]("drawing circle");
}
}
class TestInterface1 {
public static void main(String args[]) {
Drawable d=new Circle(); [Link]();
}
}

Example3
interface Bank {
int rateOfInterest();
}
class SBI implements Bank {
public int rateOfInterest() {
return 8;
}
}
class PNB implements Bank {
public int rateOfInterest() {
return 9;
}
}
class TestInterface2 {
public static void main(String[] args) {
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}
}
Implementing Multiple Interfaces
If a class implements multiple interfaces, or an interface extends multiple
interfaces i.e. known as multiple inheritance.
Ex:
interface Printable
{
void print();
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |2


Object Oriented Programming Using Java 22MCA22

interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void print() {
[Link]("Hello"); }
public void show() {
[Link]("Welcome");
}
public static void main(String args[]) {
A7 obj = new A7();
[Link]();
[Link]();
}
}

Interfaces can be extended


• One interface can be inherit another by use of the keyword extends.
• The syntax is same as for inheriting classes.
• When a class implements an interface that inherits another interface.
• It must be provide implementations for all
• methods defined within the interface inheritance chain.
• Ex:
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B {
public void meth1() {
[Link]("Implement meth1");
}
public void meth2() {
[Link]("Implement meth2");
}
public void meth3() {
[Link]("Implement meth3");
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |3


Object Oriented Programming Using Java 22MCA22

class IFExtend {
public static void main(String[] args) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

USING INTERFACE REFERENCES


• When you create a class, you are creating a new reference type.
• The same is true of interefaces.
• An interface declaration also creates a new reference type.
• When a class implements an interface, it is adding that interface's type to
its type.
• As a result, an instance of a class that implements an interface is also an
instance of that interface type.
EX:
interface Printable {
void sysout();
void displayName();
}
class Parent implements Printable {
public void displayName() {
[Link]("JAVA CLASS");
}
public void sysout() {
[Link]("MCA");
}
}
public class interface10 {
public static void main(String[] args) {
Parent obj=new Parent(); Printable a;
a=obj;
[Link]();
[Link]();
}
}

Constants in Interfaces
• The primary purpose of an interface is to declare methods that provide a
well-defined interface to functionality.
• An interface can also include variables.
• They are implicitly public, static, final and must be initialized.
• In other words, Interface fields are public, static and final by default, and
methods are public and abstract.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |4


Object Oriented Programming Using Java 22MCA22

• Ex:
interface Const {
int min= 0;
int max = 10;
String error = "Boundary Error";
}
class ConstDemo implements Const {
public static void main(String[] args) {
int[] nums = new int[max];

for(int i=min; i < (max + 1); i++)


{
if(i >= max)
[Link](error);
else {
nums[i] = i; [Link](nums[i] + " ");
}
}
}
}

Nested Interfaces
• An interface can be declared a member of another interface or of a class.
Such an interface is called member interface or a nested interface.
Ex:
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable, [Link] {
public void msg() {
[Link]("Hello nested interface");
}
public void show() {
[Link]("rnsit");
}
public static void main(String args[]) {
TestNestedInterface1 a=new TestNestedInterface1();
[Link]();
[Link]();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |5


Object Oriented Programming Using Java 22MCA22

Abstract Class vs Interface

Abstract class Interface


Abstract class can Interface can have only
have abstract and abstract methods.
nonabstract methods.
Abstract class doesn't Interface supports
support multiple multiple inheritance.
inheritance.
Abstract class can Interface has only
have final, non-final, static and final
static and non-static variables.
variables.
Abstract class can Interface can't have
have static methods, static methods, main
main method and method or
constructor. constructor.
Abstract class can Interface can't provide
provide the the implementation
implementation of of abstract class.
interface.
The abstract keyword The interface keyword
is used to declare is used to declare
abstract class. interface.

Ex:
interface A
{
void a();
void b();
void c();
void d();
}
abstract class B implements A
{
public void c() {
[Link]("I am C");
}
}

class M extends B
{
public void a() {
[Link]("I am a");
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |6


Object Oriented Programming Using Java 22MCA22

public void b() {


[Link]("I am b");
}
public void d() {
[Link]("I am d");
}
}
class Test5 {
public static void main(String args[])
{
A a=new M();
a.a();
a.b();
a.c();
a.d();
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |7


Object Oriented Programming Using Java 22MCA22

Packages
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• Package in java can be categorized in two form, builtin package and user
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
• All classes in Java belong to some package. When no package has been
explicitly specified, the default (or global) package is used.
• To create a package, you will use the package statement.
• General form of the package statement is package pkg;
• Here pkg is the name of the package.
• More than one file can include the same package statement.
• You can create hierarchy of packages.
• The general form is package pack1.pack2.pack3…..packN;
• Ex: package [Link];
• must be stored in /alpha/beta/gamma specifies the path to be specified
directories.
• Ex:
package mypack;
public class Simple {
public static void main(String args[]) {
[Link]("Welcome to package");
}
}
If you want to keep the package within the same directory, you can use .
(dot).
• To compile:
javac -d directory javafilename
• To Run:
java [Link]
• For above program to complile:
javac –d . [Link]
to run: java [Link]

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |8


Object Oriented Programming Using Java 22MCA22

Access Protection
• Packages act as containers for classes and other subordinate packages.
• Classes act as containers for data and code.
• The class is Java’s smallest unit of abstraction.
• Because of the interplay between classes and packages, Java addresses
four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses.
• The three access specifiers, private, public, and protected, provide a
variety of ways to produce the many levels of access required by these
categories.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page |9


Object Oriented Programming Using Java 22MCA22

Class member access

*having default access modifier are accessible only within the same
package.

protected access modifier


• The protected access modifier is accessible within package and outside
the package but through inheritance only.
• The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
Ex:
//save by [Link]
package pack; public class proA {
protected void msg() {
[Link]("WELCOME TO JAVA");
}
}
//save by [Link]
package mypack; import pack.*;
class proB extends proA {
public static void main(String args[])
{
proB obj = new proB();
[Link]();
}
}

default access modifier


• If you don't use any modifier, it is treated as default by default.
• The default modifier is accessible only within
package. It cannot be accessed from outside the package.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 10


Object Oriented Programming Using Java 22MCA22

• It provides more accessibility than private. But, it is more restrictive than


protected, and public.

Example
//[Link]
package pack; class proC
{
void msg() {
[Link]("Hello Bangalore");
}
}
//[Link]
package mypack; import pack.*;
class proD {
public static void main(String args[]) {
proC obj = new proC();
[Link]();
}
}
output
[Link]: error: proC is not public in pack;
cannot be accessed from outside package
proC obj = new proC();

Importing packages
• Using import, you can bring one or more members of a package into
view.
• The general form of import statement. import [Link];
• Here pkg is the name of the package, which can include its full path,
and classname is the name of the class being imported.
• If you want to import the entire contents of a package, use an
asterisk(*) for the class name.
Ex:
import [Link];
import mypack.*;
• In the first case,the MyClass is imported from mypack.
• In the second,all of the classes in myback are imported.
EX:
import [Link];
import [Link].*;
• All of the standard Java classes included with Java are stored in a
package called java.
• The basic language functions are stored in a package inside of the java
package called [Link].
import [Link].*;
EX:
import [Link].*;
class MyDate extends Date {}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 11


Object Oriented Programming Using Java 22MCA22

• The same example without the import statement looks like this: class
MyDate extends [Link] {}

Importing java’s Standard Packages


• Java defines a large number of standard classes that are available to all
programs.
Subpackage Description
[Link] Contains a large
number of general-
purpose classes
[Link] Contains the I/O
classes
[Link] Contains those classes
that support
networking
[Link] Contains classes for
creating applets
[Link] Contains classes that
support the Abstract
Window Toolkit
[Link] Contains various utility
classes, plus the
Collections Framework.

How to access package from another package?


There are three ways to access the package from outside the package.
import package.*;
import [Link]; fully qualified name.

package pack18;
// packagename.*
public class raghu18
{
public void msg() {
[Link]("Hello rnsit");
}
}
------------------------------------------------------
package mypack12;
import pack18.*;
class prasad12
{
public static void main(String args[]) {
raghu18 obj = new raghu18();
[Link]();
}
}
//save by [Link] Using [Link]

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 12


Object Oriented Programming Using Java 22MCA22

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]();
}
}
//save by [Link] package pack; Using fully qualified name
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]();
}
}

Static import
• The static import feature of Java 5 facilitate the java programmer to
access any static member of a class directly.
• There is no need to qualify it by the class name.
• Static imports are used to save your time and typing.
• If you hate to type same thing again and again then you may find such
imports interesting.

Example 1: Without Static Imports
class Demo1 {
public static void main(String args[]) {
double var1= [Link](5.0); double var2= [Link](30);
[Link]("Square of 5 is:"+ var1);
[Link]("Tan of 30 is:"+ var2);
}
}
OUTPUT
Square of 5 is:2.236 Tan of 30 is:-6.4053

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 13


Object Oriented Programming Using Java 22MCA22

Example 2: Using Static Imports

import static [Link].*;


import static [Link].*;
class Demo2 {
public static void main(String args[]) {
double var1= sqrt(5.0); double var2= tan(30);
[Link]("Square of 5 is:"+var1);
[Link]("Tan of 30 is:"+var2);
}
}

CLASSPATH
• CLASSPATH describes the location where all the required files are available
which are used in the application.
• Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate
the required files.
• If the CLASSPATH is not set, Java Compiler will not be able to find the
required files and hence will throw the following error.
Error: Could not find or load main class <class name>
Set the CLASSPATH in JAVA in Windows • Command Prompt:
set PATH=.;C:\ProgramFiles\Java\JDK1.6.20\bin

1. Select Start
2. Goto Control Pannel

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 14


Object Oriented Programming Using Java 22MCA22

3. Select System and Security

4. Select Advanced System Settings

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 15


Object Oriented Programming Using Java 22MCA22

5. Click on environment variable

6. Click on new under system variable

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 16


Object Oriented Programming Using Java 22MCA22

7. Add CLASSPATH as variable name and path of file

8. Select OK

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT P a g e | 17


Object Oriented Programming Using Java 22MCA22

MODULE 4

EXCEPTION HANDLING

The exception hierarchy:


• An exception is an error that occurs at run time.
• In java, all exceptions are represented by classes.
• All exception class are derived from a class called Throwable.
• Throwable class is the superclass of all errors and exceptions in the Java language.
• When an exception occurs in a program, an object of some type of exception class is
generated.

Benefits of exception handling


• By using exceptions to manage errors, Java programs have the following
advantages over traditional error management techniques:
• 1: Separating Error Handling Code from
• "Regular" Code.
• 2: Propagating Errors Up the Call Stack.
• 3: Grouping Error Types and Error Differentiation.

Exception handling fundamentals


• Java exception handling is managed via five keywords.
• They are try, catch, throw, throws and finally.
• Programs statements that you want to monitor for exceptions are contained a try
block.
• If an exception occurs within the try block, it is thrown.
• Your code can catch this exception using catch and handle it in some rational manner.
• System-generated exceptions are automatically thrown by the java run-time system.
• To manually throw an exception, use the keyword throw.
• Java try block must be followed by either catch or finally block.
• In some cases, an exception that is thrown out of a method must be specified as such
by a throws clause.
• Any code that absolutely must be executed upon exiting from a try block is put in a
finally block.
Syntax of java try-catch
try {
//code that may throw exception
}
catch(Exception_class_Name ref)
{
//code to handle exception

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 1


Object Oriented Programming Using Java 22MCA22

Syntax of try-finally block


try {
//code that may throw exception
}
finally
{

}
Ex:
Without using try-catch
public class testtry
{
public static void main(String args[]) {
int data=50/0;//may throw exception
[Link]("rest of the code...");
}
}

Output:
• Exception in thread main [Link]:/ by zero

Using java try-catch block.


public class testtry1 {
public static void main(String args[]) {
try{
int data=50/0;
}
catch(ArithmeticException e) {
[Link](e);
}
[Link]("rest of the code...");
}
}

Output:
• Exception in thread main [Link]:/ by zero rest of the code...
EX:
public class testtry2 {
public static void main(String args[]) {
int[] nums = new int[4];
try{
[Link](“RNSIT”);
nums[7]=80;
[Link](“MCA”);
}
catch(ArithmeticException e) {
[Link](e);
}
[Link]("rest of the code...");

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 2


Object Oriented Programming Using Java 22MCA22

}
}
The consequences of an uncaught exception
• If your program does not catch an exception, then it will be caught by the JVM.
• The trouble is that the JVM’s default exception handler terminates execution and
displays an error message followed by a list of the methods calls that lead to the
exception.

Internal working of java try-catch block

Using multiple catch clauses


• You can associate more than one catch clause with a try. Each catch must catch a
different type of exception.
• At a time only one Exception is occurred and at a time only one catch block is
executed.
• Ex:
public class MultipleCatchBlock1 {
public static void main(String args[]) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
[Link]("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
[Link]("task 2 completed"); }
catch(Exception e) {
[Link]("common task completed"); }

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 3


Object Oriented Programming Using Java 22MCA22

[Link]("rest of the code...");


}
}
• All catch blocks must be ordered from most specific to most general
i.e. Exception class have to come at last.

class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30;
}
catch(Exception e){
[Link]("common task completed");
}
catch(ArithmeticException e){
[Link]("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("task 2 c ompleted");
}
[Link]("rest of the code...");
}
}
OUTPUT
Compile-time error

Catching subclass exceptions


• There is one important point about multiple catch clauses that relates to subclasses.
• A catch clause for a superclass will also match any of its subclasses.
• If you want to catch exceptions of both a superclass type and a subclass type, put the
subclass first in the catch sequence.
• if you do not, then superclass catch will also catch all derived classes.

class ExcDemo5 {
public static void main(String[] args) {
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<[Link]; i++) {
try {
[Link](numer[i] + " / " + denom[i] + " is " +
numer[i]/denom[i]);
}catch (ArrayIndexOutOfBoundsException exc){
[Link]("No matching element found.");
}
catch (Exception e){
[Link]("Some exception occurred.");
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 4


Object Oriented Programming Using Java 22MCA22

}
}

try blocks can be nested


• One try block can be nested within another.
• An exception generated within the inner try block that is not caught by a catch
associated with that try is propagated to the outer try block.
Syntax
try
{
statements ;
try
{
statements;
}
catch(Exception e) { }
}
catch(Exception e) { }
....

Ex:
public class Excep6 {
public static void main(String args[]) {
try {
try {
int a[]=new int[5]; a[5]=30;
}
catch(Exception e) {
[Link]("task1 is completed");
}
try {
int a[]=new int[5];
a[4]=30/0;
}
catch(ArithmeticException e) {
[Link]("task2 is completed");
}
int b[]=new int[5];
b[5]=30;
}
catch(Exception e) {
[Link]("task3 is completed");
}
}
}

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 5


Object Oriented Programming Using Java 22MCA22

Throwing an exception
• The Java throw keyword is used to explicitly throw an exception.
• we can throw either checked or unchecked exception in java by throw keyword.
• The syntax of java throw keyword is given below throw exceptob;
• Here, exceptob must be an object of an exception class derived from Throwable.
• Only object of Throwable class or its sub classes can be thrown.
Creating Instance of Throwable class
• There are two possible ways to get an instance of class Throwable,
• Using a parameter in catch block.
• Creating instance with new operator.
new NullPointerException("test");
• This constructs an instance of NullPointerException with name test.
Ex:1
public class TestThrow1 {
static void validate(int age) {
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote"); }
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}
}

OUTPUT
Exception in thread main [Link]:not valid
Ex:2
class Test21{
static void avg() {
try {
throw new ArithmeticException("demo");
}
catch(Exception e) {
[Link](e);
}
}
public static void main(String args[]) {
avg();
[Link]("Exception caught");
}
}

throws
• In some cases, if a method generates an exception that it does not handle, it must declare
that exception in a throws clause.
• The general form of throws is

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 6


Object Oriented Programming Using Java 22MCA22

return-type methName(param-list)throws except-list {


//body
}
• Here, except-list is a comma-separated list of exceptions that the method might throw
outside of itself.
• subclass of Error or RuntimeException don’t need to be specified in a throws list.

Ex:1
import [Link].*;
class rns {
void mca()throws IOException {
throw new IOException("device error");
}
}
public class Testthrows2 {
public static void main(String args[]) {
try{
rns m=new rns(); [Link]();
}
catch(Exception e) {
[Link](e);
[Link]("normal flow...");
}
}
}

EX:2
import [Link].*;
class rnsit{
void mca(int a) throws IOException,ArithmeticException{
if(a%2==0)
throw new IOException("device error");
else
throw new ArithmeticException("error");
}
}
class Testthrows {
public static void main(String args[]) {
try{
rnsit m=new rnsit(); [Link](2);
}
catch(Exception e){
[Link](e); }
[Link]("normal flow...");
}
}
OUTPUT
[Link]:device Error normal flow…

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 7


Object Oriented Programming Using Java 22MCA22

EX3:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne(); }
catch (IllegalAccessException e) {
[Link]("Caught " + e);
}
}
}
Output
inside throwOne
caught [Link]: demo

Difference between throw and throws

A close look at Throwable


• All exception types are subclasses of the built-in class Throwable.
• Throwable is at the top of the exception class hierarchy.
• Immediately below Throwable are two subclasses that partition exceptions into two
distinct branches.
• One branch is headed by Exception.
• This class is used for exceptional conditions that user programs should catch.
• This is also the class that you will subclass to create your own custom exception
types.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 8


Object Oriented Programming Using Java 22MCA22

• The other branch is topped by Error, which defines exceptions that are not
expected to be caught under normal circumstances by your program.

Methods defined by throwable

Exception hierarchy
• The class at the top of the exception class hierarchy is the Throwable class, which is
a direct subclass of the Object class.
• Throwable has two direct subclasses –
1. Exception
2. Error

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 9


Object Oriented Programming Using Java 22MCA22

Throwable class:
• Throwable class which is derived from Object class, is a top of exception hierarchy
from which all exception classes are derived directly or indirectly.
• It is the root of all exception classes.
• It is present in [Link] package.
Error:
• Error class is the subclass of Throwable class and a superclass of all the runtime error
classes.
• It terminates the program if there is problem-related to a system or resources (JVM).
Exception:
• It is represented by an Exception class that represents errors caused by the program
and by
• external factors.
• Exception class is a subclass of Throwable class and a superclass of all the exception
classes.
• All the exception classes are derived directly or indirectly from the Exception class.
• They originate from within the application.

Exception Class Hierarchy in Java

Using finally
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block must be followed by try or catch block.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 10


Object Oriented Programming Using Java 22MCA22

Syntax:
finally{
finally code
}
Ex:1
class TestFinallyBlock {
public static void main(String args[]) {
try{
I nt data=25/5; [Link](data);
}
catch(ArithmeticException e){[Link](e);} finally
{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Ex:2
class TestFinallyBlock1 {
public static void main(String args[]) {
try {
int data=25/0; [Link](data);
}
catch(NullPointerException e) {
[Link](e);
}
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
• OUTPUT
(finally block is always executed)
Exception in thread main
[Link]:/ by zero
For each try block there can be zero or more catch blocks, but only one finally block.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 11


Object Oriented Programming Using Java 22MCA22

Difference between final, finally and finalize

Classification or Types of exceptions


• Exceptions can be categorized into two ways:
• Built-in Exceptions
o Checked Exception
o Unchecked Exception
• User-Defined Exceptions

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 12


Object Oriented Programming Using Java 22MCA22

Built-in exceptions
• Exceptions that are already available in Java libraries are referred to as built-in
exception.
• These exceptions are able to define the error situation so that we can understand the
reason of getting this error.
• It can be categorized into two broad categories, i.e., checked exceptions and
unchecked exception.
Checked Exception
• Checked exceptions are called compiletime exceptions because these exceptions are
checked at compile-time by the compiler.
• The compiler ensures whether the programmer handles the exception or not.
• The programmer should have to handle the exception; otherwise, the system has
shown a compilation error.

Checked exceptions defined by [Link]

UnChecked Exception
• An unchecked exception is an exception that occurs at the time of execution.
• These are also called as Runtime Exceptions.
• These include programming bugs, such as logic errors or improper use of an API.
• Runtime exceptions are ignored at the time of compilation.

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 13


Object Oriented Programming Using Java 22MCA22

Unchecked exceptions defined by [Link]

Creating Exception subclasses or how to create your own


exception
• If you are creating your own Exception that is known as custom exception or user-
defined exception.
• Just define a subclass of Exception(which is a subclass of Throwable).
• The Exception class does not define any methods of its own. It does inherit those
methods provided by Throwable.
• You can override one or more of these methods in exception subclass that you
create.
• Two commonly used Exception constructors are shown here;
Exception()
Exception(String msg)
Ex:
class MyException extends Exception {
private int detail; MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]"; }
}
public class rnsitown {
static void compute(int a) throws MyException {
[Link]("Called compute(" + a + ")");
if (a > 10)
{
throw new MyException(a);
}
[Link]("Normal exit");

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 14


Object Oriented Programming Using Java 22MCA22

}
public static void main(String args[] {
try {
compute(1); compute(20);
}
catch (MyException e) {
[Link]("Caught " + e);
}
}
}
Output
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]

• If you want to represent any object as a string, toString() method comes into existence.
• The toString() method returns the string representation of the object.

Chained Exceptions
• Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
• For example, consider a situation in which a method throws an ArithmeticException
because of an attempt to divide by zero but the actual cause of exception was an I/O
error which caused the divisor to be zero.
• The method will throw only ArithmeticException to the caller.
• So the caller would not come to know about the actual cause of exception.
Chained Exception is used in such type of situations.
• Constructors Of Throwable class Which support chained exceptions in java :
• Throwable(Throwable cause) :- Where cause is the exception that causes the current
exception.
• Throwable(String msg, Throwable cause) :- Where msg is the exception message
and cause is the exception that causes the current exception.
• Methods Of Throwable class Which support chained exceptions in java :
• getCause() method :- This method returns actualcause of an exception.
• initCause(Throwable cause) method :- This method sets the cause for the calling
exception.

public class chain {


public static void main(String[] args)
{
try {
NumberFormatException ex = new
NumberFormatException("Exception");
[Link](new NullPointerException("This is actual cause of the
exception"));
throw ex;
}
catch(NumberFormatException a) {

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 15


Object Oriented Programming Using Java 22MCA22

[Link](a);
[Link]([Link]());
}
}
}
Output
[Link]: Exception [Link]: This is actual
cause of the exception

Mr. Raghu Prasad K, Assistant Professor, MCA Dept | RNSIT Page 16


OBJECT ORIENTED PROGRAMMING USING JAVA

MODULE- 5 GUI PROGRAMMING AND APPLETS


GUI (Graphical User Interface
• GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications.
• It is mainly made of graphical components like buttons, labels, windows, etc. through which
the user can interact with an application.
• GUI plays an important role to build easy interfaces for Java applications.
AWT class hierarchy:
• AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
• AWT components are platform-dependent i.e components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
• The [Link] package provides classes for AWT api such as TextField, Label,
TextArea,RadioButton, CheckBox, Choice, List etc.

Container
• The Container is one of the components in AWT that contains other components like
buttons, text fields, labels, etc.
• The classes that extend the Container class are known as containers such as Frame, Dialog,
and Panel as shown in the hierarchy.
Types of containers
• Container refers to the location where components can be added like text field, button,
checkbox, etc.
• There are four types of containers available in AWT, that is, Window, Frame, Dialog, and
Panel.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 1


OBJECT ORIENTED PROGRAMMING USING JAVA

• As shown in the hierarchy above, Frame and Dialog are subclasses of the Window class.
1. Window: The window is a container that does not have borders and menu bars. In order to create
a window, you can use frame, dialog or another window.
2. Panel: The Panel is the container/class that doesn’t contain the title bar and menu bars. It has
other components like buttons, text fields, etc.
3. Dialog: The Dialog is the container or class having a border and title. We cannot create an
instance of the Dialog class without an associated instance of the respective Frame class.
4. Frame: The Frame is the container or class containing the title bar and might also have menu
bars. It can also have other components like text field, button, etc.

Introduction to Swing
• Swing is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


• AWT and Swing are used to develop window-based applications in Java.
• Awt is an abstract window toolkit that provides various component classes like Label,
Button, TextField, etc., to show window components on the screen. All these classes are
part of the [Link] package.
• Swing is the part of JFC (Java Foundation Classes) built on the top of AWT and written
entirely in Java.
• The [Link] API provides all the component classes like JButton, JTextField,
JCheckbox, JMenu, etc.

Context AWT Swing

API Package The AWT Component classes are The Swing component classes are
provided by the [Link] package. provided by the [Link] package.

Operating System The Components used in AWT are The Components used in Swing are
mainly dependent on the operating not dependent on the operating
system. system. It is completely scripted in
Java.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 2


OBJECT ORIENTED PROGRAMMING USING JAVA

Weightiness The AWT is heavyweight since it The Swing is mostly lightweight


uses the resources of the operating since it doesn't need any Operating
system. system object for processing. The
Swing Components are built on the
top of AWT.

Appearance The Appearance of AWT The Swing Components are


Components is mainly not configurable and mainly support
configurable. It generally depends pluggable look and feel.
on the operating system's look and
feels.

Number of The Java AWT provides a smaller Java Swing provides a greater number
Components number of components in of components than AWT, such as
comparison to Swing. list, scroll panes, tables, color
choosers, etc.

Full-Form Java AWT stands for Abstract Java Swing is mainly referred to as
Window Toolkit. Java Foundation Classes (JFC).

Functionality and Java AWT many features that are Swing components provide the
Implementation completely developed by the higher-level inbuilt functions for the
developer. It serves as a thin layer developer that facilitates the coder to
of development on the top of the write less code.
OS.

Memory Java AWT needs a higher amount Java Swing needs less memory space
of memory for the execution. as compared to Java AWT.

Speed Java AWT is slower than swing in Java Swing is faster than the AWT.
terms of performance.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 3


OBJECT ORIENTED PROGRAMMING USING JAVA

Hierarchy of Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager sets the layout manager for the component.
m)

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 4


OBJECT ORIENTED PROGRAMMING USING JAVA

Java Swing Examples


There are two ways to create a frame:
• By creating the object of Frame class (association)
• By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
File: [Link]
import [Link].*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame(); //creating instance of JFrame
JButton b=new JButton("click"); //creating instance of JButton
[Link](130,100,100, 40); //x axis, y axis, width, height
[Link](b);//adding button in JFrame
[Link](400,500); //400 width and 500 height
[Link](null); //using no layout managers
[Link](true);//making the frame visible
} }
Output:

SINDHU S L,ASST PROFESSOR,BIET, DVG. 5


OBJECT ORIENTED PROGRAMMING USING JAVA

Container
• The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
• It is basically a screen where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a container
inside container.
JFrame:
• The [Link] class is a type of container which inherits the [Link] class.
• JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.
• Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
[Link](new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
[Link]("Button");
[Link](label);
[Link](button);
[Link](panel);
[Link](200, 300);
[Link](null);

SINDHU S L,ASST PROFESSOR,BIET, DVG. 6


OBJECT ORIENTED PROGRAMMING USING JAVA

[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output

JDialog
• The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.
• Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
Syntax:
public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer

Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless dialog without a title and


without a specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with specified Frame as


its owner and an empty title.

JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 7


OBJECT ORIENTED PROGRAMMING USING JAVA

Java JDialog Example


import [Link].*;
import [Link].*;
import [Link].*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
JButton b = new JButton ("OK");
[Link] ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
[Link](false);
}
});
[Link]( new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
new DialogExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 8


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JPanel
• The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class.
• It doesn't have title bar.
JPanel class declaration
public class JPanel extends JComponent implements Accessible
Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified
isDoubleBuffered) buffering strategy.

JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.

JPanel Example
import [Link].*;
import [Link].*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");

SINDHU S L,ASST PROFESSOR,BIET, DVG. 9


OBJECT ORIENTED PROGRAMMING USING JAVA

JPanel panel=new JPanel();


[Link](40,80,200,200);
[Link]([Link]);
JButton b1=new JButton("Button 1");
[Link](50,100,80,30);
[Link]([Link]);
JButton b2=new JButton("Button 2");
[Link](100,100,80,30);
[Link]([Link]);
[Link](b1); [Link](b2);
[Link](panel);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:

SINDHU S L,ASST PROFESSOR,BIET, DVG. 10


OBJECT ORIENTED PROGRAMMING USING JAVA

JButton
• The JButton class is used to create a labeled button that has platform independent
implementation.
• The application result in some action when the button is pushed. It inherits AbstractButton
class.
JButton class declaration
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Button Example
import [Link].*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
[Link](50,100,95,30);
[Link](b);
[Link](400,400);
[Link](null);
[Link](true);
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 11


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JLabel
• The object of JLabel class is a component for placing text in a container.
• It is used to display a single line of read only text.
• The text can be changed by an application but a user cannot edit it directly.
• It inherits JComponent class.
JLabel class declaration
public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an


empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 12


OBJECT ORIENTED PROGRAMMING USING JAVA

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.

JLabel Example
import [Link].*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
l2=new JLabel("Second Label.");
[Link](50,100, 100,30);
[Link](l1); [Link](l2);
[Link](300,300);
[Link](null);
[Link](true);
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 13


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JTextField
• The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.

JTextField class declaration


public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 14


OBJECT ORIENTED PROGRAMMING USING JAVA

Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive


action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it


removeActionListener(ActionListener l) no longer receives action events from this textfield.

JTextField Example
import [Link].*;
class TextFieldExample {
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
t2=new JTextField("AWT Tutorial");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 15


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JTextArea
• The object of a JTextArea class is a multi line region that displays text.
• It allows the editing of multiple line text. It inherits JTextComponent class

JTextArea class declaration


public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int column) Creates a text area with the specified number of rows and columns
that displays no text initially.

JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns
column) that displays specified text.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 16


OBJECT ORIENTED PROGRAMMING USING JAVA

Commonly used Methods:

Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int position) It is used to insert the specified text on the specified position.

void append(String s) It is used to append the given text to the end of the document.

JTextArea Example
import [Link].*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
[Link](10,30, 200,200);
[Link](area);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 17


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

LayoutManagers
• The LayoutManagers are used to arrange components in a particular manner.
• The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms.
• LayoutManager is an interface that is implemented by all the classes of layout managers.

There are the following classes that represent the layout managers:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link] etc.
BorderLayout
• The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center.
• Each region (area) may contain one component only.
• It is the default layout of a frame or window.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 18


OBJECT ORIENTED PROGRAMMING USING JAVA

The BorderLayout provides five constants for each region:


public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical
gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: [Link]
import [Link].*;
import [Link].*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
[Link](b1, [Link]); // b1 will be placed in the North Direction
[Link](b2, [Link]); // b2 will be placed in the South Direction
[Link](b3, [Link]); // b2 will be placed in the East Direction
[Link](b4, [Link]); // b2 will be placed in the West Direction
[Link](b5, [Link]); // b2 will be placed in the Center

SINDHU S L,ASST PROFESSOR,BIET, DVG. 19


OBJECT ORIENTED PROGRAMMING USING JAVA

[Link](300, 300);
[Link](true);
}
public static void main(String[] args) {
new Border();
}
}
Output:

GridLayout
• The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows
and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor


import [Link].*;

SINDHU S L,ASST PROFESSOR,BIET, DVG. 20


OBJECT ORIENTED PROGRAMMING USING JAVA

import [Link].*;
public class GridLayoutExample
{
JFrame frameObj;
GridLayoutExample()
{
frameObj = new JFrame();
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
[Link](btn1); [Link](btn2); [Link](btn3);
[Link](btn4); [Link](btn5); [Link](btn6);
[Link](btn7); [Link](btn8); [Link](btn9);
// setting the grid layout using the parameterless constructor
[Link](new GridLayout());
[Link](300, 300);
[Link](true);
}
public static void main(String argvs[])
{
new GridLayoutExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 21


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

FlowLayout
• The Java FlowLayout class is used to arrange the components in a line, one after another (in
a flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING

Constructors of FlowLayout class


FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor


import [Link].*;
import [Link].*;
public class FlowLayoutExample
{
JFrame frameObj;

SINDHU S L,ASST PROFESSOR,BIET, DVG. 22


OBJECT ORIENTED PROGRAMMING USING JAVA

FlowLayoutExample()
{
frameObj = new JFrame();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
[Link](b1); [Link](b2); [Link](b3); [Link](b4);
[Link](b5); [Link](b6); [Link](b7); [Link](b8);
[Link](b9); [Link](b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
[Link](new FlowLayout());
[Link](300, 300);
[Link](true);
}
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 23


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

Applet
• Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage/Features of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
• Applet is a small and easy-to-write Java program.
• One can easily install Java applet along with various HTML documents.
• One needs a web browser (Java based) to use applets.
• Applet do not have access to the network or local disk and can only access browser-specific
services.
• It cannot perform system operations on local machines.
• Applet cannot establish access to local system.

Drawback of Applet
• Plugin is required at client browser to execute applet.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 24


OBJECT ORIENTED PROGRAMMING USING JAVA

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
subclass of Component.

Java Application Vs. Java Applet

Parameters Java Application Java Applet

Meaning A Java Application also known as The Java applet works on the client side,
application program is a type of and runs on the browser and makes use of
program that independently executes another application program so that we
on the computer. can execute it.

Requirement of Its execution starts with the main( ) It does not require the use of any main()
main( ) method method only. The use of the main( ) is method. Java applet initializes through
mandatory. init( ) method.

Execution It cannot run independently, but It cannot start independently but requires
requires JRE to run. APIs for use (Example. APIs like Web
API).

Installation We need to install the Java application Java applet does not need to be pre-
first and obviously on the local installed.
computer.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 25


OBJECT ORIENTED PROGRAMMING USING JAVA

Connectivity It is possible to establish connections It cannot establish connection to other


with server with other servers. servers.

Operation It performs read and write tasks on a It cannot run the applications on any local
variety of files located on a local computer.
computer.

File access It can easily access a file or data It cannot access the file or data found on
available on a computer system or any local system or computer.
device.

Security Java applications are pretty trusted, Java applets are less reliable. So, they
and thus, come with no security need to be safe.
concerns.

Applet Life Cycle


• In Java, an applet is a special type of program embedded in the web page to generate
dynamic content. Applet is a class in Java.
• The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application.
• It basically has five core methods namely init(), start(), stop(), paint() and destroy().These
methods are invoked by the browser to execute.
Along with the browser, the applet also works on the client side, thus having less processing time.

Methods of Applet Life Cycle

SINDHU S L,ASST PROFESSOR,BIET, DVG. 26


OBJECT ORIENTED PROGRAMMING USING JAVA

There are five methods of an applet life cycle, and they are:
init():
• The init() method is the first method to run that initializes the applet. It can be invoked only
once at the time of initialization.
• The web browser creates the initialized objects, i.e., the web browser (after checking the
security settings) runs the init() method within the applet.
start():
• The start() method contains the actual code of the applet and starts the applet. It is invoked
immediately after the init() method is invoked.
• Every time the browser is loaded or refreshed, the start() method is invoked.
• It is also invoked whenever the applet is maximized, restored, or moving from one tab to
another in the browser.
• It is in an inactive state until the init() method is invoked.
stop():
• The stop() method stops the execution of the applet.
• The stop () method is invoked whenever the applet is stopped, minimized, or moving from
one tab to another in the browser, the stop() method is invoked. When we go back to that
page, the start() method is invoked again.
destroy():
• The destroy() method destroys the applet after its work is done. It is invoked when the
applet window is closed or when the tab containing the webpage is closed.
• It removes the applet object from memory and is executed only once. We cannot start the
applet once it is destroyed.
paint():
• The paint() method belongs to the Graphics class in Java. It is used to draw shapes like
circle, square, trapezium, etc., in the applet.
• It is executed after the start() method and when the browser or applet windows are resized.

Life Cycle Working


• The plug-in software is responsible for managing the life cycle of an applet.
• An applet is a Java application executed in any web browser and works on the client-side. It
doesn't have the main() method because it runs in the browser. It is thus created to be placed
on an HTML page.
• The init(), start(), stop() and destroy() methods belongs to the [Link] class.
• The paint() method belongs to the [Link] class.
• If we want to make a class an Applet class, we need to extend the Applet
• Whenever we create an applet, we are creating the instance of the existing Applet class. And
thus, we can use all the methods of that class.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 27


OBJECT ORIENTED PROGRAMMING USING JAVA

Flow of Applet Life Cycle:


These methods are invoked by the browser automatically. There is no need to call them explicitly.

Syntax of entire Applet Life Cycle in Java


class TestAppletLifeCycle extends Applet
{
public void init()
{
// initialized objects
}
public void start()
{
// code to start the applet
}
public void paint(Graphics graphics)
{
// draw the shapes
}
public void stop() {
// code to stop the applet
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 28


OBJECT ORIENTED PROGRAMMING USING JAVA

public void destroy() {


// code to destroy the applet
}
}
Parameter in Applet
• We can get any information from the HTML file as a parameter.
• For this purpose, Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import [Link];
import [Link];
public class UseParam extends Applet
{
public void paint(Graphics g){
String str=getParameter("msg");
[Link](str,50, 50);
}
}
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

SINDHU S L,ASST PROFESSOR,BIET, DVG. 29

You might also like