0% found this document useful (0 votes)
75 views37 pages

Object Oriented Programming Project File

The document provides 14 code examples demonstrating different Java programming concepts: 1. It shows code for calculating the factorial of a number, power of a number, and Fibonacci series. 2. Code is provided to find the largest, middle and smallest of three numbers. 3. Examples demonstrate printing shapes like rectangles using characters, and implementing arrays. 4. Further code illustrates concepts like type casting, command line arguments, string handling functions, and constructors. 5. The document also includes examples for multilevel and hierarchical inheritance, interfaces, abstract classes, multiple inheritance, and polymorphism through method overloading and overriding.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
75 views37 pages

Object Oriented Programming Project File

The document provides 14 code examples demonstrating different Java programming concepts: 1. It shows code for calculating the factorial of a number, power of a number, and Fibonacci series. 2. Code is provided to find the largest, middle and smallest of three numbers. 3. Examples demonstrate printing shapes like rectangles using characters, and implementing arrays. 4. Further code illustrates concepts like type casting, command line arguments, string handling functions, and constructors. 5. The document also includes examples for multilevel and hierarchical inheritance, interfaces, abstract classes, multiple inheritance, and polymorphism through method overloading and overriding.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 37

Q-1:- Program to print factorial of a given no. ?

class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

OUTPUT :-
Factorial of 5 is: 120
Q-2:- Program to print power of a given no. ?

import java.util.Scanner;
public class PowerOfNumberExample1
{
//function to find the power of a number
static int power(int base, int exponent)
{
int power = 1;
//increment the value of i after each iteration until the condition becomes false
for (int i = 1; i <= exponent; i++)
//calculates power
power = power * base;
//returns power
return power;
}
//driver code
public static void main(String args[])
{
int base, exponent;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the base: ");
base=sc.nextInt();
System.out.print("Enter the exponent: ");
exponent=sc.nextInt();
//calling function
int pow=power(base, exponent);
//prints the result
System.out.println(base +" to the power " +exponent + " is: "+pow);
}
}

OUTPUT :-
Enter the base: 11
Enter the exponent: 3
11 to the power 3 is: 1331
Q-3:- Program to print Fibonacci series ?

class FibonacciExample1{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed


{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

OUTPUT :-
0 1 1 2 3 5 8 13 21 34
Q-4:- Program to print largest, middle and
smallest value among three values ?
import java.util.Scanner;
class Small_Large
{
public static void main (String args[])
{
Scanner scan=new Scanner(System.in);
System.out.print("Enter the first number: ");
float num1=scan.nextFloat();//get input from user for num1
System.out.print("Enter the second number: ");
float num2=scan.nextFloat();//get input from user for num2
System.out.print("Enter the third number: ");
float num3=scan.nextFloat();//get input from user for num3
if(num1<=num2 && num1<=num3)
{
System.out.println("\n The Smallest number is: "+num1);
}
else if(num2<=num1 && num2<=num3)
{
System.out.println("\n The Smallest number is: "+num2);
}
else{
System.out.println("\n The Smallest number is: "+num3);
}
if(num1>=num2 && num1>=num3){
System.out.println("\n The Smallest number is: "+num1);
}
else if(num2>=num1 && num2>=num3){
System.out.println("\n The Smallest number is: "+num2);
}
else{
System.out.println("\n The largest number is: "+num3);
}
}
}

OUTPUT :-

Enter the first number: 12.34


Enter the second number: 34.56
Enter the third number: 56.78
The smallest number is 12.34
The Largest number is 56.78
Q-5:- Program to print rectangular shape using
any character ?

import java.util.Scanner;

public class RectangleStar3 {


private static Scanner sc;
public static void main(String[] args)
{
int rows, columns, i, j;
char ch;
sc = new Scanner(System.in);

System.out.print(" Please Enter Number of Rows : ");


rows = sc.nextInt();

System.out.print(" Please Enter Number of Columns : ");


columns = sc.nextInt();

System.out.print(" Please Enter any Character : ");


ch = sc.next().charAt(0);

for(i = 1; i <= rows; i++)


{
for(j = 1; j <= columns; j++)
{
System.out.print(ch + " ");
}
System.out.print("\n");
}
}
}

OUTPUT :-

Please Enter Number of Rows : 8


Please Enter Number of Columns : 22
Please Enter any Character : *

**********************
**********************
**********************
**********************
**********************
**********************
**********************
Q-6:- Program to implement arrays ?
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

OUTPUT :-
10
20
70
40
50
Q-7:- Program to implement type casting using wrapper classes &
methods such as parseInt( ) ?
Q-8:- Program to implement command line arguments?
class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

compile by > javac CommandLineExample.java


run by > java CommandLineExample sonoo

OUTPUT :-
Your first argument is: sonoo
Q-9:- Program to implement string handling functions ?

class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();
System.out.println("Length: " + length);
}
}

OUTPUT :-

String: Hello! World


Length: 12
Q-10:- Program to implement constructors?

class Bike1
{
//creating a default constructor
Bike1(){System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

OUTPUT :-

Bike is created
Q-11:- Write Java Program to implement multilevel inheritance and
hierarchical inheritance ?

Multilevel inheritance:-

class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}

OUTPUT :-

Inside display
Inside area
Inside volume

Hierarchical inheritance :-

// creating the base class(or superclass)


class BaseClass
{
int parentNum = 10;
}
// creating the subclass1 that inherits the base class
class SubClass1 extends BaseClass
{
int childNum1 = 1;
}

// creating the subclass2 that inherits the base class


class SubClass2 extends BaseClass
{
int childNum2 = 2;
}

// creating the subclass3 that inherits the base class


class SubClass3 extends BaseClass
{
int childNum3 = 3;
}
public class Main
{
public static void main(String args[])
{
SubClass1 childObj1 = new SubClass1 ();
SubClass2 childObj2 = new SubClass2 ();
SubClass3 childObj3 = new SubClass3 ();

System.out.println("parentNum * childNum1 = " + childObj1.parentNum * childObj1.childNum1);


// 10 * 1 = 10
System.out.println("parentNum * childNum2 = " + childObj2.parentNum * childObj2.childNum2);
// 10 * 2 = 20
System.out.println("parentNum * childNum3 = " + childObj3.parentNum * childObj3.childNum3);
// 10 * 3 = 30
}
}

OUTPUT:-

parentNum * childNum1 = 10
parentNum * childNum2 = 20
parentNum * childNum3 = 30
Q-12:- Program to implement interfaces ?

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

OUTPUT :-

Hello
Q-13:- Program to implement abstract class and methods ?

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

OUTPUT :-

running safely
Q-15:- Program to implement multiple inheritance ?
interface PI1 {
// Default method
default void show()
{
System.out.println("Default PI1");
}
}

// Interface 2
interface PI2 {
default void show()
{
System.out.println("Default PI2");
}
}

// Main class
// Implementation class code
class TestClass implements PI1, PI2 {
// Overriding default show method
@Override
public void show()
{
// Using super keyword to call the show
// method of PI1 interface
PI1.super.show();//Should not be used directly in the main method;

// Using super keyword to call the show


// method of PI2 interface
PI2.super.show();//Should not be used directly in the main method;
}

//Method for only executing the show() of PI1


public void showOfPI1() {
PI1.super.show();//Should not be used directly in the main method;
}

//Method for only executing the show() of PI2


public void showOfPI2() {
PI2.super.show(); //Should not be used directly in the main method;
}

// Mai driver method


public static void main(String args[])
{
// Creating object of this class in main() method
TestClass d = new TestClass();
d.show();
System.out.println("Now Executing showOfPI1() showOfPI2()");
d.showOfPI1();
d.showOfPI2();
}
}

OUTPUT:-

Default PI1
Default PI2
Now Executing showOfPI1() showOfPI2()
Default PI1
Default PI2
Q-15:- Program to implement polymorphism by method overriding
and overloading ?

Method Overloading:-

import java.io.*;

class MethodOverloadingEx {

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

public static void main(String args[])


{
System.out.println("add() with 2 parameters");
System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");


System.out.println(add(4, 6, 7));
}
}

OUTPUT :-

add() with 2 parameters


10
add() with 3 parameters
17
Method overriding :-

import java.io.*;
class Animal {
void eat()
{
System.out.println("eat() method of base class");
System.out.println("eating.");
}
}

class Dog extends Animal {


void eat()
{
System.out.println("eat() method of derived class");
System.out.println("Dog is eating.");
}
}
class MethodOverridingEx {
public static void main(String args[])
{
Dog d1 = new Dog();
Animal a1 = new Animal();

d1.eat();
a1.eat();

Animal animal = new Dog();


// eat() method of animal class is overridden by
// base class eat()
animal.eat();
}
}

OUTPUT :-

eat() method of derived class


Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.
Q-16:- Program to implement nested classes and anonymous classes ?

// Java program to demonstrate Need for


// Anonymous Inner class

// Interface
interface Age {

// Defining variables and methods


int x = 21;
void getAge();
}

// Class 1
// Helper class implementing methods of Age Interface
class MyClass implements Age {

// Overriding getAge() method


@Override public void getAge()
{
// Print statement
System.out.print("Age is " + x);
}
}

// Class 2
// Main class
// AnonymousDemo
class GFG {
// Main driver method
public static void main(String[] args)
{
// Class 1 is implementation class of Age interface
MyClass obj = new MyClass();

// calling getage() method implemented at Class1


// inside main() method
obj.getAge();
}
}

OUTPUT :-

Age is 21
Q-17:- Program to implement static methods and variables ?

class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

OUTPUT :-
111 Karan ITS
222 Aryan ITS
Q-18:- Program to implement final keywords for objects, methods and
classes?

Final Keywords for method:-

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

OUTPUT :-
Compile Time Error.

Final Keyward for class:-

final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

OUTPUT :-
Compile Time Error
Q-19:- Program to implement packages ?

package p1;
class C1()
{
public void m1()
{
System.out.println("m1 of C1");
}
public static void main(string args[])
{
C1 obj = new C1();
obj.m1();
}
}
Q-20:- Program to implement access protection such as public,
protected, private and defaults ?

PRIVATE:-

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

PROTECTED:-

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

OUTPUT:- Hello
DEFAULT:-

//save by A.java
package pack;
class A{
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();//Compile Time Error
obj.msg();//Compile Time Error
}
}

PUBLIC:-

//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
Q-21:- Program to implement exception handling with checked
exceptions ?
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

OUTPUT :-

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...
Q-22:- Program to implement exception handling with user defined
exceptions?

class InvalidAgeException extends Exception


{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}
Q-23:- Program to implement multithreading using runnable
interface?

public class ExampleClass implements Runnable {

@Override
public void run() {
System.out.println("Thread has ended");
}

public static void main(String[] args) {


ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
t1.start();
System.out.println("Hi");
}
}

OUTPUT :-
Hii
Thread has ended
Q-24:- Program to implement multithreading using Thread class?

class ThreadDemo extends Thread {


private Thread t;
private String threadName;

ThreadDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2");


T2.start();
}
}
OUTPUT:-
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Q-25:- Program to implement synchronize block and methods to
handle threads?

class Table
{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronizedBlock1{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
OUTPUT :-
5
10
15
20
25
100
200
300
400
500
Q-26 :- Program to implement GUI program using AWT?

import java.awt.*;

public class AwtProgram1 {


public AwtProgram1()
{
Frame f = new Frame();
Button btn=new Button("Hello World");
btn.setBounds(80, 80, 100, 50);
f.add(btn); //adding a new Button.
f.setSize(300, 250); //setting size.
f.setTitle("JavaTPoint"); //setting title.
f.setLayout(null); //set default layout for frame.
f.setVisible(true); //set frame visibility true.
}

public static void main(String[] args) {


// TODO Auto-generated method stub

AwtProgram1 awt = new AwtProgram1(); //creating a frame.


}
}

OUTPUT:-
Q-27:- Program to implement to develop calculator application with
event handling?

// Java program to create a simple calculator


// with basic +, -, /, * using java swing elements

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;

// create a textfield
static JTextField l;

// store operator and operands


String s0, s1, s2;

// default constructor
calculator()
{
s0 = s1 = s2 = "";
}

// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");

try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}

// create a object of class


calculator c = new calculator();

// create a textfield
l = new JTextField(16);

// set the textfield to non editable


l.setEditable(false);

// create number buttons and some operators


JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;

// create number buttons


b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// equals button
beq1 = new JButton("=");

// create operator buttons


ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");

// create . button
be = new JButton(".");

// create a panel
JPanel p = new JPanel();

// add action listeners


bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);

// add elements to panel


p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);

// set Background of panel


p.setBackground(Color.blue);

// add panel to frame


f.add(p);

f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

// if the value is a number


if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";

// set the value of text


l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {

double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// set the value of text


l.setText(s0 + s1 + s2 + "=" + te);

// convert it to string
s0 = Double.toString(te);

s1 = s2 = "";
}
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;

// store the value in 1st


if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// convert it to string
s0 = Double.toString(te);

// place the operator


s1 = s;

// make the operand blank


s2 = "";
}

// set the value of text


l.setText(s0 + s1 + s2);
}
}
}

OUTPUT:-

You might also like