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();
s.name = "John";
s.roll_no = 2;
System.out.println("Name is "+s.name+" 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((x.row == y.row) && (x.column == y.column)){
Matrix m = new Matrix(x.row,x.column);
for(int i = 0;i<m.row;i++){
for(int j = 0;j<m.column;j++){
m.setElement(i,j,(x.getElement(i,j)+y.getElement(i,j)));
return m;
else{
System.out.println("Matrices can not be added");
return new Matrix(0,0);
public static Matrix product(Matrix x, Matrix y){
Matrix m = new Matrix(x.row,y.column);
for(int j = 0;j<x.row;j++){
for(int i = 0;i<y.column;i++){
int sum = 0;
for(int k = 0;k<x.column;k++){
sum = sum+(x.getElement(j,k)*y.getElement(k,i));
m.setElement(j,i,sum);
return m;
public void printMatrix(){
System.out.println("Matrix is :");
for(int i = 0;i<row;i++){
for(int j = 0;j<column;j++){
System.out.print(a[i][j]+"\t");
}
System.out.println("");
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++){
m.setElement(i,j,k);
k++;
n.setElement(i,j,k);
k++;
m.printMatrix();
n.printMatrix();
Matrix o = Matrix.add(m,n);
o.printMatrix();
Matrix p = Matrix.product(m,n);
p.printMatrix();
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 java.util.*;
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(System.in);
int l,b;
System.out.println("Enter length");
l = s.nextInt();
System.out.println("Enter breadth");
b = s.nextInt();
Area a = new Area(l,b);
System.out.println("Area : "+a.getArea());
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 java.util.*;
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((a.real+b.real),(a.imag+b.imag));
public static Complex diff(Complex a, Complex b){
return new Complex((a.real-b.real),(a.imag-b.imag));
public static Complex product(Complex a, Complex b){
return new Complex(((a.real*b.real)-(a.imag*b.imag)),((a.real*b.imag)+(a.imag*b.real)));
}
public void printComplex(){
if(real == 0 && imag!=0){
System.out.println(imag+"i");
else if(imag == 0 && real!=0){
System.out.println(real);
else{
System.out.println(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 = Complex.add(c,d);
Complex f = Complex.diff(c,d);
Complex g = Complex.product(c,d);
e.printComplex();
f.printComplex();
g.printComplex();
}
}
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);
System.out.println("Area : "+a.getArea()+" Perimeter is "+a.getPerimeter());
System.out.println("Area : "+b.getArea()+" Perimeter is "+b.getPerimeter());
}
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 java.util.Scanner;
public class Exercise1 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number: ");
double x = in.nextDouble();
System.out.print("Input the Second number: ");
double y = in.nextDouble();
System.out.print("Input the third number: ");
double z = in.nextDouble();
System.out.print("The smallest value is " + smallest(x, y, z)+"\n" );
public static double smallest(double x, double y, double z)
return Math.min(Math.min(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 java.util.Scanner;
public class Exercise2 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the first number: ");
double x = in.nextDouble();
System.out.print("Input the second number: ");
double y = in.nextDouble();
System.out.print("Input the third number: ");
double z = in.nextDouble();
System.out.print("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 java.util.Scanner;
public class Exercise3 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input a string: ");
String str = in.nextLine();
System.out.print("The middle character in the string: " + middle(str)+"\n");
public static String middle(String str)
int position;
int length;
if (str.length() % 2 == 0)
{
position = str.length() / 2 - 1;
length = 2;
else
position = str.length() / 2;
length = 1;
return str.substring(position, position + length);
QS-4. Write a Java method to count all vowels in a string
import java.util.Scanner;
public class Exercise4 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();
System.out.print("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 < str.length(); i++)
{
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(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 java.util.Scanner;
public class Exercise5 {
public static void main(String[] args)
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();
System.out.print("Number of words in the string: " + count_Words(str)+"\n");
public static int count_Words(String str)
{
int count = 0;
if (!(" ".equals(str.substring(0, 1))) || !(" ".equals(str.substring(str.length() - 1))))
for (int i = 0; i < str.length(); i++)
if (str.charAt(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)
System.out.println("Hello Readers, Welcome to DataFlair");
}
// Overloaded main methods
public static void main(String arg1)
System.out.println("Hi, " + arg1);
MetodOverloadingExample1.main("DataFlair");
public static void main(String arg1, String arg2)
System.out.println("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();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
Output :
30
60
31.0
3. class Multiply {
void mul(int a, int b) {
System.out.println("Sum of two=" + (a * b));
void mul(int a, int b, int c) {
System.out.println("Sum of three=" + (a * b * c));
public class Polymorphism {
public static void main(String args[]) {
Multiply m = new Multiply();
m.mul(6, 10);
m.mul(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)
System.out.println ("You have typed the letter: "+ch);
public void show(char ch, char ch1)
{
System.out.println("You have typed the letter: "+ch+", and " + ch1);
class Main
public static void main (String args[] )
DispOvrload o1 = new DispOvrload();
o1.show('G');
o1.show( '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)
System.out.println ("The 'show method' is defined for the first time.");
public void show(int numb, char ch)
System.out.println ("The 'show method' is defined for the second time." );
}
}
class Main
public static void main (String args[] )
DispOvrload o1 = new DispOvrload();
o1.show('G', 62);
o1.show(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;
System.out.println("Area is :"+figref.area());
figref = r;
System.out.println("Area is :"+figref.area());
class Figure {
double dim1;
double dim2;
Figure(double a , double b) {
dim1 = a;
dim2 = b;
Double area() {
System.out.println("Inside area for figure.");
return(dim1*dim2);
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a ,b);
Double area() {
System.out.println("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
System.out.println(a.move()); // Runs the method in Animal class
System.out.println(b.move()); // 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();
task.run(); //call overridden method in Task
task = new PeriodicTask();
task.run(); //calls overridden method in PeriodicTas
class Task implements Runnable{
@Override
public void run() {
System.out.println("Run method overridden in Task class");
class PeriodicTask extends Task{
@Override
public void run() {
System.err.println("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();
ic.flavor = "Pista";
ic.numberOfScoops = 2;
System.out.println(ic.numberOfScoops + " scoops of " + ic.flavor + " flavor price is : " +
ic.getPrice());
FruitSaladWithIceCream fs = new FruitSaladWithIceCream();
fs.flavor = "Chocolate";
fs.numberOfScoops = 1;
fs.gramsOfFruitSalad = 50;
System.out.print(fs.gramsOfFruitSalad + " grams of fruit salad and ");
System.out.println(fs.numberOfScoops + " scoops of " + fs.flavor + " flavor price is : " +
fs.getPrice());
KhubaniKaMeetaWithIceCream kkm = new KhubaniKaMeetaWithIceCream();
kkm.flavor = "Vanila";
kkm.numberOfScoops = 1;
kkm.gramsOfKhubaniKaMeeta = 75;
System.out.print(kkm.gramsOfKhubaniKaMeeta + " grams of khubani ka meeta and ");
System.out.println(kkm.numberOfScoops + " scoops of " + kkm.flavor + " flavor price is : "
+ kkm.getPrice());
}
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 = super.getPrice(); // LINE A
double pricePerGram = 0.75;
return gramsOfFruitSalad * pricePerGram + iceCreamPrice;
}
class KhubaniKaMeetaWithIceCream extends IceCream
int gramsOfKhubaniKaMeeta;
double getPrice()
double iceCreamPrice = super.getPrice(); // 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(){
System.out.println("Student details.");
public class CollegeStudent extends Student {
/**
* This method is used to show details of a college student.
* @author CodesJava
*/
public void show(){
System.out.println("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.
obj.show();
Output:
College Student details.
SINGLE LEVEL INHARITANCE:-
1. class Shape {
public void display() {
System.out.println("Inside display");
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
public class Tester {
public static void main(String[] arguments) {
Rectangle rect = new Rectangle();
rect.display();
rect.area();
Output
Inside display
Inside area
2. public class Inherit_Single {
protected String str;
Inherit_Single() {
str = "Java ";
}
class SubClass extends Inherit_Single {
SubClass() {
str = str.concat("World !!!");
void display()
System.out.println(str);
class MainClass {
public static void main (String args[]){
SubClass obj = new SubClass();
obj.display();
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();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
Output
Salary is: 30000.0
Bonous is: 2000.0
MULTILEVEL INHARITANCE:-
class Car{
public Car()
System.out.println("Class Car");
public void vehicleType()
System.out.println("Vehicle Type: Car");
}
class Maruti extends Car{
public Maruti()
System.out.println("Class Maruti");
public void brand()
System.out.println("Brand: Maruti");
public void speed()
System.out.println("Max: 90Kmph");
public class Maruti800 extends Maruti{
public Maruti800()
System.out.println("Maruti Model: 800");
public void speed()
System.out.println("Max: 80Kmph");
public static void main(String args[])
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
2. class Person
Person()
System.out.println("Person constructor");
void nationality()
{
System.out.println("Indian");
void place()
System.out.println("Mumbai");
class Emp extends Person
Emp()
System.out.println("Emp constructor");
}
void organization()
System.out.println("IBM");
void place()
System.out.println("New York");
class Manager extends Emp
Manager()
System.out.println("Manager constructor");
}
void subordinates()
System.out.println(12);
void place()
System.out.println("London");
class Check
public static void main(String arg[])
{
Manager m=new Manager();
m.nationality();
m.organization();
m.subordinates();
m.place();
Output:
Person constructor
Emp constructor
Manager constructor
Indian
IBM
12
London
3. package management;
import java.util.Scanner;
class teacher{
void tech(){
System.out.println("!!!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(){
System.out.println("!!!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(){
System.out.println("!!!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(System.in);
System.out.println("Enter your Department\n 1.teacher\n2.admin\n3.manager\n");
String dept=s.nextLine();
if(dept.equals("teacher"))
{ m.tech();
}
else if(dept.equals("admin"))
{ m.admin();
else if(dept.equals("manager"))
{ m.manager();
else
{ System.out.println("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(){
System.out.println("Student name = " + name);
System.out.println("Student class name = " + className);
System.out.println("Student semester = " + semester);
public class StudentTest {
public static void main(String args[]){
//creating subclass object
McaStudent obj = new McaStudent();
//method call
obj.showDetail();
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()
System.out.println("NAME:" +name+"\nAGE:"+age+"\nMARK1="+m1+"\nMARK2="+m2+"\
nMARK3="+m3+"\nTOTAL:"+total);
class multilevel
public static void main(String args[])
student ob=new student();
ob.calc();
ob.show();
MULTITHREADING:-
1. package com.techbeamers.multithreading;
class NameMyThread
public static void main (String [] args)
MyThread mt;
if (args.length == 0)
mt = new MyThread ();
else
mt = new MyThread (args [0]);
mt.start ();
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 ()
System.out.println ("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;
System.out.println("Creating thread: " + threadName );
public void run()
System.out.println("Running thread: " + threadName );
try
for(int i = 0; i < 5; i++)
System.out.println("Thread: " + threadName + ", " + i);
Thread.sleep(50);
catch (InterruptedException e)
System.out.println("Exception in thread: " + threadName);
System.out.println("Thread " + threadName + " continue...");
public void start ()
System.out.println("Start method " + threadName );
if (thread == null)
thread = new Thread (this, threadName);
thread.start ();
public class MultipleThread
public static void main(String args[])
ThreadTest thread1 = new ThreadTest( "First Thread");
thread1.start();
ThreadTest thread2 = new ThreadTest( "Second Thread");
thread2.start();
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);
p1.start();
c1.start();
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)
ie.printStackTrace();
}
materials = value;
available = true;
notifyAll();
class Consumer extends Thread
private Shop Shop;
private int number;
public Consumer(Shop c, int number)
Shop = c;
this.number = number;
public void run()
int value = 0;
for (int i = 0; i < 10; i++)
value = Shop.get();
System.out.println("Consumed value " + this.number+ " got: " + value);
class Producer extends Thread
{
private Shop Shop;
private int number;
public Producer(Shop c, int number)
Shop = c;
this.number = number;
public void run()
for (int i = 0; i < 10; i++)
Shop.put(i);
System.out.println("Produced value " + this.number+ " put: " + i);
try
sleep((int)(Math.random() * 100));
catch (InterruptedException ie)
ie.printStackTrace();
}
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.
Thread1.java
class Thread1 extends Thread
String msg = "";
Thread1(String msg)
this.msg = msg;
public void run()
try
while (true)
System.out.println(msg);
Thread.sleep(300);
catch (Exception ex)
ex.printStackTrace();
Thread2.java
class Thread2 extends Thread
String msg = "";
Thread2(String msg)
this.msg = msg;
public void run()
try
while (true)
System.out.println(msg);
Thread.sleep(400);
}
catch (Exception ex)
ex.printStackTrace();
ThreadDemo.java
class ThreadDemo
public static void main(String[] args)
Thread1 t1 = new Thread1("Running Thread1....");
Thread1 t2 = new Thread1("Running Thread2....");
t1.start();
t2.start();
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.
Fibonacci.java
import java.io.*;
class Fibonacci extends Thread
public void run()
try
int a=0, b=1, c=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Limit for fabonacci: ");
int n = Integer.parseInt(br.readLine());
System.out.println("\n=================================");
System.out.println("Fibonacci series:");
while (n>0)
System.out.print(c+" ");
a=b;
b=c;
c=a+b;
n=n-1;
}
}
catch (Exception ex)
ex.printStackTrace();
Reverse.java
class Reverse extends Thread
public void run()
try
System.out.println("\n=================================");
System.out.println("\nReverse is: ");
System.out.println("=================================");
for (int i=10; i >= 1 ;i-- )
System.out.print(i+" ");
System.out.println("\n=================================\n\n");
catch (Exception ex)
{
ex.printStackTrace();
MainThread.java
class MainThread
public static void main(String[] args)
try
Fibonacci fib = new Fibonacci();
fib.start();
fib.sleep(4000);
Reverse rev = new Reverse();
rev.start();
catch (Exception ex)
ex.printStackTrace();
}
Output: