Ooc Notes Svit
Ooc Notes Svit
Ooc Notes Svit
Syllabus:
Class and Objects: Introduction, member functions and data, objects and
functions, objects and arrays, Namespaces, Nested classes, Constructors,
Destructors.
Beautiful thought:” You cannot change your future but, you can change your habits &
surely your habits will change your future”- Dr. APJ Abdul kalam.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 1
Object Oriented Concepts-Module 1 15CS45
Overview of C++
c++ is an extension of the C language, in that most C programs are also c++programs.
Most real world objects have internal parts (Data Members) and interfaces
Object:
An object is a collection of variables that hold the data and functions that operate
on the data.
The functions that operate on the data are called Member Functions.
In OOPs the data is tied more closely to the functions and does not allow the data
to flow freely around the entire program making the data more secure.
Compliers implementing OOP does not allow unauthorized functions to access the
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 2
Object Oriented Concepts-Module 1 15CS45
Only the associated functions can operate on the data and there is no change of
The main advantage of OOP is its capability to model real world problems.
Functions
Functions Functions
Communication
2. Classes
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Binding
8. Message passing
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 3
Object Oriented Concepts-Module 1 15CS45
Objects with similar properties and methods are grouped together to form
class.
Data abstraction
Abstraction refers to the act of representing essential features without
including the background details or explanation.
Ex: Let's take one real life example of a TV, which you can turn on and off,
change the channel, adjust the volume, and add external components such as
speakers, VCRs, and DVD players, BUT you do not know its internal details,
that is, you do not know how it receives signals over the air or through a
cable, how it translates them, and finally displays them on the screen.
int main( )
{
cout << "Hello C++" <<endl;
return 0;
}
Here, you don't need to understand how cout displays the text on the user's
screen. You need to only know the public interface and the underlying
Data encapsulation
Information hiding
Wrapping (combining) of data and functions into a single unit (class) is known
as data encapsulation.
Data is not accessible to the outside world, only those functions which are
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 4
Object Oriented Concepts-Module 1 15CS45
Inheritance
Acquiring qualities.
The new class that is formed is called derived class, child or sub class.
Derived class has all the features of the base class plus it has some extra
features also.
Polymorphism
The dictionary meaning of polymorphism is “having multiple forms”.
Binding
Binding means connecting the function call to the function code to be
Static binding means that the code associated with the function call is linked
Dynamic binding means that the code associated with the function call is
Message passing
Objects communicate with one another by sending and receiving information.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 5
Object Oriented Concepts-Module 1 15CS45
Advantages of OOPS
Data security
Reusability of existing code
Creating new data types
Abstraction
Less development time
Reduce complexity
Better productivity
Benefits of OOP
Reusability
Saving of development time and higher productivity
Data hiding
Multiple objects feature
Easy to partition the work in a project based on objects.
Upgrade from small to large systems
Message passing technique for interface.
Software complexity can be easily managed.
Applications of OOP
Real time systems
Simulation and modeling
Object oriented databases
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 6
Object Oriented Concepts-Module 1 15CS45
Hypertext, hypermedia
AI (Artificial Intelligence)
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAD/CAED system
Oriented Programming)
3. Procedures are being separated from Procedures are not separated from data,
together.
4. A piece of code uses the data to The data uses the piece of code to perform
5. Data is moved freely from one Data is hidden and can be accessed only by
parameters.
8. Debugging is the difficult as the code Debugging is easier even if the code size is
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 7
Object Oriented Concepts-Module 1 15CS45
Sl.No C C++
3. The data and functions are separate The data and functions are combined
inheritance etc.
equivalent C program
definitions
Since Cin and Cout are C++ objects, they are somewhat “Intelligent”.
They do not require the usual format strings and conversion specifications.
They do require the use of the stream extraction (>>) and insertion (<<) operators.
To get input from the keyboard we use the extraction operator and the object Cin.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 8
Object Oriented Concepts-Module 1 15CS45
The compiler figures out the type of the variable and reads in the appropriate type.
o Example:
#include<iostream.h>
Void main( )
{
int x;
float y;
cin>> x;
cin>>y;
}
To send output to the screen we use the insertion operator on the object Cout.
Syntax: Cout<<variable;
Compiler figures out the type of the object and prints it out appropriately.
Example:
#include<iostream.h>
void main( )
{
cout<<5;
cout<<4.1;
cout<< “string”;
cout<< ‘\n’;
}
Programs
#include<iostream.h>
void main( )
{
int a,b;
float k;
char name[30];
cout<< “Enter your name \n”;
cin>>name;
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 9
Object Oriented Concepts-Module 1 15CS45
Output:
Enter your name
Mahesh
Enter two integers and a Float
10
20
30.5
Thank you Mahesh, you entered
10, 20 and 30.5
#include<iostream.h>
int main( )
{
int i;
cout<< “this is output\n”;
cout<< “Enter a number”;
cin>>i;
cout<<i<< “Square is” << i*i<<”\n”;
return 0;
}
Output:
This is output
Enter a number 5
5 square is 25
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 10
Object Oriented Concepts-Module 1 15CS45
Variables
Variable are used in C++, where we need storage for any value, which will change in
program. Variable can be declared in multiple ways each with different memory
requirements and functioning. Variable is the name of memory location allocated by the
Variable must be declared before they are used. Usually it is preferred to declare
them at the starting of the program, but in C++ they can be declared in the middle
Example :
char c;
int i; // declaration
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 11
Object Oriented Concepts-Module 1 15CS45
i = 10; // initialization
If a variable is declared and not initialized by default it will hold a garbage value.
Also, if a variable is once declared and if try to declare it again, we will get a
int i,j;
i=10;
j=20;
int j=i+j; //compile time error, cannot redeclare a variable in same scope
Scope of Variables
All the variables have their area of functioning, and out of that boundary they don't hold
their value, this boundary is called scope of the variable. For most of the cases its
between the curly braces, in which variable is declared that a variable exists, not outside
Global Variables
Local variables
Global variables
Global variables are those, which are once declared and can be used throughout the
lifetime of the program by any class or any function. They must be declared outside the
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 12
Object Oriented Concepts-Module 1 15CS45
main() function. If only declared, they can be assigned different values at different time
in program lifetime. But even if they are declared and initialized at the same time outside
the main() function, then also they can be assigned any value at any point in the program.
include <iostream>
int main()
Local Variables
Local variables are the variables which exist only between the curly braces, in which its
declared. Outside that they are unavailable and leads to compile time error.
Example :
include <iostream>
int main()
int i=10;
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 13
Object Oriented Concepts-Module 1 15CS45
declaration.
#include<iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
return 0;
}
Output:
x = 20
ref = 30
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 14
Object Oriented Concepts-Module 1 15CS45
Functions in c++:
Definition: Dividing the program into modules, these modules are called as functions.
Where,
return_type:
Components of function:
Function definition
Return statement
Function call
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 15
Object Oriented Concepts-Module 1 15CS45
Example:
#include<iostream.h>
int a, b, c;
cin>>a>>b;
cout<<c<<endl;
Function prototype:
The number and types of the arguments that must be supplied in a call to the
function.
Function prototyping is one of the key improvements added to the C++ functions.
When a function is encountered, the compiler checks the function call with its
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 16
Object Oriented Concepts-Module 1 15CS45
It informs the compiler that the function max has 2 arguments of the type integer.
The function max( ) returns an integer value the compiler knows how many bytes to
Function definition:
The first line of the function definition is known as function declarator and is
The declarator and declaration must use the same function name, number of
{
if(x>y) //function body
return x;
else
return y;
}
Function call:
c= max (a, b) ;
Invokes the function max( ) with two integer parameters, executing the call
function body and after execution of the function body the control is resumed to
the statement following the function call. The max( ) returns the maximum of the
parameters a and b. the return value is assigned to the local variable c in main( ).
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 17
Object Oriented Concepts-Module 1 15CS45
Function parameters:
The parameters specified in the function call are known as actual parameters and
c=max(a,b);
Here a and b are actual parameters. The parameters x and y are formal
established between the actual and the formal parameters. In this case the value
Function return:
Functions can be grouped into two categories. Functions that do not have a return
and
the value returned by the function max( ) is assigned to the local variable c in main(
).
The return statement in a function need not be at the end of the function. It can
Argument passing:
Two types
1. Call by value
2. Call by reference
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 18
Object Oriented Concepts-Module 1 15CS45
Call by value:
The default mechanism of parameter passing( argument passing) is called call
by value.
Example 1:
#include<iostream.h>
void main( )
int a, b;
cin>>a>>b;
exchange(a,b);
int temp;
temp=x;
x=y;
y=temp;
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 19
Object Oriented Concepts-Module 1 15CS45
Example 2:
#include<iostream.h>
void main( )
int a, b;
cin>>a>>b;
sub(a, b);
getch( );
Example 3:
#include<iostream.h>
void main( )
temp=add(a);
cout<<temp<<”,”<<a;
int add(int a)
{
a=a+a;
return a;
}
Output: 20
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 20
Object Oriented Concepts-Module 1 15CS45
Call by reference:
We pass address of an argument to the formal parameters.
Example 1:
#include<iostream.h>
void exchange(int *x, int *y);
void main( )
{
int a, b;
cout<< “enter values for a and b”; //10, 20
cin>>a>>b;
exchange(&a,&b);
cout<<a<<b; //output: 20,10
}
void exchange(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
cout<<x<<y; // output: 20, 10
}
Example 2:
#include<iostream.h>
void main( )
{
int a=10, temp;
temp=add(&a);
cout<<temp<<”,”<<a;
getch();
}
int add(int *a)
{
a=*a+*a;
return a;
}
Output: 20
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 21
Object Oriented Concepts-Module 1 15CS45
Default arguments:
Example:
#include <iostream.h>
void main( )
{
add(1,2,3);
add(1,2);
add(1);
add( );
}
void add(int a, int b, int c)
{
cout<< a+b+c;
}
A default argument is checked for type at the time of declaration and evaluated at
the time of call.
We must add defaults from right to left.
We cannot provide a default value to a particular argument in the middle of an
argument list.
Example:
int mul (int i, int j=5, int k=10); //legal.
int mul (int i=5, int j); //illegal.
int mul (int i=0,int j, int k=10); //illegal.
int mul (int i=2, int j=5, int k=10); //legal.
Default arguments are useful in situations where some arguments always have the
same value.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 22
Object Oriented Concepts-Module 1 15CS45
Programming language is most popular language after C Programming language. C++ is first
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 23
Object Oriented Concepts-Module 1 15CS45
Actually this section can be considered as sub section for the global
declaration section.
Class declaration and all methods of that class are defined here
Main function:
Each and every C++ program always starts with main function.
This is entry point for all the function. Each and every method is called
Class specification:
A Class is way to bind(combine) the data and its associated functions together. it
When we define a class, we are creating a new abstract data type that can be
class class_name
{
access specifier: data
};
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 24
Object Oriented Concepts-Module 1 15CS45
The keyword class specifies that what follows is an abstract data of type
semicolon.
Public:
Protected:
Note:
By default data and member functions declared within a class are private.
Variables declared inside the class are called as data members and functions
are called as member functions. Only member functions can have access to data
The binding of functions and data together into a single class type variable is
referred as Encapsulation.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 25
Object Oriented Concepts-Module 1 15CS45
Example:
#include<iostream.h>
class student
{
private:
char name[10]; // private variables
int marks1,marks2;
public:
void getdata( ) // public function accessing private members
{
cout<<”enter name,marks in two subjects”;
cin>>name>>marks1>>marks2;
}
void display( ) // public function
{
cout<<”name:”<<name<<endl;
cout<<”marks”<<marks1<<endl<<marks2;
}
}; // end of class
void main( )
{
student obj1;
obj1.getdata( );
obj1.display( );
}
Output:
Enter name,marks in two subjects
Mahesh 25 24
Name: Mahesh
Marks 25 24
In the above program,class name is student,with private data members name,marks1 and
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 26
Object Oriented Concepts-Module 1 15CS45
Functions,the getdata( ) accepts name and marks in two subjects from user and display( )
Scope resolution operator links a class name with a member name in order to tell
Syntax to define the member functions outside the class using Scope resolution
operator:
Example:
#include<iostream.h>
class student
{
private:
char name[10]; // private variables
int marks1,marks2;
public:
void getdata( );
void display( );
};
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 27
Object Oriented Concepts-Module 1 15CS45
void main( )
{
student obj1;
obj1.getdata( );
obj1.display( );
}
Example:
#include<iostream.h>
int a=100; // declaring global variable
class x
{
int a;
public:
void f( )
{
a=20; // local variable
cout<<a; // prints value of a as 20
}
};
void main( )
{
x g;
g.f( ); // this function prints value of a(local variable) as 20
cout<<::a; // this statement prints value of a(global variable) as 100
}
In the above program,the statement ::a prints global variable value of a as 100.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 28
Object Oriented Concepts-Module 1 15CS45
#include<iostream.h>
class item
{
private:
int number,cost;
public:
void getdata(int a,int b );
void display( );
};
output:
number:10
cost:20
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 29
Object Oriented Concepts-Module 1 15CS45
Access members
Class members(variables(data) and functions) Can be accessed through an object
Private members can be accessed by the functions which belong to the same class.
Object_name.function_name(actual arguments);
#include<iostream.h>
class item
{
Private: int a;
public: int b;
};
void main( )
{
item i1,i2;
i1.a=10; // illegal private member cannot be accessed outside the class
i2.b=20;
cout<<i2.b; // this statement prints value of b as 20.
}
Note: private members cannot be accessed outside the class but public members can be
accessed.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 30
Object Oriented Concepts-Module 1 15CS45
Example: private members can be accessed by the functions which belongs to the
same class
#include<iostream.h>
class item
{
int a=10; // private member
public:
void display( )
{
cout<<a; // it prints a as10
}
};
void main( )
{
item i1;
i1.display( );
}
A member function can call another function directly, without using dot operator.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 31
Object Oriented Concepts-Module 1 15CS45
Example:
#include<iostream.h>
class item
{
private:
int cost,number;
public:
void getdata(int a,int b ) // defining function inside the class
{
number=a;
cost=b;
}
void display( )
{
cout<<”cost:”<<number<<endl;
cout<<”number:”<<cost<<endl;
}
};
void main( )
{
item i1;
i1.getdata(10,30 );
i1.display( );
}
output:
number:10
cost:30
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 32
Object Oriented Concepts-Module 1 15CS45
Two or more functions have the same names but different argument lists. The
arguments may differ in type or number, or both. However, the return types of
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define pi 3.14
class fn
{
public:
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int); //triangle
};
void fn::area(int a)
{
cout<<"Area of Circle:"<<pi*a*a;
}
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}
void main()
{
int ch;
int a,b,r;
clrscr();
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 33
Object Oriented Concepts-Module 1 15CS45
fn obj;
cout<<"\n\t\tFunction Overloading";
cout<<"\n1.Area of Circle\n2.Area of Rectangle\n3.Area of Triangle\n4.Exit\n:”;
cout<<”Enter your Choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter Radious of the Circle:";
cin>>r;
obj.area(r);
break;
case 2:
cout<<"Enter Sides of the Rectangle:";
cin>>a>>b;
obj.area(a,b);
break;
case 3:
cout<<"Enter Sides of the Triangle:";
cin>>a>>b;
obj.area(0.5,a,b);
break;
case 4:
exit(0);
}
getch();
}
permitted.
Only one copy of the data member is created for the entire class and is shared by
all the objects of class. no matter how many objects are created.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 34
Object Oriented Concepts-Module 1 15CS45
Static variables are normally used to maintain values common to entire class
objects.
Example
class item
{
static int count; // static data member
int number;
public:
void getdata( )
{
number=a;
count++;
}
void putdata( )
{
cout<<”count value”<<count<<endl;
}
};
void main( )
{
item i1,i2,i3; // count is initialized to zero
i1.putdata( );
i2.putdata( );
i3.putdata( );
i1.getdata( );
i2.getdata( );
i3.getdata( );
i1.putdata( ); // display count after reading data
i2.putdata( );
i3.putdata( );
}
Output:
Count value 0
Count value 0
Count value 0
Count value 3
Count value 3
Count value 3
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 35
Object Oriented Concepts-Module 1 15CS45
In the above program,the static variable count is initialized to zero when objects
times getdata( ) is called,so 3 times count value is created.all the 3 objects will have
count value as 3 because count variable is shared by all the objects,so all the last 3
statements in
i1 i2 i3
3
Count(common for all objects)
A static member function can have access to only other static members
A static member function can be called using the class name, instead of objects.
Syntax:
class_name : : function_name ;
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 36
Object Oriented Concepts-Module 1 15CS45
Example:
class item
{
int number;
static int count;
public:
void getdata(int a )
{
number=a;
count++;
}
static void putdata( )
{
cout<<”count value”<<count;
}
};
void main( )
{
item i1,i2;
i1.getdata(10);
i2.getdata(20);
item::putdata( );
// call static member function using class name with scope resolution operator.
}
Output:
Count value 2
In the above program, we have one static data member count, it is initialized to
zero, when first object is created, and one static member function putdata( ),it can
count as 2.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 37
Object Oriented Concepts-Module 1 15CS45
Inline functions:
First control will move from calling to called function. Then arguments will be
pushed on to the stack, then control will move back to the calling from called
function.
When a function is declared as inline, compiler replaces function call with function
code.
Example:
#include<iostream.h>
void main( )
{
cout<< max(10,20);
cout<<max(100,90);
getch( );
}
inline int max(int a, int b)
{
if(a>b)
return a;
else
return b;
}
Output: 20
100
Note: inline functions are functions consisting of one or two lines of code.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 38
Object Oriented Concepts-Module 1 15CS45
Arrays of Objects:
It is possible to have arrays of objects.
The syntax for declaring and using an object array is exactly the same as it is for
Program:
#include<iostream.h>
class c1
{
int i;
public:
void get_i(int j)
{
i=j;
}
void show( )
{
cout<<i<<endl;
}
};
void main( )
{
c1 obj[3]; // declared array of objects
for(int i=0;i<3;i++)
obj[i].get_i(i);
for(int i=0;i<3;i++)
obj[i].show( );
}
In the above program,we have declared object obj as an array of objects[i.e created 3
objects].
obj[i].get_i(i);
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 39
Object Oriented Concepts-Module 1 15CS45
invokes get_i( ) function 3 times,each time it stores value of i in the index of obj[i].that is
after the execution of complete loop,the array of object “obj” looks like this:
obj[i].show( );
output: 0
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 40
Object Oriented Concepts-Module 1 15CS45
Namespace
Namespace is a new concept introduced by the ANSI C++ standards committee. For using
identifiers it can be defined in the namespace scope as below.
Syntax:
In the above syntax "std" is the namespace where ANSI C++ standard class libraries are
defined. Even own namespaces can be defined.
Syntax:
namespace namespace_name
{
//Declaration of variables, functions, classes, etc.
}
Example :
#include <iostream.h>
using namespace std; namespace Own
{
int a=100;
}
int main()
{
cout << "Value of a is:: " << Own::a;
return 0;
}
Result :
In the above example, a name space "Own" is used to assign a value to a variable. To get
the value in the "main()" function the "::" operator is used.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 41
Object Oriented Concepts-Module 1 15CS45
Nested class is a class defined inside a class that can be used within the scope of the
class in which it is defined. In C++ nested classes are not given importance because of the
strong and flexible usage of inheritance. Its objects are accessed using "Nest::Display".
Example :
#include <iostream.h>
class Nest
{
public:
class Display
{
private:
int s;
public:
void sum( int a, int b)
{
s =a+b;
}
void show( )
{
cout << "\nSum of a and b is:: " << s;
}
}; //closing of inner class
}; //closing of outer class
void main()
{
Nest::Display x; // x is a object, objects are accessed using "Nest::Display".
x.sum(12, 10);
x.show();
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 42
Object Oriented Concepts-Module 1 15CS45
Constructors
object.
class A
{
int x;
public: A(); //Constructor
};
While defining a contructor you must remeber that the name of constructor will be
same as the name of the class, and contructors never have return type.
Constructors can be defined either inside the class definition or outside class
class A
{
int i;
public:
A(); //Constructor declared
};
Types of Constructors
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 43
Object Oriented Concepts-Module 1 15CS45
Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no
parameter.
Syntax :
class_name ()
{
Constructor Definition
}
Example :
class Cube
{
int side;
public: Cube() //constructor
{
side=10;
}
};
int main()
{
Cube c; //constructor is going to call
cout << c.side;
}
Output : 10
In this case, as soon as the object is created the constructor is called which initializes its
data members.
class Cube
{
int side;
};
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 44
Object Oriented Concepts-Module 1 15CS45
int main()
{
Cube c;
cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will initialize
the object data members to default value, that will be 0 in this case.
Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide
different values to data members of different objects, by passing the appropriate values
as argument.
Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 45
Object Oriented Concepts-Module 1 15CS45
By using parameterized construcor in above case, we have initialized 3 objects with user defined
values. We can have any number of parameters in a constructor.
copy constructor
an original existing object.It is used to initialize one object from another of the same
type.
Example :
#include<iostream>
using namespace std;
class copycon
{
int copy_a,copy_b; // Variable Declaration
public:
copycon(int x,int y)
{
//Constructor with Argument
copy_a=x;
copy_b=y; // Assign Values In Constructor
}
void Display()
{
cout<<"\nValues :"<< copy_a <<"\t"<< copy_b;
}
};
int main()
{
copycon obj(10,20);
copycon obj2=obj; //Copy Constructor
cout<<"\nI am Constructor";
obj.Display(); // Constructor invoked.
cout<<"\nI am copy Constructor";
obj2.Display();
return 0;
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 46
Object Oriented Concepts-Module 1 15CS45
Result :
I am Constructor
Values:10 20
I am Copy Constructor
Values:10 20
Constructor Overloading
Just like other member functions, constructors can also be overloaded. In fact
when you have both default and parameterized constructors defined in your class
you are having Overloaded Constructors, one with no parameter and other with
parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student
{
int rollno;
string name;
public:
Student(int x)
{
rollno=x;
name="None";
}
Student(int x, string str)
{
rollno=x ;
name=str ;
}
};
int main()
{
Student A(10);
Student B(11,"Ram");
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 47
Object Oriented Concepts-Module 1 15CS45
In above case we have defined two constructors with different parameters, hence
One more important thing, if you define any constructor explicitly, then the compiler will
not provide default constructor and you will have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a compile time error,
because we haven't defined default constructor, and compiler will not provide its default
Destructors
Destructor is a special class function which destroys the object as soon as the
scope of object ends. The destructor is called automatically by the compiler when
the object goes out of scope.
The syntax for destructor is same as that for the constructor, the class name is
used for the name of destructor, with a tilde ~ sign as prefix to it.
class A
{
public:
~A();
};
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 48
Object Oriented Concepts-Module 1 15CS45
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Questions
1. State the important features of object oriented programming. Compare object oriented
3. Write the general form of function. Explain different argument passing techniques with
example
4. Define function overloading. Write a C++ program to define three overloaded functions to
swap two integers, swap two floats and swap two doubles
5. Write a C++ program to overload the function area() with three overloaded function to find
parameterized constructor with default values for the class distance with data members
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 49
Object Oriented Concepts-Module 1 15CS45
10. What is parameterized constructor. Explain different ways of passing parameters to the
constructor
11. Implement a C++ program to find prime number between 200 and 500 using for loop.
13. What is class?how it is created? Write a c++ program to create a class called Employee
with data members name age and salary. Display atleast 5 employee information
14. What is nested class? What is its use? Explain with example.
15. What is static data member?explain with example. What is the use of static members
16. Write a class rectangle which contains data items length and breadth and member
functions setdata() getdata() displaydata(),area() to set length and breadth, to take user
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 50
Object Oriented Concepts-Module 2 10CS44
Syllabus:
Data types and other tokens: Boolean variables, int, long, char, operators,
arrays, white spaces, literals, assigning values; Creating and destroying
objects; Access specifiers.
Beautiful thought:” You cannot change your future but, you can change your habits & surely your habits will
change your future”- Dr. APJ Abdul kalam.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 1
Object Oriented Concepts-Module 2 10CS44
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 2
Object Oriented Concepts-Module 2 10CS44
Introduction: Java is a general purpose programming language. We can develop two types
of Java application. They are:
(1). Stand alone Java application.
(2). Web applets.
Stand alone Java application: Stand alone Java application are programs written in
Java to carry out certain tasks on a certain stand alone system. Executing a stand-alone
Java program contains two phases:
(a) Compiling source coded into bytecode using javac compiler.
(b) Executing the bytecodede program using Java interpreter.
Java applet: Applets are small Java program developed for Internet application. An
applet located on a distant computer can be downloaded via Internet and execute on local
computer.
Java Environment:
Java environment includes a large number of development tools and hundreds of classes and
methods. The Java development tools are part of the systems known as Java development kit (JDK)
and the classes and methods are part of the Java standard library known as Java standard Library
(JSL) also known as application program interface (API).
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 3
Object Oriented Concepts-Module 2 10CS44
Java Features:
(1) Compiled and Interpreted
(2) Architecture Neutral/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 extendible.
3. Object oriented
In java everything is an Object. Java can be easily extended since it is based on the
Object model.java is a pure object oriented language.
5. Distributed.
Java is designed for the distributed environment of the internet.java applications can
open and access remote objects on internet as easily as they can do in the local
system.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 4
Object Oriented Concepts-Module 2 10CS44
8. High performance
Because of the intermediate bytecode java language provides high performance
Java Development kits(java software:jdk1.6): Java development kit comes with a number of
Java development tools. They are:
(1) Appletviewer: Enables to run Java applet.
(2) javac: Java compiler.
(3) java : Java interpreter.
(4) javah : Produces header files for use with native methods.
(5) javap : Java disassembler.
(6) javadoc : Creates HTML documents for Java source code file.
(7) jdb : Java debugger which helps us to find the error.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 5
Object Oriented Concepts-Module 2 10CS44
Description:
(1) Class declaration: “class sampleone” declares a class, which is an object-
oriented construct. Sampleone is a Java identifier that specifies the
name of the class to be defined.
(2) Opening braces: Every class definition of Java starts with opening
braces and ends with matching one.
(3) The main line: the line “ public static void main(String args[]) “ defines a
method name main. Java application program must include this main. This
is the starting point of the interpreter from where it starts executing. A
Java program can have any number of classes but only one class will have
the main method.
(4) Public: This key word is an access specifier that declares the main
method as unprotected and therefore making it accessible to the all
other classes.
(5) Static: Static keyword defines the method as one that belongs to the
entire class and not for a particular object of the class. The main must
always be declared as static.
(6) Void: the type modifier void specifies that the method main does not
return any value.
(7) The println: It is a method of the object out of system class. It is
similar to the printf or cout of c or c++.
2. Save the above program with .java extension, here file name and class name should
be same, ex: Sampleone.java,
3. Open the command prompt and Compile the above program
javac Sampleone.java
From the above compilation the java compiler produces a bytecode(.class file)
4. Finally run the program through the interpreter
java Sapleone.java
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 6
Object Oriented Concepts-Module 2 10CS44
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 7
Object Oriented Concepts-Module 2 10CS44
More Examples:
Java program with multiple lines:
Example:
import java.lang.math;
class squreroot
{
public static void main(String args[])
{
double x = 5;
double y;
y = Math.sqrt(x);
System.out.println(“Y = “ + y);
}
}
Java command line arguments: Command line arguments are the parameters that
are supplied to the application program at the time when they are invoked. The main()
method of Java program will take the command line arguments as the parameter of the
args[ ] variable which is a string array.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 8
Object Oriented Concepts-Module 2 10CS44
Example:
Class Comlinetest
{
public static void main(String args[ ] )
{
int count, n = 0;
string str;
count = args.length;
System.out.println ( “ Number of arguments :” + count);
While ( n < count )
{
str = args[ n ];
n = n + 1;
System.out.println( n + “ : “ + str);
}
}
}
Run/Calling the program:
javac Comlinetest.java
java Comlinetest Java c cpp fortran
Output:
1 : Java
2:c
3 : cpp
4 : fortran
Java API:
Java standard library includes hundreds of classes and methods grouped into several
functional packages. Most commonly used packages are:
(a) Language support Package.
(b) Utilities packages.
(c) Input/output packages
(d) Networking packages
(e) AWT packages.
(f) Applet packages.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 9
Object Oriented Concepts-Module 2 10CS44
Java Tokens
Constants: Constants in Java refers to fixed value that do not change during the
execution of program. Java supported constants are given below:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 10
Object Oriented Concepts-Module 2 10CS44
Integers Type: Java provides four types of Integers. They are byte, sort, Int, long. All
these are sign, positive or negative.
Byte: The smallest integer type is byte. This is a signed 8-bit type that has a range
from –128 to 127. Bytes are useful for working with stream or data from a network or file.
They are also useful for working with raw binary data. A byte variable is declared with the
keyword “byte”.
byte b, c;
Short: Short is a signed 16-bit type. It has a range from –32767 to 32767. This
data type is most rarely used specially used in 16 bit computers. Short variables are
declared using the keyword short.
short a, b;
int: The most commonly used Integer type is int. It is signed 32 bit type has a
range from –2147483648 to 2147483648.
int a, b, c;
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 11
Object Oriented Concepts-Module 2 10CS44
long: Long is a 64 bit type and useful in all those occasions where Int is not enough.
The range of long is very large.
long a, b;
Floating point types: Floating point numbers are also known as real numbers are useful
when evaluating a expression that requires fractional precision. The two floating-point
data types are float and double.
float: The float type specifies a single precision value that uses 32-bit storage.
Float keyword is used to declare a floating point variable.
float a, b;
double: Double DataTips is declared with double keyword and uses 64-bit value.
Characters: The Java data type to store characters is char. char data type of Java uses
Unicode to represent characters. Unicode defines a fully international character set that
can have all the characters of human language. Java char is 16-bit type. The range is 0 to
65536.
Boolean: Java has a simple type called boolean for logical values. It can have only one of
two possible values. They are true or false.
Key Words: Java program is basically a collection of classes. A class is defined by a set of
declaration statements and methods containing executable statements. Most statement
contains an expression that contains the action carried out on data. The compiler
recognizes the tokens for building up the expression and statements. Smallest individual
units of programs are known as tokens. Java language includes five types of tokens. They
are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.
(1) Reserved keyword: Java language has 60 words as reserved keywords. They
implement specific feature of the language. The keywords combined with
operators and separators according to syntax build the Java language.
(2) Identifiers: Identifiers are programmer-designed token used for naming
classes methods variable, objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
5. Name of all public method starts with lowercase.
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 12
Object Oriented Concepts-Module 2 10CS44
6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only.
(3) Literals: Literals in Java are sequence of characters that represents constant
values to be stored in variables. Java language specifies five major types of
Literals. They are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
(4) Operators: An operator is a symbol that takes one or more arguments and
operates on them to produce an result.
(5) Separators: Separators are the symbols that indicates where group of code are
divided and arranged. Some of the operators are:
1. Parenthases()
2. Braces{ }
3. Brackets [ ]
4. Semicolon ;
5. Comma ,
6. Period .
Java character set: The smallest unit of Java language are its character set used to
write Java tokens. This character are defined by unicode character set that tries to
create character for a large number of character worldwide.
The Unicode is a 16-bit character coding system and currently supports 34,000
defined characters derived from 24 languages of worldwide.
Variables: A variable is an identifier that denotes a storage location used to store a data
value. A variable may have different value in the different phase of the program. To
declare one identifier as a variable there are certain rules. They are:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 13
Object Oriented Concepts-Module 2 10CS44
Variable-name = Value;
Initializing by read statements: Using read statements we can get the values in
the variable.
Scope of Variable: Java variable is classified into three types. They are
Class Variable: Class variable is global to the class and belongs to the entire set of
object that class creates. Only one memory location is created for each class
variable.
Local Variable: Variable declared inside the method are known as local variables.
Local variables are also can be declared with in program blocks. Program blocks can
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 14
Object Oriented Concepts-Module 2 10CS44
be nested. But the inner blocks cannot have same variable that the outer blocks are
having.
Arrays in Java
Array which stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for
declaring an array variable:
Example:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement, as shown below:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 15
Object Oriented Concepts-Module 2 10CS44
The array elements are accessed through the index. Array indices are 0-based; that is,
they start from 0 to arrayRefVar.length-1.
Example:
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 16
Object Oriented Concepts-Module 2 10CS44
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
JDK 1.5 introduced a new for loop known as for-each loop or enhanced for loop, which
enables you to traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 17
Object Oriented Concepts-Module 2 10CS44
1.9
2.9
3.4
3.5
Type Casting: It is often necessary to store a value of one type into the variable of
another type. In these situations the value that to be stored should be casted to
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
Widening Casting(Implicit)
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 18
Object Oriented Concepts-Module 2 10CS44
Example :
Output :
When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example :
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 19
Object Oriented Concepts-Module 2 10CS44
Output :
Java operators:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 20
Object Oriented Concepts-Module 2 10CS44
! : Logical NOT
Assignment Operator:
+= : Plus and assign to
-= : Minus and assign to
*= : Multiply and assign to.
/= : Divide and assign to.
%= : Mod and assign to.
= : Simple assign to.
Increment and decrement operator:
++ : Increment by One {Pre/Post)
-- : Decrement by one (pre/post)
Conditional Operator: Conditional operator is also known as ternary operator.
The conditional operator is :
Exp1 ? exp2 : exp3
Bitwise Operator: Bit wise operator manipulates the data at Bit level. These operators are
used for tasting the bits. The bit wise operators are:
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 21
Object Oriented Concepts-Module 2 10CS44
Special Operator:
Instanceof operator: The instanceof operator is a object refrence operator
that returns true if the object on the right hand side is an instance of the class given in
the left hand side. This operator allows us to determine whether the object belongs to the
particular class or not.
Person instanceof student
The expression is true if the person is a instance of class student.
Dot operator:The dot(.) operator is used to access the instance variable or
method of class object.
Example Programs
class arithmeticop
{
public static void main(String args[])
{
float a=20.5f;
float b=6.4f;
System.out.println("a = " + a);
System.out.println("b = " + b );
System.out.println("a + b = " + (a+b));
}
}
class Bitlogic
{
public static void main(String args[])
{
String binary[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"};
int a = 3;
int b = 6;
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a&b)|(a & ~b);
System.out.println("a or b :"+binary[c]);
System.out.println("a and b : "+binary[d]);
System.out.println("a xor b : "+binary[e]);
System.out.println("(~a&b)|(a & ~b) : "+binary[f]);
}
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 22
Object Oriented Concepts-Module 2 10CS44
Control Statements
Decision making statements:
1.Simple If statement:
The general form of single if statement is :
If ( test expression)
{
statement-Block;
}
statement-Blocks;
2. If- Else statement:
The general form of if-else statement is
If ( test expression)
{
statement-block1;
}
else
{
statement-block2
}
3. Else-if statement:
The general form of else-if statement is:
If ( test condition)
{
statement-block1;
}
else if(test expression2)
{
statement-block2;
}
else
{
statement block3;
}
4. Nested if – else statement:
The general form of nested if-else statement is:
If ( test condition)
{
if ( test condition)
{
statement block1;
}
else
{
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 23
Object Oriented Concepts-Module 2 10CS44
statement block2;
}
}
else
{
statement block 3
}
5. The switch statements:
The general form of switch statement is:
Switch ( expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
......
default:
default block;
break;
}
Loops In Java: In looping a sequence of statements are executed until a number of time or until
some condition for the loop is being satisfied. Any looping process includes following four steps:
(1) Setting an initialization for the counter.
(2) Execution of the statement in the loop
(3) Test the specified condition for the loop.
(4) Incrementing the counter.
Java includes three loops. They are:
(1) While loop:
The general structure of a while loop is:
Initialization
While (test condition)
{
body of the loop
}
(2) Do loop:
The general structure of a do loop is :
Initialization
do
{
Body of the loop;
}
while ( test condition);
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 24
Object Oriented Concepts-Module 2 10CS44
Continue statement: The “continue” statement will cause skipping some part of the loop.
Labeled loops: We can put a label for the loop. The label can be any Java recognized
keyword. The process of giving label is
Label-name : while (condition)
{
Body ;
}
class BreakTest
{
public static void main(String args[])
{
boolean t= true;
first:
{
second:
{
third:
{
System.out.println("Third stage");
if(t)
break second;
System.out.println("Third stage complete");
}
System.out.println("Second stage");
}
System.out.println("First stage");
}
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 25
Object Oriented Concepts-Module 2 10CS44
class ContinueTest
{
public static void main(String args[])
{
outer: for(int i=0;i<10;i++)
{
for(int j = 0; j<10;j++)
{
if(j>i)
{
System.out.println("\n");
continue outer;
}
System.out.print(" "+(i*j));
}
}
//System.out.println(" ");
}
}
class ReturnTest
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return");
if(t) return;
System.out.println("After return");
}
}
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 26
Object Oriented Concepts-Module 2 10CS44
Methods, Variables and Constructors that are declared private can only be
accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Using the private modifier is the main way that an object encapsulates itself and hides data
from the outside world.
A class, method, constructor, interface etc declared public can be accessed from
any other class. Therefore fields, methods, blocks declared inside a public class can be
accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the
public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by
its subclasses.
The protected access modifier cannot be applied to class and interfaces. Methods, fields
can be declared protected, however methods and fields in a interface cannot be declared
protected.
Default access modifier means we do not explicitly declare an access modifier for a
class, field, method, etc.A variable or method declared without any access control
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 27
Object Oriented Concepts-Module 2 10CS44
modifier is available to any other class in the same package. The fields in an interface are
implicitly public static final and the methods in an interface are by default public.
Advantages of JAVA:
• It is an open source, so users do not have to struggle with heavy license fees each year.
• Platform independent.
Questions
1. List & explain the characteristics features of java language. (10 Marks)
2. Briefly discuss about the java development tool kit. (07 Marks)
3. Explain the process of building and running java application program (05Marks).
4. Explain the following: a)JVM b)Type casting. (05Marks)
5. Class Example{
public static void main(String s[]) {
int a;
for(a=0;a<3;a++){
int b=-1;
System.out.println(“ “+b);
b=50;
System.out.println(“ “+b);
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 28
Object Oriented Concepts-Module 2 10CS44
}
}}
What is the output of the above code? If you insert another ‘int b’ outside the for loop
what is the output. (05Marks)
6. With example explain the working of >> and >>>. (06Marks)
7. What is the default package & default class in java? (02Marks)
8. Write a program to calculate the average among the elements {4, 5, 7, 8}, using for
each in java. How for each is different from for loop? (07Marks)
9. Briefly explain any six key consideration used for designing JAVA
language.(06Marks)
10. Discuss three OOP principles. (06Marks)
11. How compile once and run anywhere is implemented in JAVA language? (04Marks)
12. List down various operators available in JAVA language. (04Marks)
13. What is polymorphism?explain with an example. (04Marks)
14. Explain the different access specifiers in java, with examples. (06Marks)
15. a)int num,den;
if(den!=0&&num|den>2)
{
}
b)int num,den;
if(den!=0&num|den==2)
{
}
Compare & explain the above two snippets. (02Marks)
16. Write a note on object instantiation. (02Marks)
17. Explain type casting in JAVA
18. With a program explain break, continue and return keyword in java
Prepared by Nagamahesh BS, Asst.Professor, CSE, Sai Vidya Institute of Technology Page 29
Object Oriented Concepts 15CS/IS45
Syllabus:
Beautiful thought: “You have to grow from the inside out. None can teach you, none
can make you spiritual. There is no other teacher but your own soul.” ― Swami
Vivekananda
1. CLASSES:
Definition
A class is a template for an object, and defines the data fields and methods
of the object. The class methods provide access to manipulate the data fields. The
Example Program:
class RectangleArea
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(); //object creation
rect1.getdata(10,20); //calling methods using object with dot(.)
int area1=rect1.rectArea();
System.out.println("Area1="+area1);
}
}
class. Each object occupies some memory to hold its instance variables (i.e.
its state).
The above two statements declares an object rect1 and rect2 is of type
memory for an object and returns a refernce to it.in java all class objects
The Constructors:
All classes have constructors, whether you define one or not, because
Example:
// A simple constructor.
class MyClass
{
int x;
class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Parameterized Constructor:
same way that they are added to a method: just declare them
Example:
// A simple constructor.
class MyClass
{
int x;
class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
10 20
static keyword
static variable
class Counter
{
int count=0;//will get memory when instance is created
Counter()
{
count++;
System.out.println(count);
}
}
Class MyPgm
{
public static void main(String args[])
{
Counter c1=new Counter();
As we have mentioned above, static variable will get the memory only
once, if any object changes the value of the static variable, it will retain its
value.
class Counter
{
static int count=0;//will get memory only once and retain its value
Counter()
{
count++;
System.out.println(count);
}
}
Class MyPgm
{
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:1
2
3
static method
If you apply static keyword with any method, it is known as static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
Class MyPgm
{
public static void main(String args[])
{
//calling a method directly with class (without creation of object)
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
this keyword
Output: 0 null
0 null
In the above example, parameter (formal arguments) and instance variables are
same that is why we are using this keyword to distinguish between local variable and
instance variable.
Inner class
It has access to all variables and methods of Outer class and may refer to
them directly. But the reverse is not true, that is, Outer class cannot
directly access members of Inner class.
One more important thing to notice about an Inner class is that it can be
created only within the scope of Outer class. Java compiler generates an
error if any code outside Outer class attempts to instantiate Inner class.
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output:
Inside inner
Garbage Collection
longer needed and the memories occupied by the object are released. This
No, the Garbage Collection cannot be forced explicitly. We may request JVM for
garbage collection by calling System.gc() method. But this does not guarantee that
3. Increases memory efficiency and decreases the chances for memory leak.
finalize() method
Sometime an object will need to perform some specific task before it is destroyed
such as closing an open connection or releasing any resources held. To handle such
thread before collecting object. It’s the last chance for any object to perform
cleanup utility.
//finalize-code
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does
not guarantee that JVM will perform the garbage collection. It only requests the
JVM for garbage collection. This method is present in System and Runtime class.
Output :
Garbage Collected
Inheritance:
purpose.
The derived class is called as child class or the subclass or we can say
the extended class and the class from which we are deriving the
Types of Inheritance
2. Multilevel Inheritance
When a subclass is derived simply from its parent class then this
inheritance there is only a sub class and its parent class. It is also
Example
class A
{
int x;
int y;
int get(int p, int q)
{
x=p;
y=q;
return(0);
}
void Show()
{
System.out.println(x);
}
}
class B extends A
{
public static void main(String args[])
{
A a = new A();
a.get(5,6);
a.Show();
}
void display()
{
System.out.println("y"); //inherited “y” from class A
}
}
The syntax for creating a subclass is simple. At the beginning of your class
declaration, use the extends keyword, followed by the name of the class to
inherit from:
class A
{
Multilevel Inheritance
The derived class is called the subclass or child class for it's parent
class and this parent class works as the child class for it's just above
( parent ) class.
class A
{
int x;
int y;
int get(int p, int q)
{
x=p;
y=q;
return(0);
}
void Show()
{
System.out.println(x);
}
}
class B extends A
{
void Showb()
{
System.out.println("B");
}
}
class C extends B
{
void display()
{
System.out.println("C");
}
public static void main(String args[])
{
A a = new A();
a.get(5,6);
a.Show();
}
}
OUTPUT
5
Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a
single class is known as multiple inheritance. Java does not support multiple
interface.
Here you can derive a class from any number of base classes. Deriving a
class from more than one direct base class is called multiple inheritance.
super keyword
The super is java keyword. As the name suggest super is used to access the
The first use of keyword super is to access the hidden data variables of the
Example: Suppose class A is the super class that has two instance variables
as int a and float b. class B is the subclass that also contains its own data members
named a and b. then we can access the super class (class A) variables a and b inside
super.member;
subclass hides the members of a super class having the same name. The
Example:
class A
{
int a;
float b;
void Show()
{
System.out.println("b in super class: " + b);
}
}
class B extends A
{
int a;
float b;
B( int p, float q)
{
a = p;
super.b = q;
}
void Show()
{
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
}
class Mypgm
{
public static void main(String[] args)
{
B subobj = new B(1, 5);
subobj.Show();
}
}
OUTPUT
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Use of super to call super class constructor: The second use of the keyword
super in java is to call super class constructor in the subclass. This functionality can
super(param-list);
Here parameter list is the list of the parameter requires by the constructor
in the super class. super must be the first statement executed inside a
pass the empty parameter list. The following program illustrates the use of
Example:
class A
{
int a;
int b;
int c;
A(int p, int q, int r)
{
a=p;
b=q;
c=r;
}
}
class B extends A
{
int d;
B(int l, int m, int n, int o)
{
super(l,m,n);
d=o;
}
void Show()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class Mypgm
{
public static void main(String args[])
{
B b = new B(4,3,8,7);
b.Show();
}
}
OUTPUT
a=4
b=3
c=8
d=7
Method Overriding
method.
extend the super class. In the example class B is the sub class and class A
Example:
class A
{
int i;
A(int a, int b)
{
i = a+b;
}
void add()
{
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A
{
int j;
B(int a, int b, int c)
{
super(a, b);
j = a+b+c;
}
void add()
{
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding
{
public static void main(String args[])
{
B b = new B(10, 20, 30);
b.add();
}
}
OUTPUT
Sum of a and b is: 30
Sum of a, b and c is: 60
Method Overloading
Two or more methods have the same names but different argument lists.
The arguments may differ in type or number, or both. However, the return
Example:
class MethodOverloading
{
int add( int a,int b)
{
return(a+b);
}
float add(float a,float b)
{
return(a+b);
}
double add( int a, double b,double c)
{
return(a+b+c);
}
}
class MainClass
{
public static void main( String arr[] )
{
MethodOverloading mobj = new MethodOverloading ();
System.out.println(mobj.add(50,60));
System.out.println(mobj.add(3.5f,2.5f));
System.out.println(mobj.add(10,30.5,10.5));
}
}
OUTPUT
110
6.0
51.0
Abstract Class
Example Program:
}
double area()
{
System.out.println("Traingle Area");
return dim1*dim2/2;
}
}
class MyPgm
{
public static void main(String args[])
{
The final keyword in java is used to restrict the user. The final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
1) final variable: If you make any variable as final, you cannot change the value of
final variable(It will be constant).
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
}
Class MyPgm
{
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
Output:Compile Time Error
2) final method: If you make any method as final, you cannot override it.
Example:
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
}
Class MyPgm
{
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
3) final class:If you make any class as final, you cannot extend it.
Example:
Class MyPgm
{
Exception handling:
Introduction
execution and disrupts the normal flow of instructions. The abnormal event can be
programming language.
Concepts of Exceptions
program.
Example: If you divide a number by zero or open a file that does not exist, an
exception is raised.
In java, exceptions can be handled either by the java run-time system or by a user-
The unexpected situations that may occur during program execution are:
1. try:
2. catch.
3. throw.
4. throws.
5. finally.
Exceptions are handled using a try-catch-finally construct, which has the Syntax.
try
{
<code>
}
catch (<exception type1> <parameter1>)
{
// 0 or more<statements>
}
finally
{
// finally block<statements>
}
1. try Block: The java code that you think may produce an exception is placed
within a try block for a suitable catch block to handle the error.
If no exception occurs the execution proceeds with the finally block else it
will look for the matching catch block to handle the error.
Again if the matching catch handler is not found execution proceeds with
the finally block and the default exception handler throws an exception.
2. catch Block: Exceptions thrown during execution of the try block can be caught
and handled in a catch block. On exit from a catch block, normal execution
continues and the finally block is executed (Though the catch block throws an
exception).
3. finally Block: A finally block is always executed, regardless of the cause of exit
from the try block, or whether any catch block was executed. Generally finally
block is used for freeing resources, cleaning up, closing connections etc.
Example:
The following is an array is declared with 2 elements. Then the code tries to access
A try block can be followed by multiple catch blocks. The syntax for multiple catch
try
{
// code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any
statements.
class Multi_Catch
{
public static void main (String args [])
{
try
{
int a=args.length;
System.out.println(“a=”+a);
int b=50/a;
int c[]={1}
}
catch (ArithmeticException e)
{
System.out.println ("Division by zero");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index out of bound");
}
}
}
OUTPUT
Division by zero
array index out of bound
Just like the multiple catch blocks, we can also have multiple try blocks.
These try blocks may be written independently or we can nest the try blocks
within each other, i.e., keep one try-catch block within another try-block.
Syntax
try
{
// statements
// statements
try
{
// statements
// statements
}
catch (<exception_two> obj)
{
// statements
}
// statements
// statements
}
catch (<exception_two> obj)
{
// statements
}
Consider the following example in which you are accepting two numbers from
the command line. After that, the command line arguments, which are in the
If the numbers were not received properly in a number format, then during
goes to the next try block. Inside this second try-catch block the first
number is divided by the second number, and during the calculation if there
Example
class Nested_Try
{
public static void main (String args [ ] )
{
try
{
int a = Integer.parseInt (args [0]);
int b = Integer.parseInt (args [1]);
int quot = 0;
try
{
quot = a / b;
System.out.println(quot);
}
catch (ArithmeticException e)
{
System.out.println("divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect argument type");
}
}
}
The output of the program is: If the arguments are entered properly in the
command prompt like:
OUTPUT
java Nested_Try 2 4 6
4
OUTPUT
java Nested_Try 2 4 aa
Incorrect argument type
OUTPUT
java Nested_Try 2 4 0
divide by zero
throw Keyword
new NullPointerException("test");
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}
In the above example the avg() method throw an instance of ArithmeticException,
which is successfully handled using the catch statement.
throws Keyword
Any method capable of causing exceptions must list all the exceptions
possible during its execution, so that anyone calling that method gets a prior
knowledge about which exceptions to handle. A method can do so by using
the throws keyword.
Syntax :
NOTE : It is necessary for all exceptions, except the exceptions of type Error and
RuntimeException, or any of their subclass.
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
finally
The finally clause is written with the try-catch statement. It is guaranteed
Syntax
try
{
// statements
}
Take a look at the following example which has a catch and a finally block.
arithmetic error like divide-by-zero. After executing the catch block the
finally is also executed and you get the output for both the blocks.
Example:
class Finally_Block
{
static void division ( )
{
try
{
int num = 34, den = 0;
int quot = num / den;
}
catch(ArithmeticException e)
{
System.out.println ("Divide by zero");
}
finally
{
System.out.println ("In the finally block");
}
}
class Mypgm
{
public static void main(String args[])
{
OUTPUT
Divide by zero
In the finally block
Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type
automatically available.
Java defines several other types of exceptions that relate to its various class
Exception Description
Exception Description
Here you can also define your own exception classes by extending Exception.
These exception can represents specific runtime condition of course you will
have to throw them yourself, but once thrown they will behave just like
ordinary exceptions.
When you define your own exception classes, choose the ancestor carefully.
Most custom exception will be part of the official design and thus checked,
return msg;
}
}
class test
{
public static void main(String args[])
{
test t = new test();
t.dd();
}
public void add()
{
try
{
int i=0;
if( i<40)
throw new MyException();
}
catch(MyException ee1)
{
System.out.println("Result:"+ee1);
}
}
}
OUTPUT
Result: You have Passed
Chained Exception
Chained exceptions are the exceptions which occur one after another i.e.
chaining exceptions.
handling the exception, which occur one after another i.e. most of the time
exception.
chained exceptions help the programmer to know when one exception causes
another.
Throwable initCause(Throwable)
Throwable(Throwable)
Throwable(String, Throwable)
Throwable getCause()
Packages in JAVA
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Access Modifiers/Specifiers
1. private
2. default
3. protected
4. public
The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Interface in java
only abstract methods in the java interface does not contain method body.
Interface fields are public, static and final by default, and methods are
There are mainly three reasons to use interface. They are given below.
As shown in the figure given below, a class extends another class, an interface
Example 1
In this example, Printable interface has only one method, its implementation is
provided in the Pgm1 class.
interface printable
{
void print();
}
class IntefacePgm1
{
public static void main(String args[])
{
Pgm1 obj = new Pgm1 ();
obj.print();
}
}
Output:
Hello
Example 2
In this example, Drawable interface has only one method. Its implementation is
And, it is used by someone else. The implementation part is hidden by the user
interface Drawable
{
void draw();
}
//Implementation: by second user
d.draw();
}
}
Output:
drawing circle
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
Class InterfaceDemo
{
public static void main(String args[])
{
Pgm2 obj = new Pgm2 ();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
Example
interface Printable
{
void print();
}
interface Showable
{
void print();
}
Output:
Hello
As you can see in the above example, Printable and Showable interface have
so there is no ambiguity.
Interface inheritance
interface Printable
{
void print();
}
Class InterfaceDemo2
{
public static void main(String args[])
{
InterfacePgm2 obj = new InterfacePgm2 ();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
}
}
class MyPgm
{
stackDemo.pop();
stackDemo.push(23);
stackDemo.push(2);
stackDemo.push(73);
stackDemo.push(21);
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
}
Output
Questions
13. Write a java program to find the distance between two points
whose coordinates are given. The coordinates can be 2-
dimensional or 3-dimensional (for comparing the distance
between 2D and a 3D point, the 3D point, the 3D x and y
components must be divided by z). Demonstrate method
overriding in this program. (May-2007)10 marks
14. What is an interface? Write a program to illustrate multiple
inheritance using interfaces. (Jan-2010) 8Marks
15. Explain packages in java.
16. What are access specifiers? Explain with an example.
17. With an example explain static keyword in java.
18. Why java is not support concept of multiple inheritance?
Justify with an example program.
19. Write a short note on:
1. this keyword
2. super keyword
3. final keyword
4. abstract
20. Illustrate constructors with an example program
MODULE:IV
Java’s multithreading system is built upon the Thread class, its methods, and its
companion interface, Runnable.
The Thread class defines several methods that help manage threads (shown below)
When a Java program starts up, one thread begins running immediately. This is usually called the
main thread of your program, because it is the one that is executed when your program begins.
The main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• Often, it must be the last thread to finish execution because it performs various shutdown
actions.
Although the main thread is created automatically when your program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread. Its general form is
shown here:
static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you have a reference to
the main thread, you can control it just like any other thread.
Example:
In this program, a reference to the current thread (the main thread, in this case) is
obtained by calling currentThread( ), and this reference is stored in the local variable t.
Next, the program displays information about the thread. The program then calls
setName( ) to change the internal name of the thread. Information about the thread is
then redisplayed.
Next, a loop counts down from five, pausing one second between each line.
The pause is accomplished by the sleep( ) method. The argument to sleep( ) specifies the
delay period in milliseconds.
Output:
These displays, in order: the name of the thread, its priority, and the name of its group. By
default, the name of the main thread is main. Its priority is 5, which is the default value, and
main is also the name of the group of threads to which this thread belongs.
The general form of sleep() is:
The number of milliseconds to suspend is specified in milliseconds. This method may throw an
InterruptedException.
Creating a Thread
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable interface.
You can construct a thread on any object that implements Runnable. To implement Runnable, a
class need only implement a single method called run( ), which is declared like this:
public void run( )
run( ) establishes the entry point for another, concurrent thread of execution within your
program. This thread will end when run( ) returns.
Thread defines several constructors.
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the Runnable interface.
This defines where execution of the thread will begin. The name of the new thread is specified
by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which
is declared within Thread. In essence, start( ) executes a call to run( ). The start( ) method is
shown here:
void start( )
Example:
Next, start( ) is called, which starts the thread of execution beginning at the run( ) method. This
causes the child thread’s for loop to begin. After calling start( ), NewThread’s constructor
returns to main( ). When the main thread resumes, it enters its for loop. Both threads continue
running, sharing the CPU, until their loops finish.
Output:
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run( ) method, which is
the entry point for the new thread. It must also call start( ) to begin execution of the new thread.
Example:
The child thread is created by instantiating an object of NewThread, which is derived from
Thread.
Notice the call to super( ) inside NewThread. This invokes the following form of the Thread
constructor:
public Thread(String threadName)
Here, threadName specifies the name of the thread.
Creating Multiple Threads
For example, the following program creates three child threads:
As you can see, once started, all three child threads share the CPU. Notice the call to
sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and ensures that it
will finish last.
Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Priorities
Thread priorities are used by the thread scheduler to decide when each thread should be allowed
to run. In theory, higher-priority threads get more CPU time than lower-priority threads. In
practice, the amount of CPU time that a thread gets often depends on several factors besides its
priority.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
This is its general form:
final void setPriority(int level)
Here, level specifies the new priority setting for the calling thread. The value of level must be
within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and
10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is
currently 5. These priorities are defined as static final variables within Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:
final int getPriority( )
The following example demonstrates two threads at different priorities, One thread is set two
levels above the normal priority, as defined by Thread.NORM_
PRIORITY, and the other is set to two levels below it. The threads are started and allowed to
run for ten seconds. Each thread executes a loop, counting the number of iterations. After ten
seconds, the main thread stops both threads. The number of times that each thread madeit
through the loop is then displayed.
Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process by which this is achieved is
called synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an
object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at
a given time. When a thread acquires a lock, it is said to have entered the monitor. All other
threads attempting to enter the locked monitor will be suspended until the first thread exits the
monitor. These other threads are said to be waiting for the monitor.
Using Synchronized Methods
To enter an object’s monitor, just call a method that has been modified with the synchronized
keyword. While a thread is inside a synchronized method, all other threads that try to call it (or
any other synchronized method) on the same instance have to wait. To exit the monitor and
relinquish control of the object to the next waiting thread, the owner of the monitor simply
returns from the synchronized method.
The following program has three simple classes. The first one, Callme, has a single method
named call( ). The call( ) method takes a String parameter called msg. This method tries to print
the msg string inside of square brackets. The interesting thing to notice is that after call( ) prints
the opening bracket and the msg string, it calls Thread.sleep(1000), which pauses the current
thread for one second.
The constructor of the next class, Caller, takes a reference to an instance of the Callme class and
a String, which are stored in target and msg, respectively. The constructor also creates a new
thread that will call this object’s run( ) method. The thread is started immediately. The run( )
method of Caller calls the call( ) method on the target instance of Callme, passing in the msg
string. Finally, the Synch class starts by creating a single instance of Callme, and three instances
of Caller, each with a unique message string. The same instance of Callme is passed to each
Caller.
As you can see, by calling sleep( ), the call( ) method allows execution to switch to another
thread. This results in the mixed-up output of the three message strings. In this program, nothing
exists to stop all three threads from calling the same method, on the same object, at the same
time. This is known as a race condition, because the three threads are racing each other to
complete the method.
To fix the preceding program, you must serialize access to call( ). That is, you must restrict its
access to only one thread at a time. To do this, you simply need to precede call( )’s definition
with the keyword synchronized, as shown here:
class Callme {
synchronized void call(String msg) {
...
After
synchronized has been added to call( ), the output of the program is as follows:
[Hello]
[Synchronized]
[World]
The synchronized Statement
You simply put calls to the methods defined by this class inside a synchronized block.
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized.
Here is an alternative version of the preceding example, using a synchronized block within the
run( ) method:
Interthread Communication
Java supports interprocess communication mechanism via the wait( ), notify( ), and notifyAll( )
methods.
• wait( ) tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the
threads will be granted access.
These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
The following sample program that incorrectly implements a simple form of the producer/
consumer problem. It consists of four classes: Q, the queue that you’re trying to synchronize;
Producer, the threaded object that is producing queue entries; Consumer, the threaded object
that is consuming queue entries; and PC, the tiny class that creates the single Q, Producer, and
Consumer.
Although the put( ) and get( ) methods on Q are synchronized, nothing stops the producer from
overrunning the consumer, nor will anything stop the consumer from consuming the same queue
value twice. Thus, you get the erroneous output shown here.
Put: 1
Got: 1
Got: 1
Got: 1
Got: 1
Got: 1
Put: 2
Put: 3
Put: 4
Put: 5
Put: 6
Put: 7
Got: 7
As you can see, after the producer put 1, the consumer started and got the same 1 five times in a
row. Then, the producer resumed and produced 2 through 7 without letting the consumer have a
chance to consume them.
The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both
directions, as shown here:
Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies
you that some data is ready. When this happens, execution inside get( ) resumes. After the data
has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the
queue. Inside put( ), wait( ) suspends execution until the Consumer has removed the item from
the queue. When execution resumes, the next item of data is put in the queue, and notify( ) is
called. This tells the Consumer that it should now remove it.
Here is some output from this program:
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Event Handling
Event Classes
ActionEvent Class
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
ActionEvent has these three constructors:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
Here, src is a reference to the object that generated this event. The type of the event is
specified by type, and its command string is cmd. The argument modifiers indicates
which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event
was generated. The when parameter specifies when the event occurred.
You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:
String getActionCommand( )
The getModifiers( ) method returns a value that indicates which modifier keys (ALT,
CTRL, META, and/or SHIFT) were pressed when the event was generated. Its form is
shown here:
int getModifiers( )
The method getWhen( ) returns the time at which the event took place. This is called the
event’s timestamp. The getWhen( ) method is shown here:
long getWhen( )
AdjustmentEvent Class
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment
events.
AdjustmentEvent constructor:
AdjustmentEvent(Adjustable src, int id, int type, int data)
Here, src is a reference to the object that generated this event. The id specifies the event.
The type of the adjustment is specified by type, and its associated data is data.
ComponentEvent Class
A ComponentEvent is generated when the size, position, or visibility of a component is
changed.
There are four types of component events.
You can obtain a reference to the container that generated this event by using the
getContainer( ) method, shown here:
Container getContainer( )
The getChild( ) method returns a reference to the component that was added to or
removed from the container. Its general form is shown here:
Component getChild( )
FocusEvent Class
A FocusEvent is generated when a component gains or loses input focus. These events
are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.
FocusEvent is a subclass of ComponentEvent and has these constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component other)
Here, src is a reference to the component that generated this event. The type of the event
is specified by type. The argument temporaryFlag is set to true if the focus event is
temporary. Otherwise, it is set to false.
You can determine the other component by calling getOppositeComponent( ), shown
here:
Component getOppositeComponent( )
The opposite component is returned.
The isTemporary( ) method indicates if this focus change is temporary. Its form is
shown here:
boolean isTemporary( )
The method returns true if the change is temporary. Otherwise, it returns false.
InputEvent Class
It is the superclass for component input events.
Its subclasses are KeyEvent and MouseEvent.
InputEvent defines several integer constants that represent any modifiers, such as the
control key being pressed, that might be associated with the event.
To test if a modifier was pressed at the time an event is generated, use the isAltDown( ),
isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods.
The forms of these methods are shown here:
boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
You can obtain a value that contains all of the original modifier flags by calling the
getModifiers( ) method. It is shown here:
int getModifiers( )
ItemEvent Class
An ItemEvent is generated when a check box or a list item is clicked or when a
checkable menu item is selected or deselected.
There are two types of item events, which are identified by the following integer
constants:
MouseEvent Class
There are eight types of mouse events.
MouseWheelEvent Class
The MouseWheelEvent class encapsulates a mouse wheel event. It is a subclass of
MouseEvent.
MouseWheelEvent defines these two integer constants:
getWindow( ). It returns the Window object that generated the event. Its general form is
shown here:
Window getWindow( )
Sources of Events
ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event
occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
AdjustmentListener Interface
This interface defines the adjustmentValueChanged( ) method that is invoked when an
adjustment event occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)
The ComponentListener Interface
This interface defines four methods that are invoked when a component is resized, moved,
shown, or hidden. Their general forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
The ContainerListener Interface
This interface contains two methods. When a component is added to a container,
componentAdded( ) is invoked. When a component is removed from a container,
componentRemoved( ) is invoked. Their general forms are shown here:
void componentAdded(ContainerEvent ce)
Each time the button is released, the word “Up” is shown. If a button is clicked, the
message “Mouse clicked” is displayed in the upperleft corner of the applet display area.
It displays the current coordinates of the mouse in the applet’s status window. Each time
a button is pressed, the word “Down” is displayed at the location of the mouse pointer.
Each time the button is released, the word “Up” is shown. If a button is clicked, the
message “Mouse clicked” is displayed in the upperleft corner of the applet display area.
The MouseEvents class extends Applet and implements both the MouseListener and
MouseMotionListener interfaces.
Inside init( ), the applet registers itself as a listener for mouse events. This is done by
using addMouseListener( ) and addMouseMotionListener( ), which, as mentioned, are
members of Component. They are shown here:
void addMouseListener(MouseListener ml)
void addMouseMotionListener(MouseMotionListener mml)
msg += ke.getKeyChar();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
Adapter Classes
An adapter class provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If you
were interested in only mouse drag events, then you could simply extend MouseMotionAdapter
and override mouseDragged( ). The empty implementation of mouseMoved( ) would handle the
mouse motion events for you.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
Inner Classes
An inner class is a class defined within another class, or even within an expression.
// Inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
}
}
}
Syllabus:
Beautiful thought: “You have to grow from the inside out. None can teach you, none
can make you spiritual. There is no other teacher but your own soul.” ― Swami
Vivekananda
APPLET
page. When you use a Java technology enabled browser to view a page that
This type of applet has been widely available since java was first created.
Applet Basics
The reason people are excited about Java as more than just another OOP
Hello World isn't a very interactive program, but let's look at a webbed
version.
import java.applet.Applet;
import java.awt.Graphics;
OUTPUT
<html>
<head>
<title> hello world </title>
</head>
<body>
This is the applet:<P>
<applet code="HelloWorldApplet" width="150" height="50">
</applet>
</body>
</html>
OUTPUT
An applet is a small program that is intended not to be run on its own, but
The Applet class must be the super class of any applet that is to be
embedded in a Web page or viewed by the Java Applet Viewer. The Applet
Method Summary
Void Called by the browser or applet viewer to inform this
destroy() applet that it is being reclaimed and that it should
destroy any resources that it has allocated.
AccessibleContext Gets the AccessibleContext associated with this
getAccessibleContext() Applet.
AppletContext Determines this applet's context, which allows the
getAppletContext() applet to query and affect the environment in which it
runs.
String
Returns information about this applet.
getAppletInfo()
AudioClip Returns the AudioClip object specified by the URL
getAudioClip(URL url) argument.
AudioClip Returns the AudioClip object specified by the URL and
getAudioClip(URL url, name arguments.
String name)
URL
Gets the base URL.
getCodeBase()
URL Returns an absolute URL naming the directory of the
getDocumentBase() document in which the applet is embedded.
Image Returns an Image object that can then be painted on
getImage(URL url) the screen.
Image
Returns an Image object that can then be painted on
getImage(URL url,
the screen.
String name)
Locale
Gets the Locale for the applet, if it has been set.
getLocale()
String Returns the value of the named parameter in the
getParameter(String name) HTML tag.
String[][] Returns information about the parameters than are
getParameterInfo() understood by this applet.
Void Called by the browser or applet viewer to inform this
init() applet that it has been loaded into the system.
Boolean
Determines if this applet is active.
isActive()
static AudioClip
Get an audio clip from the given URL.
newAudioClip(URL url)
Void
Plays the audio clip at the specified absolute URL.
play(URL url)
Void
Plays the audio clip given the URL and a specifier that
play(URL url, String name)
is relative to it.
Void
Requests that this applet be resized.
resize(Dimension d)
Void
resize(int width, Requests that this applet be resized.
int height)
Void
Sets this applet's stub.
setStub(AppletStub stub)
Void Requests that the argument string be displayed in the
Applet Architecture
An applet is a window-based program, its architecture different from the
The AWT notifies the applet about an event by calling event handler
2. User initiates interaction with an Applet (and not the other way
around)
An Applet Skelton
// An Applet skeleton.
import java.awt.*;
import javax.swing.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start()
{
// start or resume execution
}
OUTPUT
It is important to understand the order in which the various methods shown in the
skeleton are called. When an applet begins, the AWT calls the following
initialization methods, in
this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
1. init( )
The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your
applet.
2. start( )
applet after it has been stopped. Whereas init( ) is called once—the first time an
applet is loaded start( ) is called each time an applet’s HTML document is displayed
onscreen. So, if a user leaves a web page and comes back, the applet resumes
execution at start( ).
3. paint( )
The paint( ) method is called each time your applet’s output must be
redrawn. paint( ) is also called when the applet begins execution. Whatever the
cause, whenever the applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter
will contain the graphics context, which describes the graphics environment in
which the applet is running. This context is used whenever output to the applet is
required.
4. stop( )
The stop( ) method is called when a web browser leaves the HTML document
containing the applet when it goes to another page, for example. When stop( ) is
called, the applet is probably running. You should use stop( ) to suspend threads
that don’t need to run when the applet is not visible. You can restart them when
5. destroy( )
The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free
up any resources the applet may be using. The stop( ) method is always called
before destroy().
import java.applet.Applet;
import java.awt.Graphics;
this is a member of the Graphics class, this drawstring is called from within
general form of is
The msg indicates that string to be output beginning at x,y. in java window
to set the foreground color for example the color in which text is shown use
The newColor specifies that new color. The class Color defines the constant shown
setBackround(Color.cyan);
setForeground(Color.red)
Example Program:
/* This Applet sets the foreground and background colors and out puts a string. */
import java.applet.*;
import java.awt.*;
OUTPUT:
Requesting repainting;
The repaint() method is defined by the AWT. It causes the AWT run time
needs to output a string, it can store this string in a variable and then call
repaint(). Inside paint(), you can output the string using drawstring().
void repaint()
void repaint()
This specifies a region that will be repainted. the integers left, top, width and
height are in pixels. You save time by specifying a region to repaint instead of the
whole window.
soon. However, if your system is slow or busy, update() might not be called
your task requires consistent update time, like in animation, then use the above two
If the user has chosen to show the Status Bar in their browser then
The showStatus() method would do it for this applet, if the applet was
running in a browser.
Example
import java.awt.*;
import java.applet.*;
import java.awt.Graphics;
}
public void paint(Graphics g)
{
g.drawString("Hi this is in the applet window",10,20);
showStatus("shown in the status window");
}
}
OUTPUT
An applet viewer will execute each APPLET tag that it finds in a separate
window, while web browsers like Netscape Navigator, Internet Explorer, and
The syntax for the standard APPLET tag is shown here. Bracketed items are
optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
CODEBASE: CODEBASE is an optional attribute that specifies the base URL of the
applet code, which is the directory that will be searched for the applet’s
CODE: CODE is a required attribute that gives the name of the file containing your
applet’s compiled .class file. This file is relative to the code base URL of the
applet, which is the directory that the HTML file was in or the directory indicated
by CODEBASE if set.
ALT The ALT tag is an optional attribute used to specify a short text message that
should be displayed if the browser understands the APPLET tag but can’t currently
run Java applets. This is distinct from the alternate HTML you provide for
THEAVA
WIDTH AND HEIGHT: WIDTH and HEIGHT are required attributes that give
ALIGN: ALIGN is an optional attribute that specifies the alignment of the applet.
This attribute is treated the same as the HTML IMG tag with these possible
VSPACE AND HSPACE: These attributes are optional. VSPACE specifies the
space, in pixels, above and below the applet. HSPACE specifies the space, in pixels,
on each side of the applet. They’re treated the same as the IMG tag’s VSPACE and
HSPACE attributes.
PARAM NAME AND VALUE: The PARAM tag allows you to specify appletspecific
getParameter( ) method.
between the opening and closing APPLET tags. Inside the applet, you read
the values passed through the PARAM tags with the getParameter() method
The program below demonstrates this with a generic string drawing applet. The
Example:
import java.applet.*;
import java.awt.*;
public class DrawStringApplet extends Applet
{
private String defaultMessage = "Hello!";
inputFromPage = defaultMessage;
You also need an HTML file that references your applet. The following simple HTML
file will do:
<HTML>
<HEAD>
<TITLE> Draw String </TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="DrawStringApplet" width="300" height="50">
<PARAM name="Message" value="welcome to java world!">
This page will be very boring if your
browser doesn't understand Java.
</APPLET>
</BODY>
</HTML>
OUTPUT
You pass getParameter() a string that names the parameter you want. This
string should match the name of a PARAM element in the HTML page.
All values are passed as strings. If you want to get another type like an
integer, then you'll need to pass it as a string and convert it to the type you
really want.
and </APPLET>. It has two attributes of its own, NAME and VALUE. NAME
identifies which PARAM this is. VALUE is the string value of the PARAM.
Both should be enclosed in double quote marks if they contain white space.
We sometimes need to load media and Text with the help of Applets. We
have the facility to load the data from the directory which holds the HTML
file which started the applet and the directory from which the applet’s class
import java.awt.*;
import java.applet.*;
import java.net.*;
public class getbase extends Applet
{
public void paint(Graphics g)
{
String message;
URL url=getCodeBase();
message="code-base:"+url.toString();
g.drawString(message,10,20);
url=getDocumentBase();
message="Document-base:"+url.toString();
g.drawString(message,10,30);
}
}
OUTPUT
from the environment in which the applet is running and getting executed.
by Applet. Once we get the information with the above mentioned method,
import java.awt.*;
import java.applet.*;
import java.net.*;
public class contextdoc extends Applet
{
public void start()
{
AppletContext ac=getAppletContext();
URL url=getCodeBase();
try
{
ac.showDocument(new URL(url+"demo.html"));
}
catch(MalformedURLException e)
{
showStatus("URL not found");
}
}
Multiple AudioClip items can be playing at the same time, and the resulting
After you have loaded an audio clip using getAudioClip(), you can use these methods
to play it.
The AppletStub interface provides a way to get information from the run-
programs, it is still also possible to use console output in your applet for
debugging purpose.
Questions
Syllabus:
Swings: The origins of Swing; Two key Swing features; Components and
Introduction
Swing contains a set of classes that provides more powerful and flexible GUI
components than those of AWT. Swing provides the look and feel of modern Java
GUI. Swing library is an official Java GUI tool kit released by Sun Microsystems. It
Swing is a set of program component s for Java programmers that provide the
ability to create graphical user interface ( GUI ) components, such as buttons and
scroll bars, that are independent of the windowing system for specific operating
system . Swing components are used with the Java Foundation Classes ( JFC ).
The original Java GUI subsystem was the Abstract Window Toolkit (AWT).
(peers).
Under AWT, the look and feel of a component was defined by the platform.
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
Swing components are lightweight and don't rely on peers.
Swing supports a pluggable look and feel.
Swing is built on AWT.
Model-View-Controller
the component.
The view determines how the component is displayed on the screen.
model the view (look) and controller (feel) are combined into a "delegate".
container.
Components
Swing components are derived from the JComponent class. The only
javax.swing package.
All the component classes start with J: JLabel, JButton, JScrollbar, ...
Containers
All the component classes start with J: JLabel, JButton, JScrollbar, ...
is JRootPane.
JRootPane manages the other panes and can add a menu bar.
There are three panes in JRootPane: 1) the glass pane, 2) the content pane,
The content pane is the container used for visual components. The content
Swing is a very large subsystem and makes use of many packages. These are
The main package is javax.swing. This package must be imported into any
program that uses Swing. It contains the classes that implement the basic
javax.swing javax.swing.plaf.synth
javax.swing.border javax.swing.table
javax.swing.colorchooser javax.swing.text
javax.swing.event javax.swing.text.html
javax.swing.filechooser javax.swing.text.html.parser
javax.swing.plaf javax.swing.text.rtf
javax.swing.plaf.basic javax.swing.tree
javax.swing.plaf.metal javax.swing.undo
javax.swing.plaf.multi
We can write the code of swing inside the main(), constructor or any other
method.
import javax.swing.*;
public class FirstSwing
{
public static void main(String[] args)
{
JFrame f=new JFrame(“ MyApp”);
//creating instance of JFrame and title of the frame is MyApp.
JButton b=new JButton("click");
//creating instance of JButton and name of the button is click.
b.setBounds(130,100,100, 40); //x axis, y axis, width, height
f.add(b); //addin g butto n in JFrame
f.setSize(400,500); //400 width and 500 height
f.setLayout(null); //using no layout managers
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true); //making the frame visible
}
}
Prepared by Nagamahesh BS,Ass t.Professor, CSE, Sai Vidya Institute of Technology Page 6
Object Oriented Programming Module-5 10CS/IS45
Output:
Explanation:
The program begins by importing javax.swing. As mentioned, this package
contains the components and models defined by Swing.
For example, javax.swing defines classes that implement labels, buttons,
text controls, and menus. It will be included in all programs that use Swing.
Next,
the program declares the FirstSwing class
It begins by creating a JFrame, using this line of code:
This creates a container called f that defines a rectangular window complete
with a title bar; close, minimize, maximize, and restore buttons; and a
system menu. Thus, it creates a standard, top-level window. The title of the
f.setSize(400,500);
The setSize( ) method (which is inherited by JFrame from the AWT class
Component) sets the dimensions of the window, which are specified in pixels.
in this example, the width of the window is set to 400 and the height is set
to 500.
By default, when a top-level window is closed (such as when the user clicks
the close box), the window is removed from the screen, but the application is
not terminated.
If want the entire application to terminate when its top-level window is
closed. There are a couple of ways to achieve this. The easiest way is to call
setDefaultCloseOperation( ), as the program does:
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Swing by inheritance
We can also inherit the JFrame class, so there is no need to
create the instance of JFrame class explicitly.
import javax.swing.*;
public class MySwing extends JFram //inheriting JFrame
{
JFrame f;
MySwing()
{
JButton b=new JButton("click");//create
button b.setBounds(130,100,100, 40);
add(b);//adding button on
frame setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
new MySwing();
}
}
JLabel is Swing’s easiest-to-use component. It creates a label and was
introduced in the preceding chapter. Here, we will look at JLabel a bit more
closely.
JLabel can be used to display text and/or an icon. It is a passive component
in that it does not respond to user input. JLabel defines several
constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JTextField is the simplest Swing text component. It is also probably its
most widely used text component. JTextField allows you to edit one line of
text. It is derived from JTextComponent, which provides the basic
functionality common to Swing text components.
JTextField(int cols)
JTextField(String str)
Here, str is the string to be initially presented, and cols is the number of
columns in the text field. If no string is specified, the text field is initially
empty. If the number of columns is not specified, the text field is sized to
fit the specified string.
JPasswordField is a lightweight component that allows the editing of a
single line of text where the view indicates something was typed, but does
not show the original characters.
import javax.swing.*;
public class JTextFieldPgm
{
f.add(namelabel);
f.add( passwordLabel);
f.add(userText);
f.add(passwordText);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
JLabel can be used to display text and/or an icon. It is a passive component
in that it does not respond to user input. JLabel defines several
constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
The align argument specifies the horizontal alignment of the text and/or
icon within the dimensions of the label. It must be one of the following
values: LEFT, RIGHT, CENTER, LEADING, or TRAILING.
These constants are defined in the Swing Constants interface, along with
several others used by the Swing classes. Notice that icons are specified by
objects of type Icon, which is an interface defined by Swing.
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon
implements Icon and encapsulates an image. Thus, an object of type
constructor.
ImageIcon(String filename)
It obtains the image in the file named filename. The icon and text associated
with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
Here, icon and str are the icon and text, respectively.
Therefore, using setText( ) it is possible to change the text
inside a label during program execution.
import javax.swing.*;
JFrame jf=new
JFrame("Image Icon");
jf.setLayout(null);
jf.setSize(
300,400);
jf.setVisib
le(true);
}
1. JButton
2. JRadioButton
3. JCheckBox
4. JComboBox
JButton(Icon ic)
JButton(String str)
import javax.swing.*;
class FirstSwing
{
public static void main(String args[])
{
JFrame jf=new JFrame("My App");
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
}
}
grouping the JRadio buttons using a ButtonGroup component. The ButtonGroup class
can be used to group multiple buttons so that at a time only one button can be
selected.
import javax.swing.*;
import javax.swing.*;
public class RadioButton1
{
public static void main(String args[])
{
r2.setBounds(50,150,70,30);
ButtonGroup bg=new
ButtonGroup(); bg.add(r1);
bg.add(r2);
f.add(r1)
;
f.add(r2)
;
f.setSize(500,500);
f.setLayout(null);
f.setVisible(true);
}
}
sometimes called a ticker box, and is used to represent multiple option selections in
a form.
import javax.swing.*;
class FirstSwing
{
public static void main(String args[])
{
JFrame jf=new JFrame("CheckBox");
jf.add(jb);
jf.add(jb1);
jf.setSize(300, 600);
jf.setLayout(null);
jf.setVisible(true);
}
}
JComboBox
The JComboBox class is used to create the combobox (drop-down list). At a time
import java.awt.*;
import javax.swing.*;
String Branch[]={"cse","ise","ec","mech"};
jc.setBounds(50,50,80,50);
f.add(jc);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
The JTable class is used to display the data on two dimensional tables of cells.
specified data.
JScrollPane is a lightweight container that automatically handles the
scrolling of another component.
The component being scrolled can either be an individual component, such as
a table, or a group of components contained within another lightweight
container, such as a JPanel.
In either case, if the object being scrolled is larger than the viewable area,
horizontal and/or vertical scroll bars are automatically provided, and the
Thus, the view port displays the visible portion of the component being
scrolled. The scroll bars scroll the component through the viewport.
In its default behavior, a JScrollPane will dynamically add or remove a scroll
bar as needed. For example, if the component is taller than the viewport, a
vertical scroll bar is added. If the component will completely fit within the
viewport, the scroll bars are removed.
import javax.swing.*;
public class TableExample1
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
JFrame f=new JFrame("Table Demo");
String data[][]={
{"100","CSE","VTU"}
,
{"101","ISE","VTU"}
,
{"102","CSE","VTU"}
,
{"103","ISE","VTU"}
,
{"105","ISE","VTU"}
,
{"106","ISE","VTU"}
};
String column[]={"courseID","Branch","University"};
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
}
}
JTabbedpane
JTabbedPane encapsulates a tabbed pane. It manages a set of components
by linking them with tabs.
Selecting a tab causes the component associated with that tab to come to
the forefront. Tabbed panes are very common in the modern GUI.
Given the complex nature of a tabbed pane, they are surprisingly easy to
create and use. JTabbedPane defines three constructors. We will use its
default constructor, which creates an empty control with the tabs
positioned across the top of the pane.
The other two constructors let you specify the location of the tabs, which
can be along any of the four sides.
JTabbedPane uses the SingleSelectionModel model. Tabs are added by
calling addTab( ) method. Here is one of its forms:
Here, name is the name for the tab, and comp is the component that should
be added to the tab. Often, the component added to a tab is a JPanel that
contains a group of related components. This technique allows a tab to hold a
set of components.
import javax.swing.*;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JTabbedPaneDemo());
f.setSize(500, 500);
f.setVisible(true);
JTabbedPaneDemo()
makeGUI();
void makeGUI()
add(jtp);
public CitiesPanel()
add(b1);
add(b2);
add(b3);
add(b4);
public ColorsPanel()
JCheckBox("Red"); add(cb1);
JCheckBox("Green"); add(cb2);
JCheckBox("Blue"); add(cb3);
public FlavorsPanel()
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
JList:
In Swing, the basic list class is called JList.
It supports the selection of one or more items from a list.
Although the list often consists of strings, it is possible to create a list of
just about any object that can be displayed.
JList is so widely used in Java that it is highly unlikely that you have not
seen one before.
JList(Object[ ] items)
This creates a JList that contains the items in the array specified by items.
JList is based on two models. The first is ListModel. This interface defines
how access to the list data is achieved.
The second model is the ListSelectionModel interface, which defines
methods that determine what list item or items are selected.
import java.awt.FlowLayout;
import javax.swing.*;
list.setSelectedIndex(1);
frame.add(new JScrollPane(list));
frame.setSize(300, 400);
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Questions