OBJECT oriented program with java Module-I Object oriented concepts Introduction: Java is a high-level, third generation programming language, like C, FORTRAN, Smalltalk, Perl, and many others. Knowing how to program in C or, better yet, C++, will certainly help you to learn Java more quickly, but you don't need to know C to learn Java. A Java compiler won't compile C code, and most large C programs need to be changed substantially before they can become Java programs. What's most special about Java in relation to other programming languages is that it lets you write special programs called applets that can be downloaded from the Internet and played safely within a web browser. Java language is called as an Object-Oriented Programming language and before begining for Java, we have to learn the concept of OOPs (Object-Oriented Programming). There are some basic concepts of object oriented programming as follows: 1. Object 2. Class 3. Data abstraction 4. Data encapsulation 5. Inheritance 6. Polymorphism 7. Dynamic binding 1 | Page
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
OBJECT oriented program with java
Module-I
Object oriented concepts
Introduction:
Java is a high-level, third generation programming language, like C, FORTRAN, Smalltalk, Perl,
and many others. Knowing how to program in C or, better yet, C++, will certainly help you to learn
Java more quickly, but you don't need to know C to learn Java. A Java compiler won't compile C
code, and most large C programs need to be changed substantially before they can become Java
programs.
What's most special about Java in relation to other programming languages is that it lets you write
special programs called applets that can be downloaded from the Internet and played safely within a
web browser. Java language is called as an Object-Oriented Programming language and before
begining for Java, we have to learn the concept of OOPs (Object-Oriented Programming).
There are some basic concepts of object oriented programming as follows:
1. Object
2. Class
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
1. Object:
Objects are important runtime entities in object oriented method. They may characterize a
location, a bank account, and a table of data or any entry that the program must handle. Each
object holds data and code to operate the data. Object can interact without having to identify the
details of each other‘s data or code. It is sufficient to identify the type of message received and
the type of reply returned by the objects.
2. Classes
1 | P a g e
A class is a set of objects with similar properties (attributes), common behaviour
(operations), and common link to other objects. The complete set of data and code of an object can
be made a user defined data type with the help of class. The objects are variable of type class. A class
is a collection of objects of similar type. Classes are user defined data types and work like the build
in type of the programming language. Once the class has been defined, we can make any number of
objects belonging to that class. Each object is related with the data of type class with which they are
formed.
As we learned that, the classification of objects into various classes is based on its properties
(States) and behaviour (methods). Classes are used to distinguish are type of object from another.
The important thing about the class is to identify the properties and procedures and applicability to
its instances.
3. Data Abstraction
Data abstraction refers to the act of representing important description without including the
background details or explanations. Classes use the concept of abstraction and are defined as a list of
abstract attributes such as size, cost and functions operate on these attributes. They summarize all the
important properties of the objects that are to be created. Classes use the concepts of data abstraction
and it is called as Abstract Data Type (ADT).
4. Data Encapsulation
Data Encapsulation means wrapping of data and functions into a single unit (i.e. class). It is
most useful feature of class. The data is not easy to get to the outside world and only those functions
which are enclosed in the class can access it. These functions provide the boundary between Object‘s
data and program. This insulation of data from direct access by the program is called as Data hiding.
5. Inheritance
Inheritance is the process by which objects of one class can get the properties of objects of
another class. Inheritance means one class of objects inherits the data and behaviours from another
class. Inheritance maintains the hierarchical classification in which a class inherits from its parents.
Inheritance provides the important feature of OOP that is reusability. That means we can include
additional characteristics to an existing class without modification. This is possible deriving a new
class from existing one.
In other words, it is property of object-oriented systems that allow objects to be built from
other objects. Inheritance allows openly taking help of the commonality of objects when constructing
new classes. Inheritance is a relationship between classes where one class is the parent class of
2 | P a g e
another (derived) class. The derived class holds the properties and behaviour of base class in addition
to the properties and behaviour of derived class.
6. Polymorphism
(Poly means ―many and morph means ―form). Polymorphism means the ability to take
more than one form. Polymorphism plays a main role in allocate objects having different internal
structures to share the same external interface. This means that a general class of operations may be
accessed in the same manner even though specific activities associated with each operation may
differ. Polymorphism is broadly used in implementing inheritance.
It means objects that can take on or assume many different forms. Polymorphism means that
the same operations may behave differently on different classes. Booch defines polymorphism as the
relationship of objects many different classes by some common super class. Polymorphism allows us
to write generic, reusable code more easily, because we can specify general instructions and delegate
the implementation detail to the objects involved.
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding means that the code related with a given procedure call is not known until the
time of the call at run time. Dynamic binding is associated polymorphism and inheritance.
3 | P a g e
Java History:
Java is a general-purpose, object-oriented programming language developed by Sun Microsystems of
USA in 1991.Originally called Oak by James Gosling (one of the inventor of the language). Java was
invented for the development of software for consumer electronic devices like TVs, tosters, etc. The
main aim had to make java simple, portable and reliable.
Java Authors: James , Arthur Van , and others
Following table shows the year and beginning of Java.
4 | P a g e
JAVA Features:
5 | P a g e
Year Progress
1990 Sun decided to developed software that
could be used for electronic devices. And the
project called as Green Project head by
James Gosling.
1991 Announcement of a new language named
―Oak‖
1992 The team verified the application of their
new language to manage a list of home
appliances using a hand held device.
1993 The World Wide Web appeared on the
Internet and transformed the text-based
interface to a graphical rich environment.
1994 The team developed a new Web browsed
called ―Hot Java‖ to locate and run Applets.
1995 Oak was renamed to Java, as it did not
survive ―legal‖ registration. Many
companies such as Netscape and Microsoft
announced their support for Java.
1996 Java language is now famous for Internet
programming as well as a general purpose
OO language.
1997 Sun releases Java Development Kit(JDK
1.1)
1998 Sun releases Software Development Kit
(SDK 1.2)
1999 Sun releases Java 2 platform Standard
Edition (J2SE) and Enterprise
Edition(J2EE).
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with JDK 5.0 was released.
As we know that the Java is an object oriented programming language developed by Sun
Microsystems of USA in 1991. Java is first programming language which is not attached with any
particular hardware or operating system. Program developed in Java can be executed anywhere and
on any system.
Features of Java are as follows:
1. Compiled and Interpreted
2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
1. Compiled and Interpreted: Basically a computer language is either compiled or interpreted. Java
comes together both these approach thus making Java a two-stage system. Java compiler translates
Java code to Byte code instructions and Java Interpreter generate machine code that can be directly
executed by machine that is running the Java program.
2. Platform Independent and portable: Java supports the feature portability. Java programs can be
easily moved from one computer system to another and anywhere. Changes and upgrades in
operating systems, processors and system resources will not force any alteration in Java programs.
This is reason why Java has become a trendy language for programming on Internet which
interconnects different kind of systems worldwide. Java certifies portability in two ways. First way
is, Java compiler generates the bytecode and that can be executed on any machine. Second way is,
size of primitive data types are machine independent.
3. Object- oriented: Java is truly object-oriented language. In Java, almost everything is an Object.
All program code and data exist in objects and classes. Java comes with an extensive set of classes;
organize in packages that can be used in program by Inheritance. The object model in Java is trouble-
free and easy to enlarge.
6 | P a g e
4. Robust and secure:Java is a most strong language which provides many securities to make certain
reliable code. It is design as garbage –collected language, which helps the programmers virtually
from all memory management problems. Java also includes the concept of exception handling, which
detain serious errors and reduces all kind of threat of crashing the system. Security is an important
feature of Java and this is the strong reason that programmer use this language for programming on
Internet. The absence of pointers in Java ensures that programs cannot get right of entry to memory
location without proper approval.
5. Distributed: Java is called as Distributed language for construct applications on networks which
can contribute both data and programs. Java applications can open and access remote objects on
Internet easily. That means multiple programmers at multiple remote locations to work together on
single task.
6. Simple and small: Java is very small and simple language. Java does not use pointer and header
files, go to statements, etc. It eliminates operator overloading and multiple inheritance.
7. Multithreaded and Interactive: Multithreaded means managing multiple tasks simultaneously. Java
maintains multithreaded programs. That means we need not wait for the application to complete one
task before starting next task. This feature is helpful for graphic applications.
8. High performance: Java performance is very extraordinary for an interpreted language, majorly
due to the use of intermediate bytecode. Java architecture is also designed to reduce overheads
during runtime. The incorporation of multithreading improves the execution speed of program.
9. Dynamic and Extensible: Java is also dynamic language. Java is capable of dynamically linking in
new class, libraries, methods and objects. Java can also establish the type of class through the query
building it possible to either dynamically link or abort the program, depending on the reply. Java
program is support functions written in other language such as C and C++, known as native methods.
COMPARISON IN JAVA AND C++
Java C++
1 Java is true Object-oriented language. C++ is basically C with Object-oriented
extension.
7 | P a g e
2 Java does not support operator
overloading.
C++ supports operator overloading.
3 It supports labels with loops and
statement blocks
It supports goto statement.
4 Java does not have template classes as
in C++.
C++ has template classes.
5 Java compiled into byte code for the
Java Virtual Machine. The source code
is independent on operating system.
Source code can be written to be platform
independent and written to take advantage
of platform.C++ typically compiled into
machine code.
6 Java does not support multiple
inheritance of classes but it supports
interface.
C++ supports multiple inheritance of
classes.
7 Runs in a protected virtual machine. Exposes low-level system facilities.
8 Java does not support global variable.
Every variable should declare in class.
C++ support global variable.
9 Java does not use pointer. C++ uses pointer.
10 It Strictly enforces an object oriented
programming paradigm.
It Allows both procedural programming
and object-oriented programming.
11 There are no header files in Java. We have to use header file in C++.
JAVA Development Kit (JDK)
JDK is software, which hold all the components of JAVA program. It means, it holds the develop
mint kit of JAVA program. All the components reside within the “bin” directory of “JDK”. The
components are as follows.
JAVAC (JAVA Compiler)
JAVA (JAVA Interpreter)
JAVAP (JAVA Disabler)
JAVA doc (JAVA Document)
Applet viewer (JAVA web Browser)
Hence, to develop the JAVA program, we must have JDK software in our system. JDK comes in
A Java program is basically a set of classes. A class is defined by a set of declaration statements and
methods or functions. Most statements contain expressions, which express the actions carried out on
information or data. Smallest indivisual thing in a program are known as tokens. The compiler
recognizes them for building up expression and statements.
There are five types of token as follows:
i. Literals
ii. Identifiers
iii. Operators
iv. Separators
24 | P a g e
I. Literals:
Literals in Java are a sequence of characters (digits, letters and other characters) that characterize
constant values to be stored in variables. Java language specifies five major types of literals are as
follows:
Integer literals
Floating point literals
Character literals
String literals
Boolean literals
II. Identifiers:
Identifiers are programmer-created tokens. They are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program. Java identifiers follow the following rules:
They can have alphabets, digits, and the underscore and dollar sign characters.
They must not start with a digit.
Uppercase and lowercase letters are individual.
They can be of any length.
Identifier must be meaningful, easily understandable and descriptive.
For example:
Private and local variables like ―length‖.
Name of public methods and instance variables begin with lowercase letter like ―addition
III. Keywords:
Keywords are important part of Java. Java language has reserved 50 words as keywords. Keywords
have specific meaning in Java. We cannot use them as variable, classes and method. Following table shows
keywords.
Java Reserved KeywordsAbstract boolean break byte case catchChar Class const continue default doDouble Else extends false final finallyFloat For goto if implements importinstanceof Int interface long native newnull Package private protected public returnshort Static super switch synchronized thisthrow Throws transient true try voidvolatile While
IV.Operator:
25 | P a g e
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs to
operate data and variables. They frequently form a part of mathematical or logical expressions.
Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
1. Arithmetic operators:
Arithmetic operators are used to make mathematical expressions and the working out as same in
algebra. Java provides the fundamental arithmetic operators. These can operate on built in data type
of Java.
Following table shows the details of operators
. Operator Importance/ significance
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo division or
remainder
When both operands in the expression are integers then the expression is called Integer
expression and the operation is called Integer arithmetic.
When both operands in the expression are real then the expression is called Real expression
and the operation is called Real arithmetic.
When one operand in the expression is integer and other is float then the expression is called
Mixed Mode Arithmetic expression and the operation is called Mixed Mode Arithmetic
operation.
26 | P a g e
2. Logical operators: When we want to form compound conditions by combining two or more
relations, then we can use logical operators.
Following table shows the details of operators.
Operators Importance/significance
|| Logical – OR
&& Logical –AND
! Logical –NOT
3. Relational Operators:
When evaluation of two numbers is performed depending upon their relation, assured decisions are
made. The value of relational expression is either true or false.
Following table shows the details of operators
Operator Importance/significance
> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
4. Assignment Operators:
Assignment Operators is used to assign the value of an expression to a variable and is also called as
Shorthand operators.
Variable_name binary_operator = expression
Following table show the use of assignment operators.
Simple Assignment Operator Statement with shorthand
Operators
A=A+1 A+=1
A=A-1 A-=1
A=A/(B+1) A/=(B+1)
A=A*(B+1) A*=(B+1)
A=A/C A/=C
27 | P a g e
A=A%C A%=C
Now the following program shows the use of operators.
class Assoptr
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c = 30;
a+=1;
b-=3;
c*=7;
System.out.println("a = " +a);
System.out.println("b = "+b);
System.out.println("c = "+c);
}
}
Output:
a = 11
b = 18
c = 310
5. Conditional Operators:
The character pair?: is a ternary operator of Java, which is used to construct conditional expressions
of the following form:
Expression1? Expression3: Expression3
The operator? : works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and becomes the value of the
conditional expression. If Expression1 is false then Expression3 is evaluated and its value becomes
the conditional expression.
Now the following program shows the use of operators.
class Coptr
28 | P a g e
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c;
c=(a>b)?a:b;
System.out.println("c = " +c);
c=(a<b)?a:b;
System.out.println("c = " +c);
}
}
Output:
c = 30
c = 10
6. Increment\decrement operator
Increment\decrement operator is used to increase or decrease the value of a variable by one (1).
“++” Is known as increment operator and “- -“is known as decrement operator.
Ex: - int a = 5;
a++; a=6 equivalent to a=a+1;
++a; a=7 equivalent to a=a+1-;
a--; a=6 equivalent to a=a-1;
--a; a=5 equivalent to a=a-1;
There are two types of increment\decrement operator: -
Post-fix increment\decrement operator.
Pre-fix increment\decrement operator.
Post-Fix Increment\Decrement Operator: When increment/decrement operator is used after an
operand then it is known as post-fix increment/decrement operator.
Ex: -
int a=5,b;
b=a++; a=6
29 | P a g e
b=5
In this case, the assignment operation performed at first and then the increment\decrement operation is
performed.
Ex: - c=b-- a=4
b=5
Then it is equivalent to b= a and a--.
Pre-Fix Increment\Decrement Operator: When increment/decrement operator is used before an
operand then it is known as pre-fix increment/decrement operator.
Ex: - int a=5,b;
b=++a; a=6
b=6
c=b-- a=5
b=5
In this case, the increment/decrement operator performed at first then the assignment operation is
performed.
The statement b= ++a; is equivalent to ++a and b= a
7. Bit Wise Operators:
Bit wise operator execute single bit of their operands.
Following table shows bit wise operator:
Operator Importance/ significance
| Bitwise OR
& Bitwise AND
&= Bitwise AND assignment
|= Bitwise OR assignment
^ Bitwise Exclusive OR
<< Left shift
>> Right shift
~ One‘s complement
Now the following program shows the use of operators.
30 | P a g e
(1) Program
class Boptr1
{
public static void main (String args[])
{
int a = 4;
int b = a<<3;
System.out.println("a = " +a);
System.out.println("b = " +b);
}
}
Output:
a =4
b =16
IV. Separator:
Separators are symbols. It shows the separated code. They describe function of our code.
Name use
() Parameter in method definition,
containing statements for conditions,etc.
{} It is used for define a code for method and
classes
[] It is used for declaration of array
; It is used to show the separate statement
, It is used to show the separation in
identifier in variable declarartion
. It is used to show the separate package
name from sub-packages and classes,
separate variable and method from
reference variable.
Control flow statements:
31 | P a g e
Control statements are used to provide the flow of execution with condition. In java program, control
structure is can divide in three parts:
Selection statement
Iteration statement
Jumps in statement
I. Selection Statement: Selection statement is also called as Decision making statements
because it provides the decision making capabilities to the statements.
In selection statement, there are two types:
if statement
switch statement
These two statements are allows you to control the flow of a program with their conditions.
if Statement:
The “if statement” is also called as conditional branch statement. It is used to program execution
through two paths. The syntax of “if statement” is as follows:
Syntax:
if (condition)
{
Statement 1; Statement 2;
...
}
else
{
Statement 3;
Statement 4;
...
}
The “if statement” is a commanding decision making statement and is used to manage the flow of
execution of statements. The “if statement” is the simplest one in decision statements. Above syntax
is shows two ways decision statement and is used in combination with statements.
32 | P a g e
If-else Statements
It is known as double blocked conditional statements .It means, it has TRUE parts as well as
FALSE part.
If the given condition is TRUE then the TRUE part is executed otherwise FALSE part is executed.
Syntax: -
if (condition)
{
………………..
……………….. True part
}
else
{
………………..
……………….. False part
}
NOTE: -
When we have to write only one statement in conditional statement then it is not need to use curly
brace ON/ OFF. But it is good practice to use curly brace in all situations.
switch statement: In Java, switch statement check the value of given variable or statement against a
list of case values and when the match is found a statement-block of that case is executed. Switch
statement is also called as multiway decision statement.
Syntax:
switch(condition)// condition means case value
{
case value-1:statement block1;break;
case value-2:statement block2;break;
case value-3:statement block3;break;
…
default:statement block-default;break;
33 | P a g e
}
Statement a;
The condition is byte, short, character or an integer. Value-1, value-2, value-3…are constant and
is called as labels. Each of these values is matchless or unique with the statement. Statement
block1, Statement block2, Statement block3 .are list of statements which contain one statement or
more than one statement. Case label is always end with “:” (colon).
Nesting of if else Statement
Syn: -
if (condition)
{
………….
………….
if (condition)
{
…………..
…………..
}
else
{
…………
…………
}
}
else
{
34 | P a g e
…………
…………
The else part then we have to use Ladder of if statement. If condition is true then only “part1”will be
executed, otherwise condition2 will be checked. It conditon2 is true then only “part2” in be executed,
otherwise condition3 will be checked.
If condition3 is true then only “part3” will be executed otherwise “part4” will be executed
Syn: -
If (condition 1)
{
………….
…………. Part 1
}
else if (condition 2)
{
…………
………… Part2
}
else if (condition 3)
{
………….
…………. Part3
}
else
{
35 | P a g e
………….
…………. Part4
}
Looping Statement
Looping statement is used to repeat a set of statements again & again until the given
condition remains true. It means, it is used to repeat a certain task for a certain period.
The condition given in the looping statement must be of Boolean type. There are three looping statement
supported by JAVA.
Like C++, JAVA also supports three looping statement
1. for loop
2. while loop
3. do while loop
1. for loop: It is a Looping statement, which is used to execute a set of statements again & again until
the given condition remains true.
Syn: - for (initialization part; conditional part; increment/decrement part)
{
……….
……….
}
2. While-loop: It is also a looping statement, which is used to repeat a set of statements again &
again until the given condition remain TRUE.
Syn: - while (condition)
{
36 | P a g e
……….
………. Body of while loop
……….
Increment/decrement part;
}
Ex: -
int a=1;
while (a<=100)
{
System.out.println (+a);
a++;
}
3. do-while loop: It is also a looping statement, which is used to execute a set of statement again &
again until the given condition remains TRUE.
Syn: -
do
{
……….
……….
……….
Increment/decrement part;
} while (condition);
37 | P a g e
The basic difference between while-loop and do-while loop is that the body of do-while loop must
execute at least once time either the given condition is TRUE or FALSE. This is so because in this case
body appears before condition further execution of do-while loop depends on the condition.But the body
of for-loop and while-loop must be executed at feast one time when the given condition remains TRUE
at least one time. Otherwise, whole body is skipped by the control.
ARRAY
Array is a user-defined data type, which is used to store the homogenous types of values. In another
word, we can also say that it is also a variable, which can store more than one values of some data
type.
Syn: -
datatype v[] = new datatype [size];
Ex: -
Int a[] = new int [5];
Float b[] = new float [10];
Int []a = new int [5];
The “new” keyword initiates the array variable in memory i.e. it allocates the memory space for
array variable in memory. It also divides that memory space in different blocks according to given
size.
Like c/c++, it also provides a unique index number to each block, starts from zero (0).
a
0 1 2 3 4
Another way of declaring an Array
Syn: -
datatype v[]; //Declaration
38 | P a g e
v[]= new datatype [size]; //Instantiation
Ex: -
Int a[];
a = new int [5];
Declaration with Assignment
Syn: -
datatype v[] = {list of values};
Ex: -
Int a[] = { 1, 2, 3, 4, 5};
a
1 2 3 4 5
0 1 2 3 4
WAP to enter 10 numbers in an array and print them.
import java.io.DataInputStream;
class array
{
public static void main (String args[])
{
int a[]=new int[10];
int i;
DataInputStream obj = new DataInputStream(System.in);
try
{
for(i=0;i<10;i++)
{
System.out.print("\n ENTER NUMBER IN ARRAY: -");
a[i]=Integer.parseInt(obj.readLine());
}
System.out.print("\n ENTER OF ARRAY: -");
for (i=0;i<10;i++)
{
System.out.println(a[i]);
}
}
39 | P a g e
catch (Exception e)
{
}
}
}
TYPES OF ARRAY
Single Dimensional
Multi Dimensional
Ragged Array
Single Dimensional Array
When one dimension is mentioned with an array variable then it is known as single dimensional
array.
Syn: -
datatype v[] = new datatype [size];
The memory space is allocated by array variable name either horizontally or vertically. This space is
divided into different block according to the given size. Each block is assigned an index number,
starts from zero90).
Ex: -
Int a[] = new int [5];
0 1 2 3 4
To know the length of array
system.out.print (a. length); 5
ASSIGNMENT OF ONE ARRAY INTO ANOTHER
Unlike c/c++, JAVA provides the facility of assigning one array into another array.
Ex: -
int a [] = new int [5];
int b [] = a;
In this case the size of array “b” is automatic assigned as “a”.
int a [] = {1, 2, 3, 4, 5};
40 | P a g e
Multi Dimensional / Double Dimensional Array
When two dimensions are mentioned with an array variable then it is known as Double Dimensional
array.
Ex: -
Datatype v [][] = new datatype [size][size];
In this case, the first “size” stands for “row” value and the second “size” stands for “column” value.
So the memory space is divided into different “row” and “column” a/c to the given values.
Ex: -
Int a[][] = new int [3][3];
0 1 2
0
1
2
Each row and column is assigned an index number, starts from zero (0). And the value is assigned or
retrieved by the combination of row & column index number.
Assignment
a[0][2] = 40
a[2][1] = 50
To know the length
Ex: -
int a[][] = new int [3][4];
System.out.print (a. length); row number (3)
System.out.print (a[0].length); column number (4)
Assignment of One DDA To Another
Ex: -
int a[][] = new int [2][3];
0 1 2
0
41 | P a g e
40
b
1
so, the array “b” is also allocated the space same as “a”.
Ex: -
int a [][] = {{1, 2, 3,},{4, 5, 6}};
0 1 2
0
a
1
int b [][] = a;
0 1 2
0
b
1
42 | P a g e
1 2 3
1 2 3
MODULE-III
CLASS
“CLASS” is a user-define data type, which provides a unit under which we can kept the
variables and under which we can kept the variable and methods together.
The variables declared within class are known as Data member and the methods declared
within class are known as member method.
Class < class name>
{
friendly int m;
private int a; Data Members
protected float b;
public void f1 ()
{
- - - -
- - - - Member Method
- - - -
}
}
OBJECT
Object is also a variable, which is declared by the class name. It means, class name is used as a data
type to declare a variable i.e. objects. That’s why, class is known as used-defined data type.
43 | P a g e
When an object of any class is created, then the memory space is allocated by the object name and
then the member of that class reside within that object area. So we must have to create the object of
any class.
The syntax of declaring an object is as follows.
Class name object name = new class name ();
In this line, the object is declared as well as instantiated. It means, the above line can be break
down into two lines.
Class name object; //Declaration
Object name = new class name (); //Instantiation.
“New” keyword: - “new” keyword is used to instantiate the object in memory at run-time. It means,
it established the linking between class and object.
Let us suppose the following class
Class A
{
int a;
public void f1 ()
{
- - - -
- - - -
}
}
When we declare the “object” of class A like.
A obj;
Then it will take the memory space but that memory is now filled up with “NULL”. It means no any
members of “class A “reside within object area so we cannot use any members through this object.
Method Overloading
It is the feature of oops languages through which we can create more than one function having same
name but different parameters. Thus, when we create more than one function having same name but
different format arguments within same class then it is known as method overloading. And all such
function is called overloaded functions/methods.
44 | P a g e
The parameters (formed argument) may be different in overloaded functions cither in two ways.
Either the number of formal arguments must be different.
Or, the data type of formed arguments must be different.
Ex: -
Class A
{
public void f1 ()
{
- - - -
- - - -
}
public void f1 (int a)
{
- - - -
- - - -
}
public void f1 (int a)
{
- - - -
- - - -
}
public void f1 (float a)
{
- - - -
- - - -
}
public void f1 (int a float b)
{
- - - -
- - - -
}
public void f1 (float a int b)
{
45 | P a g e
- - - -
- - - -
}
Constructor
It is also a member method within class whose name is same as the class name. It means, a
function/method, which is created by the class name in public mode, is known as constructor.
Ex: -
Class A
{
public A () Constructor
{
- - - -
- - - -
}
}
Features of Constructor
Constructor name must be same as class name.
It must be created in friendly/public mode only.
It cannot return any value. So there is no any return type mentioned before constructor name.
Even “void” is also not used.
Constructor can receive the numbers. So, formal argument can be mentioned in any number
of any data type.
Constructor is activated automatically where an object of that class is initiated in memory.
So, it is not called explicitly like other member method.
Calling Of Constructor
Constructor is the first method within class, which is activated automatically after running the
program. It is called implicitly whenever an object of that class is initiated in memory. That is, when
the object is loaded into memory, constructor is activated. Generally constructor is used to initials the
data member automatically at run-time or to perform some certain action at run-time automatically.
Ex: -
Class A
{
public A()
Class M
{
public static void main( - - - -)
46 | P a g e
{
System.out.print(“\n HELLO”);
}
};
{
A obj1 = new A ();
A obj2 = new A ();
}
}
OUTPUT
Hello
Hello
Type of constructor
There are three type of constructor supported by JAVA.
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor : A constructor having no any formal argument is called Default
Constructor.
Ex: -
Class A
{
public A( ) Default Constructor
{
- - - -
- - - -
}
}
Simply creating the object of that class activates default Constructor.
Ex: -
; // Active Default Construe
2. Parameterized Constructor: A Constructor having some formal argument are called
Parameterized Constructor.
Ex: -
47 | P a g e
A obj = new A ()
Class A
{
public A (int a, int b) Parameterized Constructor
{
- - - -
- - - -
}
}
Passing the values with object at the time of its decollation activates parameterized Constructor.
3. Copy Constructor: It is also a type of parameterized Constructor, in which object is used as
formal argument of the same class. Copy Constructor is used to copy/assign the value of one object
into another.
Hence, the main difference between parameterized and copy constructor is that
parameterized constructor has simple variables as formal argument whereas copy constructor has an
object of same class as formal argument.
Ex: -
Class A
{
public A (int a) parameterized Constructor.
{
- - - -
- - - -
}
public A (A x) Copy Constructor
{
- - - -
- - - -
}
}
48 | P a g e
Copy Constructor is activated whenever we pass the object of same class within another object at the
time object creation.
Ex: -
A obj1 = new A (8); Activates parameterized Constructor
A obj12= new A (obj1); Activates Copy Constructor
Finalize () method
It is a destructor in JAVA. Destructor is mainly used to destroy the memory variables at the end of
the program. It is also executed automatically when our program would save the memory i.e. at the
end of the program. In another word, we can also say that when the object is saving the memory then
the destructor is automatically executed.
The class creates the main difference between C++ destructor is created by the class name and
followed by tilde (~) sign where as finalize () method is used as destructor in JAVA.
Ex: -
Class A
{
public:
finalize () Destructor
{
- - - -
- - - -
}
}
Class M
{
p.s.v.m ( - - - -)
{
A obj = new Acr
}
}
49 | P a g e
50 | P a g e
MODULE-IV
Advanced features of classes
Inheritance:
It is the most powerful and useful feature of oops through witch we can create owe or more than one
class from an existing class.A class from which another class is created is known as parent class
super class or base class and a class, which is created by another, class is known as child class, sub
class or derived class.
The syntax of deriving a class in JAVA is as follows.
Class <sub class name> extends <parent class name>
{
- - - -
- - - -
}
Ex: -
Class A
{
- - - -
- - - -
}
class B extends A
{
- - - -
- - - -
}
Hence “class B” is the child class of “class A”.
Feature of the Inheritance
The main feature of the inheritance is that the child class can use the protected as well as
public member of parent class within it. So, we can call the parent class member methods by the
51 | P a g e
object of child class outside the class. Hence, there is no need to create an object of parent class
separately.
Child class may also have some extra properties.
Class A
{
private int a;
protected int b;
public void f1 ()
{
- - - -
- - - -
}
}
class B extends A
{
public void f2 ()
{
a = 20;
b = 40;
}
}
Class M
{
p.s.v.m (- - - -)
{
B obj = new B ();
Obj.f1 ();
Obj.f2 ();
}
}
Memory Management
Type Of Inheritance
There are three types of inheritance supported by JAVA.
i. Single Inheritance
ii. Multilevel Inheritance
iii. Hierarchical Inheritance
i. Single Inheritance
In this case single Inheritance, there is one parent class and one child class.
Ex: -
Parent class
52 | P a g e
Class A
Int a
Int b
Void f1 ()
{
class B
int b
void f1 ()
{
- - -
}
void f2 ()
Class A
Derived form
Child class
Ex: -
Class A
{
- - - -
- - - -
}
class B extends A
{
- - - -
- - - -
}
In this case, the child class object can us the member of its parent class also.
ii. Multilevel Inheritance
In this case, a class is derived from this derived class and so on this type at inheritance is
known as Multilevel Inheritance.
Ex: -
Parent class
53 | P a g e
Class B
Class A
Class B
Intermediate Parent class
Child class
Ex: -
Class A
{
- - - -
- - - -
}
class B extends A
{
- - - -
- - - -
}
class C extends B
{
- - - -
- - - -
}
In this case, if we create an object of “class” then we can handle the member of all the three classes
through that object, become “class C” is indirectly linked with “class A” through “class B”.
iii. Hierarchical Inheritance
When more than class is derived from a class and again one or more than one class is derived
from any of the derived class when this type of inheritance is known as Hierarchical Inheritance.
Ex: -
54 | P a g e
Class C
Class A
Class B Class C Class D
Class E Class F
This inheritance automatically creates a “true” like structure. That’s why; it is given the name
Hierarchical Inheritance.
In this case, if we create an object of innermost child class then we can handle all the member of
above related parent classes.
INTERFACE
It is also a most useful feature of JAVA, which provides a unit like class, in which we can keep the
variables or methods. In another word, we can also say that interface is a class like entity which
provides a unit in which the variables and methods can be kept together.
Syn: -
Interface <interface name>
{
Data type list of variables return type method name ();
}
The main different between class and interface is that the methods of interface cannot be defined
within it can be declared only. Where as the method of class must be defined within the class.
All the variables defined within interface are “public” “static” & “final” by default. And the methods
within interface are “public” & “static” by default.
Ex: -
Interface int f1
{
Interface int f1
{
55 | P a g e
Int a = 10;
void f1 ();
}
By default Public static final int a = 10;
Public static void f1 ();
}
Implementing An Interface
As we know that the method of interface can not be defined within it. So, it must be implementing by
a class. That is, we implementing by a class. That is, we must establish the inheritance relation
between class and interface.
Hence, we must have to create a child class of interface by implementing it and override all the
methods of interface within the class.
The syntax of implementing a class by interface is as follows.
Syn: -
Class <class name> implements <interface name>
{
- - - -
- - - -
- - - -
}
Ex: -
Interface int f1
{
Int a = 10;
Void f1 ();
}
Class A implements int f1
{
Public void f1 ()
{
- - - -
- - - -
}}
calling
56 | P a g e
A obj = new A ();
Obj. f1 ();
Int f1 obj;
Obj = new A ();
Obj. f1 ();
If a class does not override the method of interface then that class must be declared as “Abstract”
class
Ex: -
Interface int f1
{
Public static void f1 ();
}
Abstract class A implements int f1
{
Public void f2 ()
{
- - - -
- - - -
}
}
PACKAGE: Package is a container of holding different classes and class is a container of holding
different methods. It is same as the concept of header file in C/C++.
When we need to use any pre-defined method in our program then we must have to use the
corresponding class and package in our program. There are two types of packages.
1. system package (API package)
2. user defined package
System package (API package): All the pre-define packages are known as system package
or API (Application Program Interface) package. They hold different pre-defined classes.
The list of system packages are as follows.
a. Java.lang: -Holds the standard input/output classes for printing types, strings, math function,
threads and exception. There are the classes that JAVA compiler itself user and therefore they
are automatically imported.
57 | P a g e
b. Java.util: -It holds the language utility classes such as vectors, hash tables, random number,
data etc.
c. Java.io: -It holds the standard input/output classes.
d. Java.awt: -It holds the classes for graphical user interface. It contain classes for window,
buttons, list, menus etc.
e. Java.net: -It holds classes for networking.
f. Java.applet: -It holds classes for creating and implementing applets.
g. Javax.swing: -It holds classes of different GUI controls.
Hence, we can say that all the system packages are kept either in two super package – “ java” OR
“javax”. So we use the following syntax to use any system package and its classes in our program.
Import super package. API package. Classname;
Or
Import super package. API package. * ;
Stands for all classes.
Ex: -
Import java. Lang. Math;
Import java. io. *;
Import java. Util. vector;
Import javax. swing. *;
User defined package
Like header file of C/C++, we can also create our package in java, in which we can define
any number of classes to use in any program like system packages.
These, a package created by user are known as user-defined package.
To add a class into package, write the following code.
58 | P a g e
Package <package name>
Public class <class name>
{
- - - -
- - - -
- - - -
}
Steps of creating a user-defined package
Following step are followed to create a user-defined package.
WORKING DIRECTORY
C:\jdk 1.3\bin>
Create a directory
Ex: -
C:\jdk 1.3\bin> md demo
Enter into this directory.
Ex: -
C:\jdk 1.3\bin> cd demo
C:\jdk 1.3\bin \ demo>
Open the editor and create “.java” source file to add a class into a package. It is shown as
follows.
Ex: -
C:\jdk 1.3\bin> EDIT
59 | P a g e
Package demo; Add. Java
Public class Add
{
Public void sum ()
{
Int a= 10, b = 20, c;
C = a + b;
System.out.print (“\n Sum = “ + c);
}
}
Note
Main class is not declared in packages. So, it can not be run, only compiled.
Compile this “Java” file.
Ex: -
C:\jdk 1.3\bin\ demo> cd . . .
C:\jdk 1.3\bin> javac demo\Add.java
C:\jdk 1.3\bin>
Create another “.java” surce file on the current directory. It has the main-method class.
Ex: -
C:\jdk 1.3\bin> EDIT
import demo. *; Dmain. Java
class Dmain
{
Public static void main (string args [])
{
Add obj = new Add ();
Obj. sum ();
}
}
Compile an run this “.Java” file.
Ex: -
60 | P a g e
C:\jdk 1.3\bin> javac Dmain .java
C:\jdk 1.3\bin> java Dmain
PROGRAMS RELATING JAVA
1. WAP to print a message MADE FOR EACH OTHER”.
61 | P a g e
class made
{
public static void main(String args[])
{
System.out.println("Made For Each Other");
}
}
2. WAP to print the sum of two numbersclass sum
{
public static void main(String args[])
{
int a=10,b=20,c;
c=a+b;
System.out.println("Sum of two number: -"+c);
}
}
3. WAP to pass one integer value, one float value and one character value from
command line and print them.class print
{
public static void main(String args[])
{
int a=0;
float f=0.0f;
char c='/0';
a=Integer.parseInt(args[0]);
f=Float.valueOf(args[1]).floatValue();
c=(args[2].charAt(0));
System.out.print ("\n Integer Value: - "+a);
System.out.print("\n Float Value: - "+f);
System.out.print("\n Character Value: - "+c);
}
62 | P a g e
}
4. WAP to input two values from command line and print their sum.class sum
{
public static void main(String args[])
{
int a=0,b=0,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
System.out.print("\n Sum Of Two Value: - "+c);
}
}
5. WAP to input two values from command line and swap them.class swapping
{
public static void main(String args[])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
System.out.print("\n Before swapping Value A: - "+a);
System.out.print("\n Before swapping Value B: - "+b);
c=a;
a=b;
b=c;
63 | P a g e
System.out.print("\n After swapping Value A: - "+a);
System.out.print("\n After swapping Value B : - "+b);
}
}
6. WAP to input a number from command line and check whether it is
palindrome or not.
class palindrome
{
public static void main(String args[])
{
int num,r=0,x,num1;
num=Integer.parseInt(args[0]);
num1=num;
while(num>0)
{
x=num%10;
num=num/10;
r=r*10+x;
}
if(r==num1)
{
System.out.println ("This is Palindrome");
}
else
{
System.out.println ("This is Not Palindrome");
}
}
}
64 | P a g e
7. WAP to input a number from command line and check it perfect square
number.class squre
{
public static void main(String args[])
{
int num,div=1,rem,q,c=0;
num=Integer.parseInt(args[0]);
while (div<=num)
{
rem=num%div;
q=num/div;
if(div==q&&rem==0)
{
System.out.println ("Number is Perfect Square");
c=1;
break;
}
div=div+1;
}
if(c==0)
{
System.out.println ("Number is Not Perfect Squre");
}
}
}
8. WAP to input a number and print its factorial in following format.
1 *2 * 3 *4 = 24public class fact
{
65 | P a g e
public static void main(String args[])
{
int a,c=1,i;
a=Integer.parseInt(args[0]);
for(i=1;i<=a;i++)
{
c=c*i;
System.out.print(i+"*");
}
System.out.print("="+c);
}
}
9. WAP to print the sum of all those numbers which are passed from command
line.class inputsum
{
public static void main(String args[])
{
int a,s=0,i;
for(i=0;i<args.length;i++)
{
a=Integer.parseInt(args[i]);
s=s+a;
}
System.out.print("\n Total Sum="+s);
}
}
10. WAP to input some number from command line and print the number of
arguments passed from command line and also print the greatest among all
number.
66 | P a g e
class grator
{
public static void main(String args[])
{
int num,i,a=0,b=0;
for(i=0;i<args.length;i++)
{
num=Integer.parseInt(args[i]);
if(a<num)
{
a=num;
}
}
b=args.length;
System.out.print("\n NUMBER OF ARGUMENTS="+b);
System.out.print("\n GREATOR NUMBER IS="+a);
}
}
11. WAP to input principal, reat & interest from command line and print the
simple interest.
Ex: - Si = p * r * t/100 = 200 * 5 * 2/100=200public class interest
{
public static void main(String args[])
{
int p,r,t,si=0;
p=Integer.parseInt(args[0]);
r=Integer.parseInt(args[1]);
t=Integer.parseInt(args[2]);
si=(p*r*t)/100;
System.out.println ("interest="+si);
}
}
67 | P a g e
12. WAP to solve the following expression.
1/L1+2/L2+3/L3+ - - - - -- n/Ln =
import java.io.DataInputStream;
class solve
{
public static void main (String args[])
{
int n,f=1,r=0,i,j;
DataInputStream in = new DataInputStream(System.in);