0% found this document useful (0 votes)
16 views32 pages

Vvvimp BSC Java Onetime

The document provides an overview of Object-Oriented Programming (OOP) using Java, detailing its definitions, basic concepts, benefits, and features. It covers key OOP principles such as classes, objects, inheritance, polymorphism, and encapsulation, as well as Java's unique characteristics like being platform-independent and multithreaded. Additionally, it discusses Java program structure, data types, variable scope, and operators used in Java programming.

Uploaded by

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

Vvvimp BSC Java Onetime

The document provides an overview of Object-Oriented Programming (OOP) using Java, detailing its definitions, basic concepts, benefits, and features. It covers key OOP principles such as classes, objects, inheritance, polymorphism, and encapsulation, as well as Java's unique characteristics like being platform-independent and multithreaded. Additionally, it discusses Java program structure, data types, variable scope, and operators used in Java programming.

Uploaded by

Krish Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

RAO’S DEGREE COLLEGE : : NELLORE

Object Oriented Programming Using JAVA


UNIT – I
What is Object-Oriented Programming (OOPS)
Definition :-“Object Oriented Programming is an approach that provides a way of modular
programming by creating patrician memory “area for both data and functions that can be used for
creating copies of such modules on demand.
Object Oriented Paradigm

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 : Data & Methods


The object may communicate each other like the following.

Object - 1 Object - 2

Data Data

Methods Methods

Data

Methods

Object - 3
1
RAO’S DEGREE COLLEGE : : NELLORE

What are the Basic Concepts of OOPs?

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

Flying Bird Non-Flying Bird

Sparrow Parrot Penguin Kiwi

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

Circle Rectangle Triangle

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.

- Creating classes that define objects and their behaviors.


- Creating objects from class definitions.
- Establishing communication among objects etc.

Ex. Employee . Salary(Name);


Object Message Information

What are the Benefits and Applications of OOPs?

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.

Advantages (Benefits) are:-

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

What are the Features of JAVA?

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


- Plat-from independent and portable
- Object oriented
- Robust and secure
- Distributed
- Small, simple and familiar
- Multithreaded
- High performance
- Dynamic and extensible

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

Write the Java Program Structure?

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

main method class


{
main method definition
}

Documentation Section:- The documentation section consists of comments given name of the
programmer, the author and date details. They are:

Single line comment --- //

Multi line comment ---/* ………………..*/

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.

Ex: import Student.test;

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.

What is the Java Virtual Machine(JVM)?

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

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.

public static void main(String args[])

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

What are the DATA TYPES?

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.

In ‘Java’ language, the data types are classified as shown below:

Data Types

Primitive (intrinsic) Non-primitive (Derived)

Numeric Non-Numeric Classes Interface Arrays

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

The size and range of integer types are as follows

Data type Size

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:

Data type Size Minimum values Maximum values

float 4 bytes 3.4e-38 3.4e+38

7
RAO’S DEGREE COLLEGE : : NELLORE

double 8 bytes 1.7e-308 1.7e+308

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.

What are the SCOPE OF VARIABLES?

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.

Ex: class Scope


{
static int x, y; Global variables
...
..
int a, b; Instance variables
8
RAO’S DEGREE COLLEGE : : NELLORE

void readData()
{
...............
int z; Local variables
..............
}
void printData()
{
............
............
}

What are the OPERATORS in Java?


An operator is a symbol used to perform arithmetic and logical operations. It is used to
manipulate data stored in the variables.
‘C’ language supports the following types of operators.

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

% Modulo division (Remainder)

Example: a+b, 5*4 etc.

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

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Examples: a>b, 5<90, n==m

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 AND

¦¦ Logical OR

! Logical NOT

4. Increment and Decrement Operators:

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

Ex: a++; ++a;


n--; --m;

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.

6. The Conditional Operators

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:

String s = (age>50) ? “Old Age” : “Young Age”;

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

DECISION CONTROL STRUCTURES / CONDITIONAL / BRANCHING STATEMENTS


These statements are used to execute a statement or group of statements
depending on the given condition. There are mainly two types of conditional statements. They
are
1. if or if…else statement
2. switch statement

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

The general format of switch statement is as follows:

Syntax:

switch (op)
{
case V1 : statement-block1;
[break;]
case V2 : statement-block2;
[break;]
: :
: :
case Vn : statement-block-n;
[break;]
[default : statement-block-d;]
}

ITERATIVE / LOOPING / REPETITIVE STATEMENTS


The iterative statements are used to execute a statement or a group of statements
repeatedly for a specified number of times. The iterative statements are also called repetitive
(or) Looping control statements.

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:

for(initialisation ; condition ; increment/decrement)


{
statement-block;
}

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.

Syntax:-class classname [extends superclassname]


{
[fields-declaration]
[method-declaration]
}
In the above syntax classname and superclassname are any java identifiers. The keyword
extends is used to derive the properties of superclassname to the classname. This type of process
is know as inheritance.

Example:- class person


{
String name;
int age;
void getdata()
{
--------
}
}
CONSTRUCTORS

A Constructor is a special type of method in java. It is similar to method. It is used to


initialize the instance variables or object. To do this, we follow the following.

- Constructor name and class name should be same.


- Constructor may have or may not have parameters.
- A constructor does not return any value, not even void.
- A constructor automatically called and executed at the time of creating Objects.
- A constructor is called and executed only once per object.

Example: class Rectangle


{

15
RAO’S DEGREE COLLEGE : : NELLORE

int length;
int width;
Rectangle (int x, int y)
{
length = x;
width = y;
}
}

Types of Constructors:- Java supports different types of constructors depending on the


parameter list. They are:

 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.

Ex: Rectangle(int a, int b)


{
…………….
……………
}
METHOD OVERLOADING

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

Ex: class Rectangle


{
int length;
int width;
Rectangle(int x )
{
length = width = x;
}
Rectangle(int x, int y)
{
length = x;
width = y;
}
Int getData()
{
return ( length * width);
}
}

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

B - Semi Derived Classes

C -Derived Classes
INTERFACE

Interface is an important basic concept of java (OOP). It is simply Reusability of an


existing class without redefining the same once again. The mechanism of deriving a new class
from old class is called Interface. The Old class is known as Base class or Super class or Parent
class. The new one is known as Derived class or sub class or Child class. Finally, in inheritance
the object of one class acquire the properties of another class.

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

Defining subclasses:-To define a subclass, we follow the following syntax

class SubclassName extends SuperclassName


{
Fields declaration;
Methods declaration;
}
In the above syntax, the keyword extends specifies the properties of SuperclassName are
extended to SubclassName.

FINAL VARIABLES, METHODS AND CLASSES

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.

Syntax: final datatype variable = values;

Ex: final int size = 100;

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.

Syntax: final returntype methodName()


{
……………..
}

19
RAO’S DEGREE COLLEGE : : NELLORE

Ex: final void display()


{
…………………
}
Final Classes:- The class is defined as final, which is never be sub-classed. The final class helps
us to create a secured programs, which is never be accessed by the others. The general form of
final class is as follows.

Syntax: final class ClassName


{
………………………
}
Ex: final class NonDerived
{
…………………….
}
ARRAYS

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.

Ex: a[ i ] // Here i is an index number.

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.

o Declare the array


o Creating memory locations
o Putting values into memory (initialization)

Declare the array:- the following syntax is used to declare the array.

Syntax: type arrayName[ ];

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.

Syntax: arrayName = new Type[size];


Or
Type arrayName = new type[size];
Ex: a = new int[5]; or int a[ ] = new int[5];

Putting values into memory: the following syntax is used to put values to the arrays.

Syntax: type arrayName[ ] = {list of values};

Ex: int a[ ] = {1,2,3,4,5};

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.

- Declare the tow dimensional array.


int a[ ][ ]; or int [ ][ ] a;
- Creating memory locations.

a = new int [2][2] or int a[ ][ ]=new int [2][2];

- Initialization of two dimensional arrays.

int a[ ][ ]= {{1,2},{3,4}}

STRINGS

A string is a collection of characters, which are enclosed with in double quotes.


Or
A string represents a sequence of characters that are implemented with string operations like
length, copy, reverse, concatenation etc.
The general form of string declaration is as follows.

Syntax: String stringName;


stringName = new String (“String”);
ex: String str;
str = new String(“BSc”);
or
Syn: String stringName = new String(“String “);
Ex: String str = new String(“BSc”);
String Methods: A String class defines a number of methods to manipulate strings.

21
RAO’S DEGREE COLLEGE : : NELLORE

Sl.no Method Description


1 S1=s.toLoweCase Converts the s to all lower case
2 S1=s.toUpperCase Converts the s to all upper case
3 N=s.length Gives the length of s
4 S.concatenate(s1) Concatenates s and s1
5 s.compateTo(s1) Compare, return negative if s<s1, positive if s>s1, if
equals return zero
6 s.charAt(x) Gives x th character of s
7 s.indexOf(x) Gives the position of x in the string s
8 s.equals(s1) Return true if s == s1
9 s.substring(n) Gives substring starting of nth character

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.

Ex: Vector name = new Vector();

Or

Vector name = new Vector(5);

In the above example, we may or may not supply size of vector.

Advantage of Vectors:- Vectors has several advantages, some of them are given below:

- It is convenient to use vectors to store Objects.


- A vector can be used to store a list of objects that may vary in size.
- We can add or delete objects from the list, when required.

Methods: The following methods are used to operate the vectors.

Slno. Methods Description


1 List.addElement(item) Adds the item specified to list at end
2 List.elementAt(n) Gives the name of the n th Objects
3 List.size() Gives the number of objects present
4 List.removeElement(item) Removes the specified item form list
5 List.removeElementAt(n) Removes the nth element from list
6 List.removeAllElements() Removes all elements of list
7 List.copyInto(array) Copies all elements of list to array
8 List.insertElementAt(item,n) Inserts the item a nth position
WRAPPER CLSSES

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.

The following table shows wrapper classes and primitive type.

Simple Type Wrapper Class

boolean Bollean
char Character
double Double
float Float
int Integer
long Long

Methods:- The following methods are used to handle primitive type to object.

(a). Methods Converting Primitive datatype into Objects.

Method Calling Action


Integer int = new Integer(i); Converts integer to integer object.
Float flt = new Float(f); Converts float to float Object.
Double dbl = new Double(d); Convert double to double object.
Long lg = new Long(l); Convert long to long Object
.

(b).Converting object to Primitive datatype.

Method Calling Action


int i = int.intValue( ); Converts int object to integer.
float f = flt.floatValue( ); Converts float object to float.
double d = dbl.doubleValue( ); Converts double object to double.
long l = lg.longValue( ); Convert long object to lo
( c ). Converting Primitive type to String.

Method Calling Action


str = Integer.toString( i ); converts integer to string.
str = Float.toString( f ); converts float to string.
str = Double.toString( d ); converts double to string.
Str = Long.toString( l ); converts long to string.

( d ). Converting String Object to Primitive Type Object.

23
RAO’S DEGREE COLLEGE : : NELLORE

Method Calling Action


int = Integer.valueOf(str); converts string objects to Integer object.
flt = Float .valuesOf(str); converts string objects to Float object.
dbl = Double.valueOf(str); converts string objects to Double object.
lg = Long.valueof(str); converts string objects to long object.

( e ). Converting numeric string to primitive datatype.

Method Calling Action


int i = Integer.parseInt(str); Converts string to integer.
float f = Float.parsefloat(str); Converts string to float.
double d = Converts string to double.
Double.parseDouble(str)
long l = long.parseLong(str); Converts string to long.

Interface ( or ) Multiple - Inheritance

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.

The general form of interface is as follows.

Syntax: interface Interfacename


{
fields;
methods;
}

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.

Example:- interface Area


{
final float PI = 3.142f;
float compute(float x, float y);
}

UNIT - IV

24
RAO’S DEGREE COLLEGE : : NELLORE

Multi Thread Programming


A thread is similar to program that has a single flow of control. It has a beginning, a
body, an end and executes commands sequentially.

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.

Syntax: public void run( )


{
………………..
Statement(s);
……………………
}
Extending the thread class :

We can extend the class from java.lang.Thread to do this. We follow the following steps.

 Declaring the class.


 Implementing the run( ) method.
 Starting the thread.

Declaring the class :The thread class can be extended like the following.

class Mythread extends Thread


{
………..
…………..
}
Implementing the run( ) method : The run method is used to implements the thread concepts.
The run( ) method is implemented like the following.

public void run( )


{
----------------
-----------------
}
Starting the Thread : Starting a new thread. The run method is involved with the help of
another method is known as start( ).
Life Cycle Of Thread:-

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.

->For Running , We use start( ) method.

->For killing, We use stop method.

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

 Compile time errors.


 Run-Time errors.

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.

The following are the most commonly occurring problems.

 Missing – Semicolon.
 Missing – double – quotes.
 Misspelling keywords.
 Use of undeclared variables.
 Missing brackets in classes and methods etc.
 Improper placement of braces.

Example: class Example


{
System.out.println(“Hello World”) // Missing Semicolon.
}
2.Run - Time Errors : Sometimes, a program may compile successfully but not run properly.
Such programs may produce wrong results. These are called run – time errors.

27
RAO’S DEGREE COLLEGE : : NELLORE

The following are most commonly occurring errors.

->Dividing an integer by Zero.


->Accessing an element that is the out of bounds of Array.
->Converting invalid string to a number etc.
->Trying to change the state of a thread illegally.

Example: class Example


{
int x; //variable.
x =5/0; //division by zero.
}

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.

Try block Exception object creation


statements
that causes an
exception
Throws exception
object
catch block
statements
that handle the Exception handler
exception

The general form of try and catch block is as follows.


Syntax :- ---------
----------
try
{
Statement;

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

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.

- Applets do not use main() methods


- Applets cannot run independently, they are run thru HTML code.
- Applets cannot read/write files from local computers
- Applets cannot communicate with other servers on the network.
- Applets cannot run any program from the local computer.
- Applets cannot run methods which are in other languages like C or C++

Applet Life Cycle


Applet is a small program, which is developed for internet applications. During lifetime
of an applet, there are many states it can enter. They are:

*Born (or) Initialization state.

*Running State.

*Idle state.

*Dead or Destroy 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.

Begin Local Bor


Applet Stop()
30

Idle Stopped
Running
RAO’S DEGREE COLLEGE : : NELLORE

Born(or)Initialization State:- When we load applet(begin), it enters into the initialization


state. In this state, we may do the following tasks.

*Create objects needed by the applet.


*Setup initial values.
*Load images(or)fonts.
*Setup colors etc.
These are activated by calling the init( ) method of AppletClass. It occurs only

Once in the applet life cycle. The general form of init( ) method is as follows.

Syntax: public void init( )


{
-----------
------------ // Action
}
*Running State:- After initializing the applet, it enters into running state by calling start( )
method automatically. It may occur once again if the applet is already in idle state. The start( )
method is called more than once for an applet while leaving and return back to the page. The
general form of start( ) method is as follows.

Syntax : public void start( )


{
----------- \\Action
------------
}
*Idle(or)Stopped State :- After calling method, applet becomes idle state. It is automatically
calls while leaving the page. The stop( ) method is called more than once for an applet. The
general form of stop( ) method is as follows.

Syntax: public void stop( )

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.

Syntax : public void destroy( )


{
----------//Action
-----------
}
*Display State:- The display state is nothing but displaying information on screen. The Paint( )
method helps us to performs some output operations on the screen. The general form of paint
method is as follows.

Syntax : public void paint(Graphics g)


{
------------ //Action
-------------
}

32

You might also like