0% found this document useful (0 votes)
42 views51 pages

Java Programming Study Notes MCS 024

The document provides comprehensive study notes on Object Oriented Technology and Java Programming, covering key concepts such as objects, classes, encapsulation, inheritance, and polymorphism. It also details Java language basics, including the Java Virtual Machine (JVM), bytecode, and platform independence. The notes are structured into blocks and units, each focusing on different aspects of object-oriented programming and Java development.

Uploaded by

piyush72717272
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)
42 views51 pages

Java Programming Study Notes MCS 024

The document provides comprehensive study notes on Object Oriented Technology and Java Programming, covering key concepts such as objects, classes, encapsulation, inheritance, and polymorphism. It also details Java language basics, including the Java Virtual Machine (JVM), bytecode, and platform independence. The notes are structured into blocks and units, each focusing on different aspects of object-oriented programming and Java development.

Uploaded by

piyush72717272
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

lOMoARcPSD|37613978

MCS 024 Object Oriented Technology and Java


Programming Study Notes
Object Oriented Technologies and Java Programming (Indira Gandhi National Open
University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by MR PIYUSH YT (piyushkumat76@[Link])
lOMoARcPSD|37613978

Contents
Block 1.........................................................................................................................................................4
Unit 1 Object Oriented Methodology 1.......................................................................................................4
Components of Object Oriented Programming.......................................................................................4
Objects....................................................................................................................................................4
Class.........................................................................................................................................................5
Encapsulation..........................................................................................................................................6
Inheritance..............................................................................................................................................6
Salient Features of Object Oriented Programming..................................................................................8
JVM..........................................................................................................................................................8
Public static void main.............................................................................................................................9
Bytecode..................................................................................................................................................9
Java Platform Independence....................................................................................................................9
Unit 2 Object Oriented Methodology 2.....................................................................................................11
Forms of Inheritance.............................................................................................................................11
Benefits of Inheritance..........................................................................................................................11
Unit 3 – Java Language Basics....................................................................................................................13
Java Platform Independence..................................................................................................................13
Dynamic Initialization............................................................................................................................13
Unit 4 – Expression, Statements, and Arrays.............................................................................................15
Switch Statement...................................................................................................................................15
Block 2.......................................................................................................................................................17
Unit 1 – Class and Objects.........................................................................................................................17
Passing objects as parameters...............................................................................................................17
Static Methods.......................................................................................................................................19
Method Overloading.............................................................................................................................20
finalize() method...................................................................................................................................21
Creating Objects....................................................................................................................................23
Constructors..........................................................................................................................................23
Unit 2 – Inheritance and Polymorphism....................................................................................................25

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Abstract Classes.....................................................................................................................................25
Public Access Specifier...........................................................................................................................26
Private Access Specifier.........................................................................................................................26
Method Overriding................................................................................................................................27
Final Keyword........................................................................................................................................29
Unit 3 – Packages and Interface.................................................................................................................31
Interfaces...............................................................................................................................................31
Implementing Interfaces........................................................................................................................31
Package..................................................................................................................................................34
CLASSPATH.............................................................................................................................................34
Interfaces and Abstract Class.................................................................................................................35
import keyword.....................................................................................................................................35
throws keyword.....................................................................................................................................35
Exception...............................................................................................................................................36
Causes of Exception...............................................................................................................................37
Block 3.......................................................................................................................................................38
Unit 1 – Multithreaded Programming........................................................................................................38
Notify and notifyAll................................................................................................................................38
Unit 2 – IO in Java......................................................................................................................................39
Unit 3 – Strings and Characters..................................................................................................................40
String Class Constructors.......................................................................................................................40
Unit 4 – Exploring Java IO..........................................................................................................................41
Serialization...........................................................................................................................................41
Block 4.......................................................................................................................................................42
Unit 1 – Applets.........................................................................................................................................42
Applets..................................................................................................................................................42
Events....................................................................................................................................................42
Applet LifeCycle.....................................................................................................................................43
Unit 2 – Graphic and User Interface..........................................................................................................44
Container...............................................................................................................................................44
Layout Manager.....................................................................................................................................44
Difference between swing and awt.......................................................................................................45

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 3 – Networking Features....................................................................................................................46


Unit 4 – Advance Java................................................................................................................................47
Java Beans.............................................................................................................................................47
Features of JavaBeans............................................................................................................................47
RMI........................................................................................................................................................48
Servlets..................................................................................................................................................49
JDBC.......................................................................................................................................................49
JDBC Connection....................................................................................................................................50

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Block 1

Unit 1 Object Oriented Methodology 1


Components of Object Oriented Programming
- Objects and Classes
- Data Abstraction and Encapsulation
- Inheritance
- Polymorphism

Objects
- An object is a software bundle of variables and related methods
- Real-world objects share two characteristics: They all have state and
behavior. For example, cars have state (current gear, current speed,
front wheels, number of gears) and behavior (braking, accelerating,
slowing down, changing gears). Because Software objects are modeled
after real-world objects, they too have state and behavior.
- A software object maintains its state in one or more variables. A
variable is an item of data named by an identifier.
- A software object reflects its behavior with the help of method
implementation. A method is an implementation way of a function
associated with an object.
- Everything that the software object knows (state) and can do
(behavior) is expressed by the variables and the methods within that
object. For example, a software object that modeled your real-world
car would have variables that indicated the car’s current state: its
speed is 100 kmph, and its current gear is the 5th gear.
- These variables used to represent the object’s state are formally
known as instance variables, because they contain the state for a
particular car instance.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- In addition to its variables, the software car object would also have
methods to brake, change gears, etc. These methods are formally
known as instance methods because they impact or change the state
of a particular car instance.
- In object-oriented terminology, a particular object is called an instance
of the class to which it belongs.

Class
- A class is a blueprint, or prototype, that defines the variables and the
methods common to all objects of a certain kind.
- The class for a car would declare the instance variables necessary to
contain the current gear, the current speed, and so on, for each car
object.
- The class would also declare and provide implementations for the
instance methods that allow the driver to change gears, brake, etc.
- After you’ve created the car class, you can create any number of car
objects from the class. When you create an instance of a class, the
system allocates enough memory for the object and all its instance
variables. Each instance gets its own copy of all the instance variables
defined in the class.
- In addition to instance variables, classes can define class variables.
- A class variable contains information that is shared by all instances of
the class. For example, suppose that all cars had the same number of
gears (18). In this case, defining an instance variable to hold the
number of gears is inefficient; each instance would have its own copy
of the variable, but the value would be the same for every instance. In
such situations, you can define a class variable. All instances share this
variable. If one object changes the variable, it changes for all other
objects of that class.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- A class can also declare class methods. You can invoke a class method
directly from the class, whereas you must invoke instance methods
from a particular instance.

Encapsulation
- Packaging an object’s variables within the protective custody of its
methods is called encapsulation.
- This is one of the strong features of the object oriented approach. The
data is not directly accessible to the outside world. Only the functions,
which are wrapped in the class, can access it.
- Encapsulating related variables and methods into a neat software
bundle is a simple yet powerful idea that provides two primary
benefits to software developers:
o Modularity: The source code for an object can be written and
maintained independently of the source code for other objects.
Also, an object can be easily passed around in the system. You
can give your car to someone else, and it will still work.
o Information hiding: An object has a public interface that other
objects can use to communicate with it. The object can maintain
private information and methods that can be changed at any
time without affecting the other objects that depend on it. You
don’t need to understand the gear mechanism in your car to use
it.

Inheritance
- Inheritance is a language property specific to the object-oriented
paradigm.
- Inheritance is used for a unique form of code-sharing by allowing you
to take the implementation of any given class and build a new class
based on that implementation.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- Let us say class B, starts by inheriting all of the data and operations
defined in class A. This new subclass can extend the behavior by
adding additional data and new methods to operate on it.
- Basically during programming inheritance is used for extending the
existing property of a class. In other words, it can be said that
inheritance is “from-generalization-to-specialization”.
- By using a general class, a class with specific properties can be defined.
- Now let us take the example of BankAccount class, which is declared
as:
class BankAccount
{
data members
member functions
}
Data members and member functions of BankAccount class are used
to display characteristics of withdrawals, deposits, balance, etc.
- Now suppose you want to define a SavingAccount class. In the
SavingAccount class, you will definitely have basic characteristics of the
Bankaccount class mentioned above.
- In your SavingAccount class you can use the properties of BankAccount
class, without any modification in them using inheritance.
- To inherit a class into another class, extends keyword is used.
- SavingAccount class will inherit BankAccount class as given below.
class SavingAccount extends BankAccount
{
data members
member functions
}

Salient Features of Object Oriented Programming


- More emphasis is on data rather than procedure.
- Programs are modularized into entities called objects.
- Data structures and methods characterize the objects of the problem.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- Since the data is not global, there is no question of any operations


other than those defined within the object, accessing the data.
Therefore, there is no scope of accidental modification of data.
- It is easier to maintain programs. The manner in which an object
implements its operations is internal to it. Therefore, any change
within the object would not affect external objects. Hence, systems
built using objects are resilient to change.
- Object reusability, which can save many human hours of effort, is
possible. An application developer can use objects like ‘array’, ‘list’,
‘windows’, and many other components, which were developed by
other programmers, in her program and thereby reduce program
development time.
- It employs bottom-up approach in program design.

JVM
- When a Java program is compiled, it is converted to byte code ,which
is then executed by the Java interpreter by translating the byte code
into machine instructions. Java interpreter is part of Java runtime
environment. Byte code is an intermediate code independent of any
machine and any operating system. Program in Java runtime
environment, which is used to interpret the byte code, is called Java
Virtual Machine (JVM).
- The JVM plays the main role to making Java portable.
- It provides a layer of abstraction between the compiled Java program
and the hardware platform and operating system.
- The JVM is central to Java’s portability because compiled Java
programs run on the JVM, independent of whatever hardware is used.

Public static void main


- This is the point from where the program will start the execution.
- The program starts the execution by calling main () method.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- In this line public, static, and void all are keywords.


- The public keyword is used to control the access of various class
members.
- If member is public it can be accessed outside the class. So we have to
declare main () as public because it has to be invoked by the code
outside the class when program is executed.
- Static key word allows the main () method to be executed without
creating an object of that class, and void means main () method does
not return any value.

Bytecode
- Generally a language is either compiled or interpreted, but Java is both
compiled as well as interpreted.
- First, a Java program is compiled and comes in the form of "Java byte
code" (which is an intermediate code).
- Then, this Java byte code is run on interpreter to execute a program.
- This byte code is the actual power of Java to make it popular and
dominating over other programming languages.

Java Platform Independence


- Java is Platform independent. In the computer industry, platform
typically means some combination of hardware and system software
but here you can understand it as your operating system.
- Java is compiled to an intermediate form called Java byte-code or
simply byte code. A Java program never really executes immediately
after compilation on the host machine. Rather, this special program
called the Java interpreter or Java Virtual Machine reads the byte code,
translates it into the corresponding host machine instructions and
then executes the machine instructions.
- A Java program can run on any computer system for which a JVM (Java
Virtual Machine) and some library routines have been installed.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- The second important part which makes Java portable is the


elimination of hardware architecture dependent constructs. For
example, integers are always four bytes long and floating-point
variables follow the IEEE 754 standard,
- You don’t need to worry that the interpretation of your integer is going
to change if you move from one hardware to another hardware like
Pentium to a PowerPC. You can develop a Java program on any
computer system and the execution of that program will be possible
on any other computer system loaded with JVM.
- For example, you can write and compile a Java program on Windows
98 and execute the compiled program on JVM of a Macintosh
operating system.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 2 Object Oriented Methodology 2


Forms of Inheritance
- Single Inheritance: In this form, a subclass can have only one super
class.
- Multiple Inheritance: This form of inheritance can have several
superclasses.
- Multilevel Inheritance: This form has subclasses derived from another
subclass. The example can be grandfather, father and child.
- Hierarchical Inheritance: This form has one superclass and many
subclasses. More than one class inherits the traits of one class. For
example: bank accounts

Benefits of Inheritance
- Subclasses provide specialized behaviors from the basis of common
elements provided by the superclass. Through the use of inheritance,
programmers can reuse the code in the superclass many times. Once a
superclass is written and debugged, it need not be touched again but

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

at the same time can be adapted to work in different situations.


Reusing existing code saves time and money and increases a program’s
reliability.
- Programmers can implement superclasses called abstract classes that
define “generic” behaviors. A class for which objects don’t exist.
Example: Furniture class has no object, but its derived classes: chair,
table have objects. The abstract superclass defines and may partially
implement the behavior, but much of the abstract class is undefined
and unimplemented. These undefined and unimplemented behaviors
fill in the details with specialized subclasses. Hence, Inheritance can
also help in the original conceptualization of a programming problem,
and in the overall design of the program.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 3 – Java Language Basics


Dynamic Initialization
- We can declare and assign a value to a variable in a single statement.
This is called Dynamic initialization.
- Variables can be dynamically initialized using any expression valid at
the time the variable is declared.
- Example:
class DynamicInitialization {

public static void main (String args [ ] )

double h = 3.0, b = 4.0;

double c = [Link](h*h + b*b); // here c is dynamically

initialized

[Link] (“ Hypotenuse is ” + c);

Here, in this code, the variables h and b are declared and initialized to
some values in a single statement.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 4 – Expression, Statements, and Arrays


Switch Statement
- Java has a built-in multiway decision statement known as switch
statement. The switch statement is used to conditionally perform
statements based on an integer expression.
- Let us consider the following example. Using the switch statement, it
displays the name of the month, based on the value of month variable.
public class SwitchExample1
{
public static void main(String[] args)
{
int month = 11;
switch (month)
{
case 1: [Link]("January"); break;
case 2: [Link]("February"); break;
case 3: [Link]("March"); break;
case 4: [Link]("April"); break;
case 5: [Link]("May"); break;
case 6: [Link]("June"); break;
case 7: [Link]("July"); break;
case 8: [Link]("August"); break;
case 9: [Link]("September"); break;
case 10: [Link]("October"); break;
case 11: [Link]("November"); break;
case 12: [Link]("December"); break;
}
}
}
The switch statement evaluates its expression and executes the
appropriate case statement. Thus, in this case it evaluates the value of
month and the output of the program is: November.
- It is important to notice the use of the break statement after each case
in the switch statement. Each break statement terminates the

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

enclosing switch statement, and the flow of control continues with the
first statement following the switch block.
- The break statements are necessary because without them, the case
statements fall through. That is, without an explicit break, control will
flow sequentially through subsequent case statements.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Block 2

Unit 1 – Class and Objects


Passing objects as parameters
- Pass-by-value means that when you call a method, a copy of the value
of each of the actual parameter is passed to the method. You can
change that copy inside the method, but this will have no effect on the
actual parameters.
- Everything in Java except constant value, is passed by reference.
- The values of variables are always primitives or references, never
objects.
- In Java, we can pass a reference of the object to the formal parameter.
If any changes to the local object that take place inside the method will
modify the object that was passed to it as argument. Due to this
reason objects passing as parameter in Java are referred to as passing
by reference.
- In the program given below object of the class Marks is passed to
method Set_Grade, in which instance variable grade of the object
passed is assigned some value. This reflects that the object itself is
modified.
class Marks

String name;

int percentage;

String grade;

Marks(String n, int m)

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

name = n;

percentage = m;

void Display()

[Link]("Student Name :"+name);

[Link]("Percentage Marks:"+percentage);

[Link]("Grade : "+grade);

[Link]("*****************************");

class Object_Pass

public static void main(String[] args){

Marks ob1 = new Marks("Naveen",75);

Marks ob2 = new Marks("Neeraj",45);

Set_Grade(ob1);

[Link]("*****************************");

[Link]();

Set_Grade(ob2);

[Link]();

static void Set_Grade(Marks m)

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

if ([Link] >= 60)

[Link] ="A";

else if( [Link] >=40)

[Link] = "B";

else

[Link] = "F";

Output of this program is:


*****************************

Student Name :Naveen

Percentage Marks:75

Grade : A

*****************************

Student Name :Neeraj

Percentage Marks:45

Grade : B

*****************************

Static Methods
- Methods and variables that are not declared as static are known as
instance methods and instance variables or in other words you can say
that they belong to objects of the class. To refer to instance methods
and variables, you must instantiate the class first then, obtain the
methods and variables from the instance.
- A static method is a characteristic of a class, not of the objects it has
created.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- Static variables and methods are also known as class variables or class
methods since each class variable and each class method occurs once
per class. Instance methods and variables occur once per instance of a
class or you can say every object is having its own copy of instance
variables.
- One very important point to note here is that a program can execute a
static method without creating an object of the class. All other
methods must be invoked through an object, and, therefore an object
must exist before they can be used.
- Every Java application program has one main() method. This method is
always static because Java starts execution from this main() method,
and at that time no object is created.

Method Overloading
- Sometimes two or more methods which are very similar in nature are
required.
- For example, you can take methods Area_S and Area_R in the given
program.
class Test
{
int Area_S( int i)
{
return i*i;
}
int Area_R(int a,int b)
{
return a*b;
}
}
Both the methods are finding area but the argument passed to them
and their implementation is different.
- All the methods of similar kinds in a class can have the same name, but
all the methods will have different prototypes. This concept is known
as method overloading.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- By matching the type and order of arguments passed to methods, the


exact method that should execute is resolved.
- Sometimes overloaded methods may have different return types, the
return type alone is not sufficient to differentiate two overloaded
methods.
- In the program given below, the area() method is overloaded.
class Test
{
int Area( int i)
{
return i*i;
}
int Area(int a,int b)
{
return a*b;
}
}
class Area_Overload
{
public static void main(String args[])
{
Test t = new Test();
int area;
area = [Link](5);
[Link]("Area of Square is : "+area);
area = [Link](5,4);
[Link]("Area of Rectangle is : "+area);
}
}
Output of the program:
Area of Square is: 25
Area of Rectangle is: 20

finalize() method
- Sometimes it is required to take independent resources from some
object before the garbage collector takes the object. To perform this
operation, a method named finalize () is used.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- finalize () is called by the garbage collector when it detemines no more


references to the object exist.
- In other words, the intent for calling the finalize() method to release
system resources such as open files or open sockets before object
getts collected by garbage collector.
- Your class can provide for its finalization simply by defining and
implementing a finalize() method in your class. Your finalize() method
must be declared as follows:
protected void finalize () throws throwable
- Example:
This class opens a file when it’s constructed:
class OpenAFile
{
FileInputStream aFile = null;
OpenAFile(String filename)
{
try
{
a File = new FileInputStream(filename);
}
catch ([Link] e)
{
[Link]("Could not open file " + filename);
}
}
}
To avoid accidental modification or other related problem the
OpenAFile class should close the file when it is finalized.
Implementation of finalize () method for the OpenAFile class:
protected void finalize () throws throwable
{
if (aFile != null)
{
a [Link]();
a File = null;
}
}

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Creating Objects
- An object of a class can be created by performing these two steps.
o 1. Declare an object of class.
o 2. Acquire space for and bind it to object.
- In the first step only a reference to a variable is created, no actual
object’s exists.
- For actual existence of an object memory is needed. That is acquired
by using new operator.
- The new operator in Java dynamically allocates memory for an object
returns a reference to object and binds the reference with the object.
- Here reference to object means address of object. So it is essential in
Java that all the objects must be dynamically allocated.
- Declaring Student object
o Step 1: Student student1; // declaring reference to object
o Step 2: student1 = new Student( ); // allocating memory
- In normal practice these two steps are written in a single statement as:
Student student1 = new Student( );

Constructors
- A constructor initializes object with its creation. It has the same name
as the name of its class.
- Once a constructor is defined, it is automatically called immediately
when the memory is allocated before the new operation completes.
- Constructor does not have any return type, its implicit return type is
class object.
- You can see constructor as a class type. Its job is to initialize the
instance variables of an object, so that the created object is usable just
after creation.
- Constructors can be defined in two ways.
o First , a constructor may not have parameter. This type of
constructor is known as non-parameterized constructor.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

class Point
{
int x;
int y;
Point()
{
x = 2;
y = 4;
}
}
o The second, a constructor may take parameters. This type of
constructor is known as parameterized constructor.
class Point
{
int x;
int y;
Point(int a, int b)
{
x = a;
y = b;
}
}

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 2 – Inheritance and Polymorphism


Abstract Classes
- A superclass has common features that are shared by subclasses.
- In some cases you will find that superclass cannot have any instance
(object) and such classes are called abstract classes.
- Abstract classes usually contain abstract methods. Abstract method is
a method signature (declaration) without implementation. Basically
these abstract methods provide a common interface to different
derived classes.
- Abstract classes are generally used to provide common interface to
derived classes.
- The superclass contains elements and properties common to all of the
subclasses. Often, the superclass will be set up as an abstract class,
which does not allow objects of its prototype to be created.
- In this case only objects of the subclass are created.
- To do this the reserved word abstract is included (prefixed) in the class
definition.
- In case attempts are made to create objects of abstract classes, the
compiler doesn’t allow compilation and generates an error message.
- If you are inheriting in a new class from an abstract class and you want
to create objects of this new class, you must provide definitions to all
the abstract methods in the superclass.
- If all the abstract methods of super class are not defined in this new
class this class also will become abstract.
- For example, the class given below is an abstract class.
public abstract class Player // class is abstract
{
private String name;
public Player(String vname)
{

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

name=vname;
}
public String getName() // regular method
{
return (name);
}
public abstract void Play();
// abstract method: no implementation
}

Public Access Specifier


- This is the easiest access specifier.
- Any class, in any package, can access the public members of a class.
- Declare public members only if you want to provide access to a
member by every class.
- In other words you can say if access to a member by outsider cannot
produce undesirable results, then the member may be declared public.
- To declare a public member, use the keyword public.

Private Access Specifier


- Private is the most restrictive access level.
- A private member is accessible only to the class in which it is defined.
- You should use this access to declare members that you are going to
use within the class only.
- This includes variables that contain information which if accessed by
an outsider could put the object in an inconsistent state, or methods, if
invoked by an outsider, could jeopardize the state of the object or the
program in which it is running.
- You can see private members like secrets you never tell anybody.
- To declare a private member, use the private keyword in its
declaration.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Method Overriding
- A subclass extending the parent class has access to all the non-private
data members and methods its parent class. Most of the time the
purpose of inheriting properties from the parent class and adding new
methods is to extend the behaviour of the parent class. However,
sometimes, it is required to modify the behaviour of parent class. To
modify the behaviour of the parent class overriding is used.
- Some important points that must be taken care while overriding a
method:
o i. An overriding method (largely) replaces the method it
overrides.
o ii. Each method in a parent class can be overridden at most once
in any one of the subclass.
o iii. Overriding methods must have exactly the same argument
lists, both in type and in order.
o iv. An overriding method must have exactly the same return type
as the method it overrides.
o v. Overriding is associated with inheritance.
- The following example program shows how member function area () of
the class Figure is overridden in subclasses Rectangle and Square.
class Figure
{
double sidea;
double sideb;
Figure(double a, double b)
{
sidea = a;
sideb = b;
}
Figure(double a)
{
sidea = a;
sideb = a;
}

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

double area( )
{
[Link]("Area inside figure is Undefined.");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle( double a , double b)
{
super ( a, b);
}
double area ( )
{
[Link]("The Area of Rectangle:");
return sidea*sideb;
}
}
class Squre extends Figure
{
Squre( double a )
{
super (a);
}
double area( )
{
[Link]("Area of Squre: ");
return sidea*sidea;
}
}
class Area_Overrid
{
public static void main(String[] args)
{
Figure f = new Figure(20.9, 67.9);
Rectangle r = new Rectangle( 34.2, 56.3);
Squre s = new Squre( 23.1);
[Link]("***** Welcome to Override Demo ******");
[Link]();
[Link](" "+[Link]());
[Link](" "+[Link]());

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

}
}
Output:
***** Welcome to Override Demo ******
Area inside figure is Undefined.
The Area of Rectangle:
1925.46
Area of Squre:
533.61

Final Keyword
- In Java programming the final key word is used for three purposes:
- i. Making constants
- ii. Preventing method to be overridden
- iii. Preventing a class to be inherited
- The final keyword is a way of marking a variable as "read-only". Its
value is set once and then cannot be changed. For example, if year is
declared as
final int year = 2005;
Variable year will be containing value 2005 and cannot take any other
value after words.
- The final keyword can also be applied to methods, with similar
semantics: i.e. the definition will not change.
- You cannot override a final method in subclasses, this means the
definition is the “final” one.
- You should define a method final when you are concerned that a
subclass may accidentally or deliberately redefine the method
(override).
- If you want to prevent a class to be inherited, apply the final keyword
to an entire class definition. For example, if you want to prevent class
Personal to be inherited further, define it as follows:
final class Personal
{
// Data members

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

//Member functions
}
Now if you try to inherit from class Personal
class Sub_Personal extends Personal
It will be illegal. You cannot derive from Personal class since it is a final
class.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 3 – Packages and Interface


Interfaces
- Interfaces in Java look similar to classes but they don’t have instance
variables and provide methods without implementation. It means that
every method in the interface is strictly a declaration.
- All methods and fields of an interface must be public.
- Interfaces are used to provide methods to be implemented by
class(es).
- A class implements an interface using implements clause. If a class is
implementing an interface it has to define all the methods given in
that interface.
- More than one interface can be implemented in a single class.
- Basically an interface is used to define a protocol of behavior that can
be implemented by any class anywhere in the class hierarchy.
- As Java does not support multiple inheritance, interfaces are seen as
the alternative of multiple inheritance, because of the feature that
multiple interfaces can be implemented by a class.

Implementing Interfaces
- To declare a class that implements an interface, include an implements
clause in the class declaration.
- Your class can implement more than one interface (the Java platform
supports multiple interface inheritance), so the implements keyword is
followed by a comma-separated list of the interfaces implemented by
the class.
- Remember that when a class implements an interface, it is essentially
signing a contract with the interface that the class must provide
method implementations for all of the methods declared in the
interface and its superinterfaces.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- If a class does not implement all the methods declared in the interface
the class must be declared abstract.
- The method signature (the name and the number and type of
arguments) for the method in the class must match the method
signature as it appears in the interface.
- Example of interface Calculate and implement it in a class:
public interface Calculate

public double calculateInterest();

In the following program interface Calculate is implemented by SavingAccount class.

//program

interface Calculate

public double calculateInterest();

class SavingAccount implements Calculate

int Ac_No;

int Amount;

double Rate_of_Int;

int time;

SavingAccount( int a , double b, int c, int d)

Ac_No = a;

Rate_of_Int = b;

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

time = c;

Amount = d;

void DisplayInt()

[Link]("Interest for Account No. "+Ac_No+" is Rs "+calculateInterest());

public double calculateInterest( )

return( Amount*Rate_of_Int*time/100);

public class TestIterface

public static void main( String args[])

SavingAccount S = new SavingAccount( 1010,4.5,5,5000);

[Link]();

Output:

Interest for Account No. 1010 is Rs 1125.0.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Package
- A package is a collection of related classes and interfaces providing
access protection and namespace management.
- Java programmer creates packages to partition classes.
- Partitioning of classes helps in managing the program. The package
statement is used to define space to store classes.
- In Java you can write your own package. Writing packages is just like
writing any other Java program. You just have to take care of some
points when writing packages. These are given below.
o There must be not more than one public class per file.
o All files in the package must be named name_of_class.Java
where name_of_class is the name of the single public class in
the file.
o The very first statement in each file in the package, before any
import statements or anything put the statement package
myPackageName;

CLASSPATH
- CLASSPATH is an environment variable of system. The setting of this
variable is used to provide the root of any package hierarchy to Java
compiler.
- Suppose you create a package named MyPak. It will be stored in
MyPak directory.
- Now let us say class named MyClass is in [Link] will store
[Link] in MyPak directory . To complie [Link] you have to
make
- MyPak as current directory and [Link] will be stored in MyPak.
- You cannot run [Link] file using Java interpreter from any
directory because [Link] is in package MyPak, so during
execution you will to refer to package hierarchy.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- For this purpose you have to set CLASSPATH variable for setting the top
of the hierarchy. Once you set CLASSPATH for MyPak , it can be used
from any directory.
- For example, if /home/MyDir/Classes is in your CLASSPATH and your
package is called MyPak1, then you would make a directory called
MyPak in /home/MyDir/Classes and then put all the .class files in the
package in /home/MyDir/Classes/MyPak1.

Interfaces and Abstract Class


- A class can implement more than one interface, but an abstract class
can only subclass one class.
- An abstract class can have non-abstract methods. All methods of an
interface are implicitly (or explicitly) abstract.
- An abstract class can declare instance variables; an interface cannot.
- An abstract class can have a user-defined constructor; an interface has
no constructors.
- Every method of an interface is implicitly (or explicitly) public. An
abstract class can have non-public methods.

import keyword
- import is a Java keyword used to include a particular package or to
include specific classes or interfaces of any package.
- import keyword is used to:
o either include whole package by statement
import PackageName.*;
o or to import specific class or interface by statement
import [Link](or InterfaceName) .*;

Unit 4 – Exceptions Handling

throws keyword
- If you don't want to explicitly implement exception handling, you can
declare that your method throws an exception.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- This passes the responsibility to handle this exception to the method


that invokes your method. This is done with the throws keyword.
- Example:
public static void copy (InputStream in, OutputStream out) throws IOException
{
byte[] Mybuf = new byte[256];
while (true)
{
int bytesRead = [Link](Mybuf);
if (bytesRead == -1) break;
[Link](Mybuf, 0, bytesRead);
}
}
In this code snippet copy method throws IOException, and now the
method that invokes copy method is responsible for handling
IOException.

Exception
- An exceptional condition is considered as a problem, which stops
program execution from continuation from the point of occurrence of
it. Exception stops you from continuing because of lack of information
to deal with the exception condition. In other words it is not known
what to do in specific conditions.
- If the system does not provide it you would have to write your own
routine to test for possible errors. You need to write a special code to
catch exceptions before they cause an error.
- If you attempt in a Java program to carry out an illegal operation, it
does not necessarily halt processing at that point. In most cases, the
JVM sees for the possibility of catching the problem and recovering
from it.
- If the problems are such which can be caught and recovery can be
provided, then we say the problems are not fatal, and for this the term
exception is used rather than error.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Causes of Exception
- Exception arises at runtime due to some abnormal condition in
program for example when a method. E.g. division encounters an
abnormal condition that it can't handle itself, i.e. “divide by zero,” then
this method may throw an exception.
- If a program written in Java does not follow the rule of Java language
or violates the Java execution environment, constraints exception may
occur. There may be a manually generated exception to pass on some
error reports to some calling certain methods.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Block 3

Unit 1 – Multithreaded Programming


Notify and notifyAll
- notify( ): Wakes up a single thread that is waiting on this object’s
monitor.
- notifyAll( ): Wakes up all threads that are waiting on this object’s
monitor, the highest priority Thread will be run first.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 2 – IO in Java

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 3 – Strings and Characters


String Class Constructors
- public String(): Used to create a String object that represents an empty
character sequence.
- public String(String value): Used to create a String object that
represents the same sequence of characters as the argument; in other
words, the newly created string is a copy of the string passed as an
argument.
- public String(char value[]): New object of string is created using the
sequence of characters currently contained in the character array
argument.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 4 – Exploring Java IO


Serialization
- You can read and write text, but with Java you can also read and write
objects to files. You can say that object I/O is serialization where you
read/write state of an object to a byte stream.
- It plays an important role when you are interested in saving the state
of objects in your program to a persistent storage area like file. You can
de-serialize to restore these objects, whenever needed.
- Java efficiently implements serialization but we have to follow different
conditions; we can call them “conditions for serializability”.
o If you want to serialize an object, the class of the object must be
declared as public, and must implement serialization.
o The class also must have a no argument constructor and all fields
of class must be serializable.
- Java gives you the facility of serialization and deserialization to save
the state of objects.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Block 4

Unit 1 – Applets
Applets
- Java Applets are essentially Java programs that run within a web page.
- Applet programs are Java classes that extend the [Link]
class and are embedded by reference within a HTML page.
- You can observe that when Applets are combined with HTML, they can
make an interface more dynamic and powerful than with HTML alone.
- While some Applets do nothing more than scroll text or play
animations, but by incorporating these basic features in web pages you
can make them dynamic.
- These dynamic web pages can be used in an enterprise application to
view or manipulate data coming from some source on the server.
- For example, an Applet may be used to browse and modify records in a
database or control runtime aspects of some other application running
on the server.
- Applets differ from Java applications in the way that they are not
allowed to access certain resources on the local computer, such as files
and serial devices (modems, printers, etc.), and are prohibited from
communicating with most other computers across a network.
- The common rule is that an Applet can only make an Internet
connection to the computer from which the Applet was sent.

Events
- In application environments, program logic doesn’t flow from the top
to the bottom of the program as it does in most procedural code.
- Rather, the operating system collects events and the program responds
to them.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- These events may be mouse clicks, key presses, network data arriving
on the Ethernet port, or any from about two dozen other possibilities.
- The operating system looks at each event, determines what program it
was intended for, and places the event in the appropriate program’s
event queue.
- Every application program has an event loop.
- This is just a while loop which loops continuously. On every pass
through the loop the application retrieves the next event from its
event queue and responds accordingly.

Applet LifeCycle
- 1. The browser reads the HTML page and finds any <APPLET> tags.
- 2. The browser parses the <APPLET> tag to find the CODE and possibly
CODEBASE attribute.
- 3. The browser downloads the Class file for the Applet from the URL
(Uniform Resource Locator) found in the last step.
- 4. The browser converts the raw bytes downloaded into a Java class,
that is a [Link] object.
- 5. The browser instantiates the Applet class to form an Applet object.
This requires the Applet to have a no-args constructor.
- 6. The browser calls the Applet’s init () method.
- 7. The browser calls the Applet’s start () method.
- 8. While the Applet is running, the browser passes all the events
intended for the Applet, like mouse clicks, key presses, etc. to the
Applet’s handle Event() method.
- 9. The default method paint() in Applets just draw messages or
graphics (such as lines, ovals etc.) on the screen. Update events are
used to tell the Applet that it needs to repaint itself.
- 10. The browser calls the Applet’s stop () method.
- 11. The browser calls the Applet’s destroy () method.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 2 – Graphic and User Interface


Container
- Container object is derived from the [Link] class and is
one of (or inherited from) three primary classes: [Link],
[Link], [Link].
- The Window class represents a standalone window (either an
application window in the form of a [Link], or a dialog box in
the form of a [Link]).
- The [Link] class is not a standalone window by itself; instead,
it acts as a background container for all other components on a form.
For instance, the [Link] class is a direct descendant of
[Link].
- The three steps common for all Java GUI applications are:
o 1. Creation of a container
o 2. Layout of GUI components.
o 3. Handling of events.
- The Container class contains the setLayout() method so that you can
set the default LayoutManager to be used by your GUI.
- To actually add components to the container, you can use the
container’s add() method:
Panel p = new [Link]();
Button b = new [Link](“OK”);
[Link](b);
- A JPanel is a Container, which means that it can contain other
components. GUI design in Java relies on a layered approach where
each layer uses an appropriate layout manager.

Layout Manager
- When you add a component to an applet or a container, the container
uses its layout manager to decide where to put the component.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- Different LayoutManager classes use different rules to place


components.
- [Link] is an interface. Five classes in the java
packages implement it:
o FlowLayout
o BorderLayout
o CardLayout
o GridLayout
o GridBagLayout
o plus [Link]

Difference between swing and awt


- Swing has lightweight components and does not write itself to the
screen, but redirects it to the component it builds on. On the other
hand AWT are heavyweight and have their own view port, which sends
the output to the screen. Heavyweight components also have their
own z-ordering (look and feel) dependent on the machine on which
the program is running.
- This is the reason why you can’t combine AWT and Swing in the same
container. If you do, AWT will always be drawn on top of the Swing
components.
- Another difference is that Swing is pure Java, and therefore platform
independent. Swing looks identical on all platforms, while AWT looks
different on different platforms.
- See, basically Swing provides a rich set of GUI components; features
include model-UI separation and a plug able look and feel. Actually you
can make your GUI also with AWT but with Swing you can make it
more user-friendly and interactive. Swing components make programs
efficient.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 3 – Networking Features

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

Unit 4 – Advance Java


Java Beans
- Java Beans are reusable software component model which allow a
great flexibility and addition of features to the existing piece of
software.
- You will find it very interesting and useful to use them by linking
together the components to create applets or even new beans for
reuse by others.
- Graphical programming and design environments often called builder
tools give a good visual support to bean programmers. The builder tool
does all the work of associating of various components together.
- A “JavaBeans-enabled” builder tool examines the Bean’s patterns,
discerns its features, and exposes those features for visual
manipulation.
- A builder tool maintains Beans in a palette or toolbox. You can select a
Bean from the toolbox, drop it into a form, modify its appearance and
behaviour, define its interaction with other Beans, and compose it into
applets, application, or new Bean. All this can be done without writing
a line of code.

Features of JavaBeans
- Individual Java Beans will vary in functionality, but most share certain
common defining features.
- Support for introspection allowing a builder tool to analyze how a
bean works.
- Support for customization allowing a user to alter the appearance and
behaviour of a bean.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- Support for events allowing beans to fire events, and informing builder
tools about both the events they can fire and the events they can
handle.
- Support for properties allowing beans to be manipulated
programmatically, as well as to support the customization mentioned
above.
- Support for allowing beans that have been customized in an
application builder to have their state saved and restored. Typically
persistence is used with an application builder’s save and load menu
commands to restore any work that has gone into constructing an
application.

RMI
- Java provides RMI (Remote Method Invocation), which is "a
mechanism that allows one to invoke a method on an object that
exists in another address space. The other address space could be on
the same machine or a different one. The RMI mechanism is basically
an object-oriented RPC mechanism."
- RPC (Remote Procedure Call) organizes the types of messages which
an application can receive in the form of functions. Basically it is a
management of streams of data transmission.
- RMI applications often comprised two separate programs: a server and
a client.
- A typical server application creates some remote objects, makes
references to them accessible, and waits for clients to invoke methods
on these remote objects. A typical client application gets a remote
reference to one or more remote objects in the server and then
invokes methods on them.
- RMI provides the mechanism by which the server and the client
communicate and pass information back and forth. Such an application
is sometimes referred to as a distributed object application.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- There are three processes that participate in developing applications


based on remote method invocation.
o The Client is the process that is invoking a method on a remote
object.
o The Server is the process that owns the remote object. The
remote object is an ordinary object in the address space of the
server process.
o The Object Registry is a name server that relates objects with
names. Objects are registered with the Object Registry. Once an
object has been registered, one can use the Object Registry to
obtain access to a remote object using the name of the object.

Servlets
- Java has utility known as servlets for server side-programming.
- A servlet is a class of Java programming language used to extend the
capabilities of servers that host applications accessed via a request-
response programming model.
- Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by web servers.
- Java Servlet technology also defines HTTP-specific servlet classes. The
[Link] and [Link] packages provide interfaces and
classes for writing servlets.
- All servlets must implement the Servlet interface, which defines life-
cycle methods.
- When implementing a generic service, you can use or extend the
GenericServlet class provided with the Java Servlet API. The
HttpServlet class provides methods, such as doGet and doPost, for
handling HTTP-specific services.

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

JDBC
- During programming you may need to interact with database to solve
your problem. Java provides JDBC to connect to databases and work
with it.
- Using standard library routines, you can open a connection to the
database.
- Basically JDBC allows the integration of SQL calls into a general
programming environment by providing library routines, which
interface with the database.
- In particular, Java’s JDBC has a rich collection of routines which makes
such an interface extremely simple and intuitive.

JDBC Connection
Load the vendor specific driver:
- For example, an Oracle driver is loaded using the following code
snippet:
[Link]("[Link]")

Make the connection:


- Once the driver is loaded and ready for a connection to be made, you
may create an instance of a Connection object using:
Connection con = [Link](url, username, password);

Creating JDBC Statements:


- An active connection is needed to create a Statement object. The
following code is a snippet, using our Connection object con
Statement statmnt = [Link]();

Creating JDBC PreparedStatement:

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])


lOMoARcPSD|37613978

- PreparedStatements are also created with a Connection method. The


following code shows how to create a parameterized SQL statement
with three input parameters:
PreparedStatement prepareUpdatePrice =
[Link]( "UPDATE Employee SET emp_address =?
WHERE emp_code =“1001” AND emp_name =?");
- You can see two ? symbol in the above PreparedStatement
prepareUpdatePrice. This means that you have to provide values for
two variables emp_address and emp_name in PreparedStatement
before you execute it. Calling one of the setXXX methods defined in
the class PreparedStatement can provide values. Most often used
methods are setInt, setFloat, setDouble, setString, etc. You can set
these values before each execution of the prepared statement. You can
write something like:
-
[Link](1, 3);
[Link](2, "Renuka");
[Link](3, "101, Sector-8,Vasundhara, M.P");

Download Link: [Link]


usp=sharing&ouid=101687282440582388863&rtpof=true&sd=true

Downloaded by MR PIYUSH YT (piyushkumat76@[Link])

You might also like