CLASS AND OBJECT
QS -1. Create a class named 'Student' with String variable 'name' and integer variable 'roll_no'.
Assign the value of roll_no as '2' and that of name as "John" by creating an object of the class
Student.
class Student{
String name;
int roll_no;
class Ans{
public static void main(String[] args){
Student s = new Student();
[Link] = "John";
s.roll_no = 2;
[Link]("Name is "+[Link]+" and roll number is "+s.roll_no);
QS- 2. The Matrix class has methods for each of the following:
1 - get the number of rows
2 - get the number of columns
3 - set the elements of the matrix at given position (i,j)
4 - adding two matrices. If the matrices are not addable, "Matrices cannot be added" will be
displayed.
5 - multiplying the two matrices
class Matrix{
int row;
int column;
int[][] a;
public Matrix(int r, int c){
row = r;
column = c;
a = new int[row][column];
public int getRows(){
return row;
public int getColumns(){
return column;
public int getElement(int r, int c){
return a[r][c];
public void setElement(int r, int c, int element){
a[r][c] = element;
public static Matrix add(Matrix x, Matrix y){
if(([Link] == [Link]) && ([Link] == [Link])){
Matrix m = new Matrix([Link],[Link]);
for(int i = 0;i<[Link];i++){
for(int j = 0;j<[Link];j++){
[Link](i,j,([Link](i,j)+[Link](i,j)));
return m;
else{
[Link]("Matrices can not be added");
return new Matrix(0,0);
public static Matrix product(Matrix x, Matrix y){
Matrix m = new Matrix([Link],[Link]);
for(int j = 0;j<[Link];j++){
for(int i = 0;i<[Link];i++){
int sum = 0;
for(int k = 0;k<[Link];k++){
sum = sum+([Link](j,k)*[Link](k,i));
[Link](j,i,sum);
return m;
public void printMatrix(){
[Link]("Matrix is :");
for(int i = 0;i<row;i++){
for(int j = 0;j<column;j++){
[Link](a[i][j]+"\t");
}
[Link]("");
class Ans{
public static void main(String[] args){
Matrix m = new Matrix(3,3);
Matrix n = new Matrix(3,3);
int k = 1;
for(int i = 0;i<3;i++){
for(int j = 0;j < 3;j++){
[Link](i,j,k);
k++;
[Link](i,j,k);
k++;
[Link]();
[Link]();
Matrix o = [Link](m,n);
[Link]();
Matrix p = [Link](m,n);
[Link]();
QS- 3. Write a program to print the area of a rectangle by creating a class named 'Area' taking
the values of its length and breadth as parameters of its constructor and having a method named
'returnArea' which returns the area of the rectangle. Length and breadth of rectangle are entered
through keyboard.
import [Link].*;
class Area{
int length;
int breadth;
public Area(int l, int b){
length = l;
breadth = b;
public int getArea(){
return length*breadth;
class Ans{
public static void main(String[] args){
Scanner s = new Scanner([Link]);
int l,b;
[Link]("Enter length");
l = [Link]();
[Link]("Enter breadth");
b = [Link]();
Area a = new Area(l,b);
[Link]("Area : "+[Link]());
QS 4. Print the sum, difference and product of two complex numbers by creating a class named
'Complex' with separate methods for each operation whose real and imaginary parts are entered
by user.
import [Link].*;
class Complex{
int real;
int imag;
public Complex(int r, int i){
real = r;
imag = i;
public static Complex add(Complex a, Complex b){
return new Complex(([Link]+[Link]),([Link]+[Link]));
public static Complex diff(Complex a, Complex b){
return new Complex(([Link]),([Link]));
public static Complex product(Complex a, Complex b){
return new Complex((([Link]*[Link])-([Link]*[Link])),(([Link]*[Link])+([Link]*[Link])));
}
public void printComplex(){
if(real == 0 && imag!=0){
[Link](imag+"i");
else if(imag == 0 && real!=0){
[Link](real);
else{
[Link](real+"+"+imag+"i");
class Ans{
public static void main(String[] args){
Complex c = new Complex(4,5);
Complex d = new Complex(9,4);
Complex e = [Link](c,d);
Complex f = [Link](c,d);
Complex g = [Link](c,d);
[Link]();
[Link]();
[Link]();
}
}
QS- 5-Write a program to print the area of two rectangles having sides (4,5) and (5,8)
respectively by creating a class named 'Rectangle' with a method named 'Area' which returns the
area and length and breadth passed as parameters to its constructor.
class Rectangle{
int length;
int breadth;
public Rectangle(int l, int b){
length = l;
breadth = b;
public int getArea(){
return length*breadth;
public int getPerimeter(){
return 2*(length+breadth);
class Ans{
public static void main(String[] args){
Rectangle a = new Rectangle(4,5);
Rectangle b = new Rectangle(5,8);
[Link]("Area : "+[Link]()+" Perimeter is "+[Link]());
[Link]("Area : "+[Link]()+" Perimeter is "+[Link]());
}
METHODS:-
QS-1 Write a Java method to find the smallest number among three numbers.
Test Data:
Input the first number: 25
Input the Second number: 37
Input the third number: 29
import [Link];
public class Exercise1 {
public static void main(String[] args)
Scanner in = new Scanner([Link]);
[Link]("Input the first number: ");
double x = [Link]();
[Link]("Input the Second number: ");
double y = [Link]();
[Link]("Input the third number: ");
double z = [Link]();
[Link]("The smallest value is " + smallest(x, y, z)+"\n" );
public static double smallest(double x, double y, double z)
return [Link]([Link](x, y), z);
Sample Output:
Input the first number: 25
Input the Second number: 37
Input the third number: 29
The smallest value is 25.0
QS-2 Write a Java method to compute the average of three numbers. Go to the editor
Test Data:
Input the first number: 25
Input the second number: 45
Input the third number: 65
import [Link];
public class Exercise2 {
public static void main(String[] args)
Scanner in = new Scanner([Link]);
[Link]("Input the first number: ");
double x = [Link]();
[Link]("Input the second number: ");
double y = [Link]();
[Link]("Input the third number: ");
double z = [Link]();
[Link]("The average value is " + average(x, y, z)+"\n" );
public static double average(double x, double y, double z)
return (x + y + z) / 3;
}
}
Sample Output:
Input the first number: 25
Input the second number: 45
Input the third number: 65
The average value is 45.0
QS-3. Write a Java method to display the middle character of a string. Go to the editor
Note: a) If the length of the string is odd there will be two middle characters.
b) If the length of the string is even there will be one middle character.
Test Data:
Input a string: 350
import [Link];
public class Exercise3 {
public static void main(String[] args)
Scanner in = new Scanner([Link]);
[Link]("Input a string: ");
String str = [Link]();
[Link]("The middle character in the string: " + middle(str)+"\n");
public static String middle(String str)
int position;
int length;
if ([Link]() % 2 == 0)
{
position = [Link]() / 2 - 1;
length = 2;
else
position = [Link]() / 2;
length = 1;
return [Link](position, position + length);
QS-4. Write a Java method to count all vowels in a string
import [Link];
public class Exercise4 {
public static void main(String[] args)
Scanner in = new Scanner([Link]);
[Link]("Input the string: ");
String str = [Link]();
[Link]("Number of Vowels in the string: " + count_Vowels(str)+"\n");
public static int count_Vowels(String str)
int count = 0;
for (int i = 0; i < [Link](); i++)
{
if ([Link](i) == 'a' || [Link](i) == 'e' || [Link](i) == 'i'
|| [Link](i) == 'o' || [Link](i) == 'u')
count++;
return count;
Sample Output:
Input the string:SRMSCETR
Number of Vowels in the string: 1
QS-5. Write a Java method to count all words in a string.
import [Link];
public class Exercise5 {
public static void main(String[] args)
Scanner in = new Scanner([Link]);
[Link]("Input the string: ");
String str = [Link]();
[Link]("Number of words in the string: " + count_Words(str)+"\n");
public static int count_Words(String str)
{
int count = 0;
if (!(" ".equals([Link](0, 1))) || !(" ".equals([Link]([Link]() - 1))))
for (int i = 0; i < [Link](); i++)
if ([Link](i) == ' ')
count++;
count = count + 1;
return count; // returns 0 if string starts or ends with space " ".
Sample Output:
Input the string: The quick brown fox jumps over the lazy dog
Number of words in the string: 9
METHOD OVERLOADING:-
1. public class MetodOverloadingExample1
// Normal main()
public static void main(String[] args)
[Link]("Hello Readers, Welcome to DataFlair");
}
// Overloaded main methods
public static void main(String arg1)
[Link]("Hi, " + arg1);
[Link]("DataFlair");
public static void main(String arg1, String arg2)
[Link]("Hi, " + arg1 + ", " + arg2);
2. public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y)
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
return (x + y + z);
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y)
return (x + y);
// Driver code
public static void main(String args[])
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
Output :
30
60
31.0
3. class Multiply {
void mul(int a, int b) {
[Link]("Sum of two=" + (a * b));
void mul(int a, int b, int c) {
[Link]("Sum of three=" + (a * b * c));
public class Polymorphism {
public static void main(String args[]) {
Multiply m = new Multiply();
[Link](6, 10);
[Link](10, 6, 5);
output:-
Sum of two=60
Sum of three=300
Program to demonstrate method overloading based on number of parameter
4. class DispOvrload
public void show(char ch)
[Link] ("You have typed the letter: "+ch);
public void show(char ch, char ch1)
{
[Link]("You have typed the letter: "+ch+", and " + ch1);
class Main
public static void main (String args[] )
DispOvrload o1 = new DispOvrload();
[Link]('G');
[Link]( 'S', 'J' );
Output:-
You have typed the letter: G
You have typed the letter: S, and J
5. Program to demonstrate method overloading based sequence of data type in parameter
class DispOvrload
public void show(char ch, int numb)
[Link] ("The 'show method' is defined for the first time.");
public void show(int numb, char ch)
[Link] ("The 'show method' is defined for the second time." );
}
}
class Main
public static void main (String args[] )
DispOvrload o1 = new DispOvrload();
[Link]('G', 62);
[Link](46, 'S');
output:-
The 'show method' is defined for the first time.
The 'show method' is defined for the second time.
MRTHOD OVERRIDING:-
1. public class Findareas {
public static void main (String []agrs) {
Figure f = new Figure(10 , 10);
Rectangle r = new Rectangle(9 , 5);
Figure figref;
figref = f;
[Link]("Area is :"+[Link]());
figref = r;
[Link]("Area is :"+[Link]());
class Figure {
double dim1;
double dim2;
Figure(double a , double b) {
dim1 = a;
dim2 = b;
Double area() {
[Link]("Inside area for figure.");
return(dim1*dim2);
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a ,b);
Double area() {
[Link]("Inside area for rectangle.");
return(dim1*dim2);
output:-
Inside area for figure.
Area is :100.0
Inside area for rectangle.
Area is :45.0
2. class Animal{
public String move(){
return "Animals can move";
class Cow extends Animal{
@Override
public String move(){
return "Cow can walk and run";
public class OverridingMethods {
public static void main(String args[]){
Animal a = new Animal(); // Animal reference to an Animal object
Animal b = new Cow(); // Animal reference to a Cow object
[Link]([Link]()); // Runs the method in Animal class
[Link]([Link]()); // Runs the method in Cow class
Output:
Animals can move
Cow can walk and run
3. public class CollectionTest {
public static void main(String args[]) {
Runnable task = new Task();
[Link](); //call overridden method in Task
task = new PeriodicTask();
[Link](); //calls overridden method in PeriodicTas
class Task implements Runnable{
@Override
public void run() {
[Link]("Run method overridden in Task class");
class PeriodicTask extends Task{
@Override
public void run() {
[Link]("overridden method run() in PeriodicTask class");
Output:
Run method overridden in Task class
overridden method run() in PeriodicTask class
4. class IceCreamPricesWithOverriding
{
public static void main(String arg[])
IceCream ic = new IceCream();
[Link] = "Pista";
[Link] = 2;
[Link]([Link] + " scoops of " + [Link] + " flavor price is : " +
[Link]());
FruitSaladWithIceCream fs = new FruitSaladWithIceCream();
[Link] = "Chocolate";
[Link] = 1;
[Link] = 50;
[Link]([Link] + " grams of fruit salad and ");
[Link]([Link] + " scoops of " + [Link] + " flavor price is : " +
[Link]());
KhubaniKaMeetaWithIceCream kkm = new KhubaniKaMeetaWithIceCream();
[Link] = "Vanila";
[Link] = 1;
[Link] = 75;
[Link]([Link] + " grams of khubani ka meeta and ");
[Link]([Link] + " scoops of " + [Link] + " flavor price is : "
+ [Link]());
}
class IceCream
String flavor;
int numberOfScoops;
double getPrice()
double pricePerScoop = 35.0;
return numberOfScoops * pricePerScoop;
class FruitSaladWithIceCream extends IceCream
int gramsOfFruitSalad;
double getPrice()
double iceCreamPrice = [Link](); // LINE A
double pricePerGram = 0.75;
return gramsOfFruitSalad * pricePerGram + iceCreamPrice;
}
class KhubaniKaMeetaWithIceCream extends IceCream
int gramsOfKhubaniKaMeeta;
double getPrice()
double iceCreamPrice = [Link](); // LINE B
double pricePerGram = 1.25;
return gramsOfKhubaniKaMeeta * pricePerGram + iceCreamPrice;
OUTPUT
2 scoops of Pista flavor price is : 70.0
50 grams of fruit salad and 1 scoops of Chocolate flavor price is : 72.5
75 grams of khubani ka meeta and 1 scoops of Vanila flavor price is : 128.75
5. /**
* This program is used for simple method overriding example.
* @author CodesJava
*/
class Student {
/**
* This method is used to show details of a student.
* @author CodesJava
*/
public void show(){
[Link]("Student details.");
public class CollegeStudent extends Student {
/**
* This method is used to show details of a college student.
* @author CodesJava
*/
public void show(){
[Link]("College Student details.");
//main method
public static void main(String args[]){
CollegeStudent obj = new CollegeStudent();
//subclass overrides super class method
//hence method of CollegeStudent class will be called.
[Link]();
Output:
College Student details.
SINGLE LEVEL INHARITANCE:-
1. class Shape {
public void display() {
[Link]("Inside display");
}
class Rectangle extends Shape {
public void area() {
[Link]("Inside area");
public class Tester {
public static void main(String[] arguments) {
Rectangle rect = new Rectangle();
[Link]();
[Link]();
Output
Inside display
Inside area
2. public class Inherit_Single {
protected String str;
Inherit_Single() {
str = "Java ";
}
class SubClass extends Inherit_Single {
SubClass() {
str = [Link]("World !!!");
void display()
[Link](str);
class MainClass {
public static void main (String args[]){
SubClass obj = new SubClass();
[Link]();
Sample Output
Java World !!!
3. class Faculty
{
float salary=30000;
class Science extends Faculty
float bonous=2000;
public static void main(String args[])
Science obj=new Science();
[Link]("Salary is:"+[Link]);
[Link]("Bonous is:"+[Link]);
Output
Salary is: 30000.0
Bonous is: 2000.0
MULTILEVEL INHARITANCE:-
class Car{
public Car()
[Link]("Class Car");
public void vehicleType()
[Link]("Vehicle Type: Car");
}
class Maruti extends Car{
public Maruti()
[Link]("Class Maruti");
public void brand()
[Link]("Brand: Maruti");
public void speed()
[Link]("Max: 90Kmph");
public class Maruti800 extends Maruti{
public Maruti800()
[Link]("Maruti Model: 800");
public void speed()
[Link]("Max: 80Kmph");
public static void main(String args[])
Maruti800 obj=new Maruti800();
[Link]();
[Link]();
[Link]();
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
2. class Person
Person()
[Link]("Person constructor");
void nationality()
{
[Link]("Indian");
void place()
[Link]("Mumbai");
class Emp extends Person
Emp()
[Link]("Emp constructor");
}
void organization()
[Link]("IBM");
void place()
[Link]("New York");
class Manager extends Emp
Manager()
[Link]("Manager constructor");
}
void subordinates()
[Link](12);
void place()
[Link]("London");
class Check
public static void main(String arg[])
{
Manager m=new Manager();
[Link]();
[Link]();
[Link]();
[Link]();
Output:
Person constructor
Emp constructor
Manager constructor
Indian
IBM
12
London
3. package management;
import [Link];
class teacher{
void tech(){
[Link]("!!!Subject!!!\t\t!!Empid!!\n1)java\t\t\t101\n2)php\t\t\t102\n3)Android\t\
t103\n\n");
class Admin extends teacher{
void admin(){
[Link]("!!!Salary!!!\t\t!!Shift!!\n1)rs25,000\t\t9:00 AM to 5:00PM\
n2)rs30,000\t\t9:00 AM to 5:30PM)\n3)rs45,000\t\t5:00 PM to 9:00AM\n\n");
class Manage extends Admin{
void manager(){
[Link]("!!!HR Salary!!!\t\t!!!FinanceSalary!!!\n
1)Rs35,000\t\t40,000\n2)Rs45,000\t\t47,000\n1)Rs55,000\t\t57,000\n");
public class Management {
public static void main(String[] args) {
// TODO code application logic here
Manage m=new Manage();
Scanner s=new Scanner([Link]);
[Link]("Enter your Department\n [Link]\[Link]\[Link]\n");
String dept=[Link]();
if([Link]("teacher"))
{ [Link]();
}
else if([Link]("admin"))
{ [Link]();
else if([Link]("manager"))
{ [Link]();
else
{ [Link]("Invalid Input again try");
4. class Student {
String name = "jai";
class CollegeStudent extends Student {
String className = "MCA";
class McaStudent extends CollegeStudent{
String semester = "3rd sem.";
/**
* This method is used to show details of a student.
* @author CodesJava
*/
public void showDetail(){
[Link]("Student name = " + name);
[Link]("Student class name = " + className);
[Link]("Student semester = " + semester);
public class StudentTest {
public static void main(String args[]){
//creating subclass object
McaStudent obj = new McaStudent();
//method call
[Link]();
Output:
Student name = jai
Student class name = MCA
Student semester = 3rd sem.
5. class name
String name="anu";
int age=20;
class mark extends name
int m1=30,m2=30,m3=30;
class student extends mark
int total;
void calc()
total=m1+m2+m3;
void show()
[Link]("NAME:" +name+"\nAGE:"+age+"\nMARK1="+m1+"\nMARK2="+m2+"\
nMARK3="+m3+"\nTOTAL:"+total);
class multilevel
public static void main(String args[])
student ob=new student();
[Link]();
[Link]();
MULTITHREADING:-
1. package [Link];
class NameMyThread
public static void main (String [] args)
MyThread mt;
if ([Link] == 0)
mt = new MyThread ();
else
mt = new MyThread (args [0]);
[Link] ();
class MyThread extends Thread
MyThread ()
// The compiler creates the byte code equivalent of super ();
MyThread (String name)
setName (name); // Pass name to Thread superclass
}
public void run ()
[Link] ("My name is: " + getName ());
Output.
Java NameMyThread
Output:
My name is: Thread-0
2. class ThreadTest extends Thread
private Thread thread;
private String threadName;
ThreadTest( String msg)
threadName = msg;
[Link]("Creating thread: " + threadName );
public void run()
[Link]("Running thread: " + threadName );
try
for(int i = 0; i < 5; i++)
[Link]("Thread: " + threadName + ", " + i);
[Link](50);
catch (InterruptedException e)
[Link]("Exception in thread: " + threadName);
[Link]("Thread " + threadName + " continue...");
public void start ()
[Link]("Start method " + threadName );
if (thread == null)
thread = new Thread (this, threadName);
[Link] ();
public class MultipleThread
public static void main(String args[])
ThreadTest thread1 = new ThreadTest( "First Thread");
[Link]();
ThreadTest thread2 = new ThreadTest( "Second Thread");
[Link]();
3. public class ProducerConsumer
public static void main(String[] args)
Shop c = new Shop();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
[Link]();
[Link]();
class Shop
private int materials;
private boolean available = false;
public synchronized int get()
while (available == false)
try
wait();
catch (InterruptedException ie)
available = false;
notifyAll();
return materials;
public synchronized void put(int value)
while (available == true)
try
wait();
catch (InterruptedException ie)
[Link]();
}
materials = value;
available = true;
notifyAll();
class Consumer extends Thread
private Shop Shop;
private int number;
public Consumer(Shop c, int number)
Shop = c;
[Link] = number;
public void run()
int value = 0;
for (int i = 0; i < 10; i++)
value = [Link]();
[Link]("Consumed value " + [Link]+ " got: " + value);
class Producer extends Thread
{
private Shop Shop;
private int number;
public Producer(Shop c, int number)
Shop = c;
[Link] = number;
public void run()
for (int i = 0; i < 10; i++)
[Link](i);
[Link]("Produced value " + [Link]+ " put: " + i);
try
sleep((int)([Link]() * 100));
catch (InterruptedException ie)
[Link]();
}
4. Write a program that creates 2 threads - each displaying a message (Pass the message as a
parameter to the constructor). The threads should display the messages continuously till the user
presses ctrl+c.
[Link]
class Thread1 extends Thread
String msg = "";
Thread1(String msg)
[Link] = msg;
public void run()
try
while (true)
[Link](msg);
[Link](300);
catch (Exception ex)
[Link]();
[Link]
class Thread2 extends Thread
String msg = "";
Thread2(String msg)
[Link] = msg;
public void run()
try
while (true)
[Link](msg);
[Link](400);
}
catch (Exception ex)
[Link]();
[Link]
class ThreadDemo
public static void main(String[] args)
Thread1 t1 = new Thread1("Running Thread1....");
Thread1 t2 = new Thread1("Running Thread2....");
[Link]();
[Link]();
Output:
5. Q. Write a JAVA program which will generate the threads:
- To display 10 terms of Fibonacci series.
- To display 1 to 10 in reverse order.
[Link]
import [Link].*;
class Fibonacci extends Thread
public void run()
try
int a=0, b=1, c=0;
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the Limit for fabonacci: ");
int n = [Link]([Link]());
[Link]("\n=================================");
[Link]("Fibonacci series:");
while (n>0)
[Link](c+" ");
a=b;
b=c;
c=a+b;
n=n-1;
}
}
catch (Exception ex)
[Link]();
[Link]
class Reverse extends Thread
public void run()
try
[Link]("\n=================================");
[Link]("\nReverse is: ");
[Link]("=================================");
for (int i=10; i >= 1 ;i-- )
[Link](i+" ");
[Link]("\n=================================\n\n");
catch (Exception ex)
{
[Link]();
[Link]
class MainThread
public static void main(String[] args)
try
Fibonacci fib = new Fibonacci();
[Link]();
[Link](4000);
Reverse rev = new Reverse();
[Link]();
catch (Exception ex)
[Link]();
}
Output: