Vvvimp BSC Java Onetime
Vvvimp BSC Java Onetime
The major objective of Object Oriented Programming (OOP) is to dominate some of the defect
encountered in the Procedure Oriented Programming (POP). OOP treats data as critical elements which
doesn’t move freely around the system. It ties data more closely to the functions that operate it and
protects it from accidental modifications by other functions.
In OOP, the problem is decomposed into number of entities called Objects. And then built data
and functions (Known as methods in java) around there entities. The diagrammatic representation of
object creation is as follows.
Method Method
Data
Method Method
Object - 1 Object - 2
Data Data
Methods Methods
Data
Methods
Object - 3
1
RAO’S DEGREE COLLEGE : : NELLORE
Object Oriented Programming offers several benefits to both programmer designer and user. It
contributes to the solution of many problems, associated with the development of better software
products and also provides user maintenance cost. The basic concepts of OOP are as follows.
- Class
- Object
- Data Abstraction
- Data Encapsulation
- Inheritance
- Polymorphism
- Dynamic Binding
- Message Passing
Class:- A class mechanism binds together the data and action. It allows the data to be hidden if
necessary from the external users. For Ex. In case of student class all objects have similar attributes like
student name, student number and marks. Actions like Total () and Average () etc..
Object: Objects are primary runtime entities in object oriented system. It can be anything that exits in
the world. It is a composition of properties and actions. Ex. Student, Chair, Pen etc.
Data Abstraction:- Abstraction means data hiding. The technique of creating new data type using
encapsulating items that is applied to an application. The data types that are used in data abstraction
those are called as abstract data types (ADT).
Data Encapsulation:- The grouping of data and functions into a single component is known as
encapsulation. Here the data is not accessible by outside functions.
Inheritance:- Inheritance is the process by which objects of one class acquire the properties of objects of
another class. It supports the concepts of hierarchical classification. In OOP, the concept of inheritance
provides the idea of reusability. The following example shows the inheritance hierarchy.
Bird
Polymorphism:-It is another important OOP concept. Poly means many or several, morphism means
forms. It is an ability to take more than one form. Polymorphism plays an important role in allowing the
objects having different internal structures to share the external interface. The following example shows
the polymorphism hierarchy.
2
RAO’S DEGREE COLLEGE : : NELLORE
Shape
Dynamic Binding:- Binding refers to the linking of procedure-call to the code to be executed in response
to that call. Binding means that the code associated with a given procedure –call is not known until the
time of the call at run time.
Message Passing:- In object Oriented program concepts of set of objects that communicate with each
other. The following this to done thru Message passing.
OOP offers several benefits to both program designer and users. It contributes to the solution of
many problems, associated with the development of better software product and also provides user
maintenance cost.
a) Through inheritance, we can eliminate the redundant code and extend the use of existing classes.
b) We can build standard working modules that communicate with one another. This leads less
development time and higher productivity.
c) It is possible to have multiple objects to co-exist without any interference.
d) The data centered design approach enables to capture more details of a model in an implementable
form.
e) Object oriented systems can be easily upgraded from small to large systems.
f) Message passing technique for communication between objects.
g) Software complexity can be easily manages.
3
RAO’S DEGREE COLLEGE : : NELLORE
The inventor of java is james Gosling and it is become the familiar language for general purpose
and stand alone applications. The features of java are as follows.
Compiled and interpreted:- Java combines both compiled and interpreted, thus making java a two stage
system. First the java compiler translates source code into byte code instructions. Then the java
interpreter generates byte code into machine code that’s why java is a both compiled and interpreted
language.
Plat-form independent and portable:- The most significant feature of java over other languages is
portability. Java programs can be easily moved from one computer system to another, anywhere and
anytime.
Object Oriented:- Java is pure object oriented language. Almost everything in java is an object. Almost
everything in java is an object. All programs are resides within objects and classes.
Robust and secure:- java is a robust language. It performs many safe guards to reliable code. Security
becomes an important issue for a language that is used for programming on internet.
Distributed:- Java is designed as distributed language for creating applications on network. It has the
ability to share both data and programs and it also familiar language.
Small, simple and familiar:- Java is a small and simple language. Many features of C and C++ that are
either redundant or sources of unreliable code are not part of java.
Multithreaded:- Multithreaded means handling multiple tasks simultaneously this means that java
supports multi threaded programs. The programmer need not wait for the application to finish one task
before beginning another.
High Performance:- Java performance is impressive for an interpreted language mainly due to the use of
intermediate byte code.
Dynamic and extendible:- Java is a dynamic language. It is capable dynamically linking in new class
libraries, methods and objects. Java supports functions written in other languages such as C and C++.
4
RAO’S DEGREE COLLEGE : : NELLORE
Java program may contain many classes of which only one class defines a main method. It
contains data members and methods that operate on the data members of the class. A java program
can contain one or more section. They are:
Documentation Section
Package Statements
Import Statements
Interface Statements
Class Section
Documentation Section:- The documentation section consists of comments given name of the
programmer, the author and date details. They are:
Java also use third style of comments i.e. /** ……. */ known as documentation comment.
Package Section:- the first statement in java file is package statement. This statement declares a
package name and informs the compilers that the class defined here belong to the package.
Ex : package Student;
Import statement:- The next statement after java package is import statement, it is similar to # include
statement in C.
This statement instructs the interpreter to load the test class contained in package student.
Interface statement:- An interface is like a class but it includes a group of method declarations. That is
an optional section and is used only when we wish to implement multiple inheritance feature in java
program.
5
RAO’S DEGREE COLLEGE : : NELLORE
Class Definition:- A java program may contain multiple class definitions. Class are the primary and
essential elements of a program.
Main method class:- Every java program requires a main method as its starting point. The main method
creates objects of various classes and establishes communication between them.
Java Virtual Machine is the heart of entire java program execution process. It is responsible for taking
the class file and converting each byte code instruction into machine language instruction that can be
executed by the microprocessor. The following diagram represents the process of JVM.
Command line arguments are the parameters, which are passed to the application program at
the time of calling it for execution. Through this feature, we can access any elements and used them in
the program as our wish. Generally we write the java programs that can receive and use the arguments
provided in the command line for reading the command line arguments. We write the java main method
like the following.
In the above definition args[] is declared as array of string. Any arguments provided in the
command line (at the time of execution) are passed to the array args[] as its elements. Then access and
used them in the program the following program illustrate the process of command line argument
The data type specifies what type of data is stored and manipulated in the computer
system. Data type specifies a collection of values and a set of operations to be applied on those
values. It also specifies the memory usage by a memory variable.
Data Types
6
Integer Floating-point Character Boolean
RAO’S DEGREE COLLEGE : : NELLORE
Integer types:- Integer data type are used to store whole numbers only. In java the integer data
type support four types of data types. They are shown in the following diagram.
. Integer
Byte Long
Short int
byte 1
short 2 bytes
int 4 bytes
long 8 bytes
Floating Point types:- floating point data types are used to store floating point data like real
numbers or fractional values. In java two types of floating point types which are shown in the
following diagram.
Floating-point
float double
The keywords ‘float’ and ‘double’ are used to declare float type variables. We can also
use qualifiers to declare float type variables. The following table shows float data types and their
range of values:
7
RAO’S DEGREE COLLEGE : : NELLORE
Character Family:
The keyword ‘char’ is used to declare character data type variables. It contains any
alphabet, digit (or) special character. It occupies 2 bytes of memory space.
Boolean type:
Boolean type is used to store only true and false values. It occupies 1 byte of memory space.
The default value of Boolean variable is false.
The scope of variable represents, how long a variable is stored into a computer’s
memory. The scope of variable is determined by the way of it has been declared. In java, the
variables scope is classified into the following types. They are:
Instance variables
Class variables
Local variables
Instance variables:- instance variables are declared inside the class. These variables are created
when the objects are created and they are associated with the object.
Class variables:- class variables are also declared inside the class but they are global to the class
and belongs to the entire set of objects that class creates. A separate memory location is created
for each class variables for storing and accessing the value to the entire class.
Local variables:- the local variables are declared inside the method only. They are accessed only
inside the method and cannot be accessed outside the method. In java, local variables can also be
declared inside of program blocks that are defined between ‘{‘ and ‘}’. These variables are
visible to the program only from the beginning of its program block and to the end of the
program.
The following program is shown the scope of variables.
void readData()
{
...............
int z; Local variables
..............
}
void printData()
{
............
............
}
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Increment and decrement operators
5. Assignment Operators
6. Conditional operator
7. Bitwise operators
8. Special operators
1. Arithmetic operators:
Arithmetic operators are used to perform arithmetic calculations. The following are the
various arithmetic operators.
Operato Meaning
r
+ Addition
– Subtraction
* Multiplication
9
RAO’S DEGREE COLLEGE : : NELLORE
/ Division
2. Relational Operators:
The relational operators are used to compare two values and to give either true (1) or
false (0) result. The following are the relational operators.
Operato Meaning
r
== Equal to
!= Not equal to
3. Logical Operators:
These are used to combine two or more conditions and give the result either true or false.
They are used to form compound conditions.
Operator Meaning
¦¦ Logical OR
! Logical NOT
Increment and decrement operators are used to increment and decrements the
value of an operand. It is incremented and decremented only 1 value at a time.
10
RAO’S DEGREE COLLEGE : : NELLORE
5. Assignment Operators: The assignment operator is used to assign the value to the variable.
The operator ‘=’ is used to assign the value of the variable. The general form of assignment
operator is as follows.
Value
variable
Variable = constant
expression
In the above syntax, any one of the left side value is assigned to the variable.
The conditional operators (? :) are used to execute the statements which are depending on the
given condition. The general form of conditional operator is as follows.
Syntax:
Conditional expression ? expression-1 : expression-2;
In the above syntax, the conditional expression is executed first. If the result is true,
expression-1 is executed and it is returned as the value of the conditional expression. Otherwise,
expression-2 is executed and its value is returned.
Ex:
7. Bitwise Operators: The bitwise operators are used to perform the operation on bits insteadof
decimal values. The bitwise operators which are supported by java are as follows.
Operator Meaning
& AND
| OR
^ XOR
~ One’s complement
<< Left shift
>> Right shift
>>> Right shift with zero fill
8.Special Operators: The operator ‘.’ (dot) and instanceof are used as special operators.
11
RAO’S DEGREE COLLEGE : : NELLORE
UNIT – II
if statement:-
The ‘if’ statement is a conditional execution statement that executes the specified set of
instructions based on the condition.
Syntax:
if (condition) statement-block ;
To specify more than one statement in a statement-block, they must be enclosed within a
pair of flower braces ({}).
Examples:
1. if (avg >= 75) System.out.println(“grade is distinction”);
2. if (a < 0) a++;
’if…else’ statement:
It is also conditional execution statement that executes the statements based on the
condition. If the condition is true then it executes one group of instructions otherwise it executes
another group of statements.
Syntax:
if (condition)
statement-block1 ;
else
statement-block2 ;
Switch Statement:
The ‘switch’ statement is a multiple branching statement. It can be used to make a decision
from the number of choices. It is an extension of ‘if…else’ statement.
12
RAO’S DEGREE COLLEGE : : NELLORE
Syntax:
switch (op)
{
case V1 : statement-block1;
[break;]
case V2 : statement-block2;
[break;]
: :
: :
case Vn : statement-block-n;
[break;]
[default : statement-block-d;]
}
In 'Java' language, there are 3 types of repetitive control structures. They are
1. While structure
2. Do…while structure
3. For structure
While Statement (while loop):
While is one of the looping statement. This statement is used to execute a statement or
group of statements repeatedly as long as the specified condition is satisfied. It is an entry
control loop statement. The syntax of while statement is as follows:
Syntax:
while (condition)
{
statement-block;
}
13
RAO’S DEGREE COLLEGE : : NELLORE
do…while Statement:
Do..While is one of the looping statement. This statement is used to execute a statement
or group of statements repeatedly as long as the specified condition is satisfied. It is an exit
control loop structure. The do…while structure executes at least one time even initially the
condition is false.
Syntax:
do
{
statement-block;
} while (condition) ;
‘for’ Statement:
For is one of the looping statements. This statement is used to execute a statement or
group of statements repeatedly as long as the specified condition is satisfied.
Syntax:
Break Statement:
Break is one of the statements, which is used in Switch and Loops only. If we execute the
break statement, the control point is come out form the switch or loop. The general form of
break statement is as follows.
Syntax: break ;
Continue Statement:
The continue statement must be used in loops only. When the continue statement is
reached within a loop, it continues the execution from the first statement of the loop.
Syntax:
14
RAO’S DEGREE COLLEGE : : NELLORE
Continue ;
CLASSES
A class is a basic concept of OOP which is used to create Objects. A class is also a basic
structure of all programs of java programs. It provides a convenient environment for packing
together a group of logically related data items. It is also the basic description of how to make an
object that contains fields and methods.
15
RAO’S DEGREE COLLEGE : : NELLORE
int length;
int width;
Rectangle (int x, int y)
{
length = x;
width = y;
}
}
Default Constructor
Parameterized Constructors
Default Constructors:- Default constructor is a constructor which is not having any parameter
list. The following example shows the default constructors.
Ex: Rectangle()
{
…………….
……………
}
Parameterized Constructors:- Parameterized constructor is a constructor which is having one
or more parameter list. The following example shows the default constructors.
In java, is possible to create methods that have the same name, but different parameter
list and with different definitions are called method Overloading.
Or
Method overloading has ability to define more than one method with the same name in
class. In method overloading, the Objects are requested to perform similar tasks using different
input parameters when we call a method. Java matches the method name first and then the
number and type of parameters to decide which one of the definitions have to execute. This
process is known as Polymorphism.
16
RAO’S DEGREE COLLEGE : : NELLORE
After execution of the above program, the first method Rectangle is executed because we
are passing one parameter. And then second method also executed while passing two parameters.
Simply this process is known as method overloading
UNIT – III
Inheritance
Inheritance is the process of inherit (import) the properties of one class to another. In OOP the
concept of inheritance provides the idea of re-usability. This means that we can add additional features
to an existing class without modifying it. The mechanism of deriving a new class from an old class is
called inheritance. Here the old class is referring to base-class and new class can be referred as derived-
class. The derived inherits the features from the base class. Inheritance can be classified into following
types.
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical
4. Multilevel inheritance
1. Single Inheritance:- The derived class with only one class is called as single inheritance. The
diagrammatic representation of single inheritance is as follows.
A -Base Classes
B 17 -Derived Class
RAO’S DEGREE COLLEGE : : NELLORE
2. Multiple Inheritance:- A derived class can be derived from multiple base classes is multiple
inheritance. The diagrammatic representation of multiple inheritances is as follows.
A B -Base Classes
C -Derived Class
3. Hierarchical Inheritance: - Two or more derived classes can be derived from one base called is
called hierarchical inheritance. The diagrammatic representation of hierarchical inheritance is as
follows.
-Base Classes
A
A C D -Derived Classes
4. Multilevel Inheritance:- The mechanism of deriving a class from another derived class is known
as multilevel Inheritance. The diagrammatic representation of multilevel inheritance is as
follows.
A - Base class
C -Derived Classes
INTERFACE
Ex: class A
18
RAO’S DEGREE COLLEGE : : NELLORE
{
…………………
}
class B extends A
{
………………....
}
In java, there are four kinds of inheritance. They are:
- Single inheritance
- Multiple inheritance
- Hierarchical inheritance
- Multi-level inheritance
Final is a keyword, which is used to define the variables, methods and classes as final.
Once we define these as final they are not modifiable or not accessible for the others. The final
keyword is used like the following.
Final variables:- The variables which defined as final variables, are not modified in the
program. The general form of final variable is as follows.
Final methods:- The methods which are defined as final are not altered anywhere or the final
method is not accessible by the Subclass Objects. The general form of final method is as follows.
19
RAO’S DEGREE COLLEGE : : NELLORE
An array is a group of related data items that share a common name and same datatype. Using
arrays, we can store group of elements of a particular type. In arrays a particular item is
identified by their index numbers.
One-Dimensional Arrays:- A list items can be given one variable name using only one
subscript is known as single subscripted variable or one-dimensional variable. While creating
one-dimensional arrays, we follow the following steps.
Declare the array:- the following syntax is used to declare the array.
Or
Type [ ] arrayName;
Ex: int a[ ];
Or
int [ ] a;
20
RAO’S DEGREE COLLEGE : : NELLORE
Creating memory locations:- the following syntax is used to create memory location to the array.
Putting values into memory: the following syntax is used to put values to the arrays.
Two-dimensional Array or double Dimensional array: For creating two dimensional arrays,
we must follow some steps as one dimensional arrays. Two dimensional array must be used two
subscripts: one for row and another for column representation. The following are used to create
two dimensional arrays.
int a[ ][ ]= {{1,2},{3,4}}
STRINGS
21
RAO’S DEGREE COLLEGE : : NELLORE
VECTORS
Vector is a special kind of class in java.util package. Using Vectors, we can store objects
like an array. Simply we can create a dynamic array for storing any type (Data type) of objects.
So that arrays can be easily implemented by vectors. Vectors are created like the following.
Or
Advantage of Vectors:- Vectors has several advantages, some of them are given below:
22
RAO’S DEGREE COLLEGE : : NELLORE
Wrapper class is a class, which is used to convert the Primitive datatype into Object
types. Sometimes we need to convert a Primitive type like int type into an integer datatype
object. We use wrapper class of that type. The Wrapper class is the Package of java.lang
directory.
boolean Bollean
char Character
double Double
float Float
int Integer
long Long
Methods:- The following methods are used to handle primitive type to object.
23
RAO’S DEGREE COLLEGE : : NELLORE
An interface is basically a kind of class like class. Interface also contains variables and
methods. The main difference between class and interface is that interface contains abstract
methods and final variables.
In the above syntax, the interface is keyword and “interfacename” is name of the
interface. The variables are declared as constant and methods are as abstract.
*Note:- Interface supports multi-inheritance because we can derive a class from more than one
interface.
UNIT - IV
24
RAO’S DEGREE COLLEGE : : NELLORE
All java programs in our earlier example can be called single threaded programs. A
program that contains multiple flow of control can be called Multi-Threading.
Creating Thread:-
Creating thread is simple to create run( ) method of thread object. The run method is
heart and soul of any thread. The general form of run method is as follows.
We can extend the class from java.lang.Thread to do this. We follow the following steps.
Declaring the class :The thread class can be extended like the following.
25
RAO’S DEGREE COLLEGE : : NELLORE
A thread is a group of statements, which are executed as a single task. During lifetime of a
thread, there are many states it can enter, they are
Newborn State
Runnable State
Running State
Blocked state.
Dead State.
A thread is always is one of these five states. It can move from one state to another state via a
variety of ways as shown in the below following Diagram.
Start Newborn
Stop
Start
Stop
Dead
Active Runnin Runnable Killed
Thread yield Thread
Suspend Resume
Stop
sleep notify
wait
Blocked
Idle Thread
Newborn State : when we Create a thread objects, the thread is born and is said to be in
Newborn Sate. At this state we can do only one of the following methods.
Runnable state :- The runnable states means that the thread is ready for exection and is waiting
for the availability of the processor.That is the thread is joined the Queue processor(FIFO).In this
state , executing yield( ) method, to provide a priority.
26
RAO’S DEGREE COLLEGE : : NELLORE
Running State:- Running state means that the processor has given its time to the thread for its
execution. while running the thread we may execute any one of the following methods.
->Suspend
->sleep(1000);
->Wait( );
Blocked State:- A method is said to be blocked when it is prevented from entering into the
runnable state and subsequently the running state. Simply the blocked thread is considered not
runnable but not dead therefore fully qualified to run again.
Dead State:-Every thread has a life cycle. A running thread ends its life when it has completed
executing its run( ) method. It is a natural death. However we can kill it at any state even newly
born or blocked state.
Exceptions In Java
Errors are the wrongs that can make a program go wrong. An error may produce an
incorrect output or may terminate the execution of the program or system crash.
Types of errors:-The errors may be classified into two categories. They are
1. Compile – Time errors :- All syntax errors will be detected and displayed by the java
compiler are known as Compile - Time errors. Most compile time errors are detected due to
typing mistakes.
Missing – Semicolon.
Missing – double – quotes.
Misspelling keywords.
Use of undeclared variables.
Missing brackets in classes and methods etc.
Improper placement of braces.
27
RAO’S DEGREE COLLEGE : : NELLORE
Exceptions
An Exception is a condition that is caused by run-time errors in the program. When Java
interpreter encounters an error such as dividing an integer by Zero. It creates an exception object
and throws it. While throwing the exception object, we should be catch that, otherwise the
program is terminated abruptly. The process of handling the exception is known as exception
handling.
The error handling code basically consists of two segments, one is detect and throw errors(try
block) and other is to catch the exception(catch block).
The following diagram shows the process of try and catch block.
28
RAO’S DEGREE COLLEGE : : NELLORE
}
catch(Exception-type e)
{
Statement;
}
In the above syntax the try-block can have one or more statements that could generate an
exception. If anyone statement generate an exception, the reaming statements in the block are
skipped and exception jumps to the catch-block. The catch statement that is works like method
definitions which handle the exception.
UNIT - V
Applet Programming
Applet:- Applet is a small program which is developed for internet applications. An applet is
located on a remote computer (server) can be downloaded via internet and executed on a local
computer (client) using a java capable browser such as HotJava.
In java we can develop applets for doing anything from simple animated Graphics to
computer games and utilities. Since applets are embedded in html document and run inside a web
page. They are two types of Apples in java.
*Local Applets.
*Remote Applets.
*Local Apples:- An applet which is stored and executed in a local system is known as local
applet.
*Remote Applets: A remote applet is that which is developed by someone else and stored on a
remote computer connected to the internet.
Internet
29
RAO’S DEGREE COLLEGE : : NELLORE
Applets and applications are java programs, but there is a difference between them.
Applets are not full-featured application programs where are applications are full-featured
applications. Generally, applications are used as any kind of applications where as applets are
used for internet applications only. The difference between applets and application are shown
below.
*Running State.
*Idle state.
*Display State.
An applet is always in one of the above states. It can move from one state to another state
via. a variety of ways as shown in the following diagram.
Idle Stopped
Running
RAO’S DEGREE COLLEGE : : NELLORE
Once in the applet life cycle. The general form of init( ) method is as follows.
31
RAO’S DEGREE COLLEGE : : NELLORE
{
----------- //Action
------------
}
*Dead State:- An applet is said to be dead when it is removed from memory. This is achieved by
invoking the destroy( ) method. It occurs only once for applet. The general form of destroy( )
method is as follows.
32