Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
93 views

Java F

This document contains 15 questions related to Java programming concepts like object oriented programming, classes, inheritance, polymorphism, interfaces, exceptions, threads, and string operations. The questions cover basic syntax and usage of these Java features through examples like printing odd numbers, calculating factorials recursively, command line arguments, Fibonacci series, class accounts with methods for transactions, constructor overloading, method overloading and overriding, interfaces, exceptions, matrix multiplication using 2D arrays, user defined exceptions, even/odd numbers using threads, array lists, and string class methods.

Uploaded by

neeraj kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Java F

This document contains 15 questions related to Java programming concepts like object oriented programming, classes, inheritance, polymorphism, interfaces, exceptions, threads, and string operations. The questions cover basic syntax and usage of these Java features through examples like printing odd numbers, calculating factorials recursively, command line arguments, Fibonacci series, class accounts with methods for transactions, constructor overloading, method overloading and overriding, interfaces, exceptions, matrix multiplication using 2D arrays, user defined exceptions, even/odd numbers using threads, array lists, and string class methods.

Uploaded by

neeraj kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Vivekananda Institute of Professional Studies

Master of Computer Applications

OBJECT ORIENTED PROGRAMMING AND JAVA

Guru Gobind Singh lndraprastha University

Submitted To: DR. NEHA VERMA MALHOTRA Submitted By: Neeraj Kumar
Professor MCA 1B

VSIT 06717704422
QUESTION 1: Write a Java program to print all odd numbers between 1 to 10.

QUESTION 2: Write a Java program to find out factorial of a number through recursion

QUESTION 3: Write a Java program to accept command line arguments & print them
QUESTION 4: Write a Java program to print fibonacci series.

QUESTION 5: Write a Java program that creates a class accounts with following details: Instance variables: ac_no., name,
ac_name, balance. Methods: withdrawal (), deposit (), display (). Use constructors to initialize members.
QUESTION 6: Write a Java program to implement constructor overloading.
QUESTION 7: Write a Java program to count the no. of objects created in a program.

QUESTION 8: Write a Java program to show call by value & call by reference.
QUESTION 9: Write a Java program to implement method over ridding & method overloading.

OVER RIDDING

class Add
{
void display(int a, int b)
{
System.out.println("SUM OF "+a+" AND "+b+": "+(a+b));
}
}
class Mul extends Add
{
void display(int a, int b)
{
System.out.println("PRODUCT OF "+a+" AND "+b+": "+(a*b));
}
}

public class file {

public static void main(String[] args) {


Add x = new Add();
Add y = new Mul();
x.display(2,3);
y.display(4,5);

}
}

OVER LOADING

QUESTION 10: Create a class box having height, width, depth as the instance variables & calculate its volume. Implement
constructor overloading in it. Create a subclass named box_new that has weight as an instance variable. Use super in the
box_new class to initialize members of the base class.

class box
{
int height, width,depth;
box()
{
height=width=depth=19;
}
box(int h,int w,int d)
{
height=h;
width=w;
depth=d;
}
void volume()
{
System.out.println("Volume of BOX: "+height*width*depth);
}
}
class box_new extends box
{
int weight;
box_new()
{
super();
weight=13;
}
box_new(int a,int b,int c,int d)
{
super(a,b,c);
weight=d;
}
void show()
{
volume();
System.out.println("Weight of BOXNEW: "+weight);

QUESTION 11: Write a Java program to implement run time polymorphism.

class Add
{
void display(int a, int b)
{
System.out.println("SUM OF "+a+" AND "+b+": "+(a+b));
}
}
class Mul extends Add
{
void display(int a, int b)
{
System.out.println("PRODUCT OF "+a+" AND "+b+": "+(a*b));
}

public class file {

public static void main(String[] args) {

Add x = new Add();


Add y = new Mul();
x.display(2,3);
y.display(4,5);

}
}
QUESTION 12: Write a Java program to implement interface. Create an interface named shape having area () & perimeter
() as its methods. Create three classes circle, rectangle & square that implement this interface. }

interface Shape
{
double area();
double perimeter();
}
class Rectangle implements Shape
{
private double length;
private double breadth;
public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
public double area()
{
return length * breadth;
}
public double perimeter()
{
return 2 * (length + breadth);
}
}
class Circle implements Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double area()
{
return Math.PI * radius * radius;
}
public double perimeter()
{
return 2 * Math.PI * radius;
}
}
class Square implements Shape
{private double side;
public Square(double side)
{
this.side = side;
}
public double area()
{
return side * side;
}
public double perimeter()
{
return 4 * side;
}
}

public class file {

public static void main(String[] args) {

Shape rectShape = new Rectangle(8, 12);


Shape circShape = new Circle(5);
Shape squareShape = new Square(10);
System.out.println("Area of Rectangle: " + rectShape.area());
System.out.println("Perimeter of Rectangle: " + rectShape.perimeter());
System.out.println("Area of Circle: " + circShape.area());
System.out.println("Perimeter of Circle: " + circShape.perimeter());
System.out.println("Area of Square: " + squareShape.area());
System.out.println("Perimeter of Square: " + squareShape.perimeter());

}
QUESTION 13: Write a Java program to show multiple inheritance.

interface Length
{
int l=10;
void displayLength();
}
interface Breadth
{
int b=5;
void displayBreadth();
}
class Rectangle implements Length, Breadth
{
public void displayLength()
{
System.out.println("LENGTH OF RECTANGLE:"+l);
}
public void displayBreadth()
{
System.out.println("BREADTH OF RECTANGLE:"+b);
}

public class file {

public static void main(String[] args) {

Rectangle r = new Rectangle();


r.displayLength();
r.displayBreadth();

QUESTION 14: Write a Java program to implement exception handling. Use try, catch & Finally.

public class file {

public static void main(String[] args) {


int a=40,b=0,c;
try
{
c=a/b;
}
catch (ArithmeticException e)
{
System.out.println("CANNOT DIVIDE BY ZERO!");
}
finally
{
System.out.println("FINALLY BLOCK");
}
c=b/a;
System.out.println("RESULT: "+c);
}
}

}
}
QUESTION 15: Write a Java program to implement matrix multiplication by 2d array

public class file {

public static void main(String[] args) {

int a[][]={{2,3,3},{3,2,2},{2,2,2}};
int b[][]={{4,3,2},{4,2,3},{3,4,3}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}
QUESTION 17: Create a user defined exception named “nomatchexception” that is fired when the string entered by the
user is not “india”.

import java.util.Scanner;
class NoMatchException extends Exception
{
String s1;
NoMatchException(String s2)
{
this.s1 = s2;
}
public String toString()
{
return s1;
}
}

public class file {

public static void main(String[] args) {


String s3;
Scanner sc = new Scanner(System.in);
System.out.println("ENTER A STRING: ");
s3 = sc.nextLine();
try {
if (!"india".equalsIgnoreCase(s3))
throw new NoMatchException("NoMatchException CAUGHT!!!");
else
{
System.out.println("STRING MATCHED!!!");
}
}
catch (NoMatchException e)
{
System.out.println(e);
}
}
}

QUESTION 18: Write a Java program to show even & odd numbers by thread.

class Even extends Thread


{
public void run()
{
for(int i=0;i<=5;i+=2)
System.out.println("Even Num: "+i);
System.out.println("In EVEN Class");
}
}
class Odd extends Thread{
public void run(){
for(int i=1;i<=5;i+=2)
System.out.println("Odd Num: "+i);
System.out.println("In Odd Class");
}
}

public class file {

public static void main(String[] args) {


Even obj1=new Even();
Odd obj2=new Odd();
obj1.start();
obj2.start();

}
}

QUESTION 19: Write a Java program to iterate through all elements in an array list.

public class file {

public static void main(String[] args) {


ArrayList<Integer> arr = new ArrayList<Integer>(4);

arr.add(15);
arr.add(25);
arr.add(35);
arr.add(45);

System.out.println("ARRAY LIST: " + arr);

int element = arr.get(3);

System.out.println("THE ELEMENT AT INDEX 3: " + element);

}
}
24. QUESTION 24: Write a Java program to demonstrate the use of equals(), trim() ,length() ,substring(),
compareto() of string class.

public class file {

public static void main(String[] args) {


String str1="Neeraj";
String str2="Neeraj";
String str3="My Name Is Neeraj";
String str4=" Remove Space";
System.out.println(str1.equals(str2));
System.out.println("String Without Trim: "+str4);
System.out.println("Trimmed String: " + str4.trim());
System.out.println("Length of string (" + str3 +"): " + str3.length());
System.out.println("Substring ("+str3+"): " + str3.substring(4));
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str3));

}
25.
public class file {

public static void main(String[] args) {


String str1="Hello World";
String str2 ="Hello World";
String str3 = new String("Hello World");

System.out.println(str1.equals(str2));
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str1.equals(str3));

}
}
}

QUESTION 27: Write a Java program to implement keyboard events.

CODE:

import java.awt.event.*;
import java.applet.*;
import java.awt.*;

/*<applet code = "KeyboardEvents.class" width = 300 height =200>


</applet>
*/

public class KeyboardEvents extends Applet implements KeyListener


{
String msg= " ";
int x,y;

public void init()


{
x=10;
y=10;
addKeyListener(this);
}

public void keyPressed(KeyEvent ky)


{
showStatus("Key Pressed!!");
}

public void keyReleased(KeyEvent ky)


{
showStatus("Key Released!!");
}

public void keyTyped(KeyEvent ky)


{
msg+=ky.getKeyChar();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,x,y);

}
}
OUTPUT:
QUESTION 28: Write a Java program using AWT to create a simple calculator.

CODE:

import java.awt.*;
import java.awt.event.*;

class Calculator extends Frame implements ActionListener


{

TextField tfInput;
Panel panel;
String btnString[] = {"7", "8", "9", "+","4", "5", "6", "-","1", "2", "3", "*","C", "0", "=", "/"};
Button btn[] = new Button[16];
int num1 = 0, num2 = 0, result = 0;
char op;

public Calculator()
{

Font f = new Font("Cambria", Font.BOLD, 18);


tfInput = new TextField(10);
tfInput.setFont(f);

panel = new Panel();

add(tfInput, "North");
add(panel, "Center");

panel.setLayout(new GridLayout(4,4));

for(int i=0; i < 16; i++)


{

btn[i] = new Button(btnString[i]);


btn[i].setFont(f);
btn[i].addActionListener(this);
panel.add(btn[i]);
}

addWindowListener(new WindowAdapter()
{

public void windowClosing(WindowEvent we)


{
System.exit(0);
}
});
}

public void actionPerformed(ActionEvent ae)


{

String str = ae.getActionCommand();

if(str.equals("+"))
{

op = '+';
num1 = Integer.parseInt(tfInput.getText());
tfInput.setText("");
}

else if(str.equals("-"))
{
op = '-';
num1 = Integer.parseInt(tfInput.getText());
tfInput.setText("");
}
else if(str.equals("*"))
{
op = '*';
num1 = Integer.parseInt(tfInput.getText());
tfInput.setText("");
}

else if(str.equals("/"))
{
op = '/';
num1 = Integer.parseInt(tfInput.getText());
tfInput.setText("");
}

else if(str.equals("="))
{

num2 = Integer.parseInt(tfInput.getText());

switch(op)
{

case '+' : result = num1 + num2;


break;
case '-' : result = num1 - num2;
break;
case '*' : result = num1 * num2;
break;
case '/' : result = num1 / num2;
break;
}

tfInput.setText(result + "");
result = 0;
}

else if(str.equals("C"))
{

tfInput.setText("");
num1 = num2 = result = 0;
}

else
{
tfInput.setText(tfInput.getText() + str);
}
}
public static void main(String args[])
{

Calculator m = new Calculator();


m.setTitle("Calculator");
m.setSize(250,300);
m.setVisible(true);
}
}

OUTPUT:
QUESTION 29: Create a Java applet with three buttons ‘red’,’green’,’blue’. Whenever user presses any
button the corresponding color should be seen as background color in an applet window.

CODE:

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*

<applet code="ChangeBackground.class" width=300 height=100>

</applet>

*/

public class ChangeBackground extends Applet implements ActionListener


{
Button Red,Blue,Green;

public void init()


{

Red = new Button("Red");

add(Red);

Red.addActionListener(this);

Blue = new Button("Blue");

add(Blue);

Blue.addActionListener(this);
Green = new Button("Green");

add(Green);

Green.addActionListener(this);

public void actionPerformed(ActionEvent e)


{

if (e.getSource() == Red)
{

setBackground(Color.red);

else if (e.getSource() == Blue)

setBackground(Color.blue);

else if (e.getSource() == Green)

setBackground(Color.green);

public void paint(Graphics g)


{

OUTPUT:
QUESTION 30: Write a Java program to show all layout managers (4 layout managers).

CODE:

import java.awt.*;
import javax.swing.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="LayoutManagers.class" width=500 height=500>
</applet>
*/
public class LayoutManagers extends Applet implements ActionListener
{
CardLayout cl = new CardLayout();
JPanel Card;

public void init()


{
JPanel Flow = new JPanel();
Flow.setLayout(new FlowLayout());
Button b1 = new Button("1");
Button b2 = new Button("2");
Button b3 = new Button("3");
Button b4 = new Button("4");
Flow.add(b1);
Flow.add(b2);
Flow.add(b3);
Flow.add(b4);
JPanel Grid = new JPanel();
Grid.setLayout(new GridLayout(3, 2));
Button Gb1 = new Button("1");
Button Gb2 = new Button("2");
Button Gb3 = new Button("3");
Button Gb4 = new Button("4");
Grid.add(Gb1);
Grid.add(Gb2);
Grid.add(Gb3);
Grid.add(Gb4);
Card = new JPanel();
Card.setLayout(cl);
Button Cb1 = new Button("1");
Button Cb2 = new Button("2");
Button Cb3 = new Button("3");
Button Cb4 = new Button("4");
Cb1.addActionListener(this);
Cb2.addActionListener(this);
Cb3.addActionListener(this);
Cb4.addActionListener(this);
Card.add(Cb1, "1");
Card.add(Cb2, "2");
Card.add(Cb3, "3");
Card.add(Cb4, "4");
JPanel Border = new JPanel();
Border.setLayout(new BorderLayout());
Button Bb1 = new Button("1");
Button Bb2 = new Button("2");
Button Bb3 = new Button("3");
Button Bb4 = new Button("4");
Border.add(Bb1, BorderLayout.EAST);
Border.add(Bb2, BorderLayout.CENTER);
Border.add(Bb3, BorderLayout.WEST);
Border.add(Bb4, BorderLayout.NORTH);
add(new Label("*Flow Layout Manager*"));
add(Flow);
add(new Label("*Grid Layout Manager*"));
add(Grid);
add(new Label("*Card Layout Manager*"));
add(Card);
add(new Label("*Border Layout Manager*"));
add(Border);
setLayout(new GridLayout(8,1));
}
public void actionPerformed(ActionEvent e)
{
cl.next(Card);
}
}
OUTPUT:
QUESTION 31: Create an applet with two buttons named ‘audio’ and ‘image’. When user will press button
‘audio’ then an audio file should play in applet, and if user press button ‘image’ then an
image should see in applet window.

CODE:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="ImageAndAudio.class" width=300 height=300>
<param name="msg" value="Hello World">
</applet>
*/
public class ImageAndAudio extends Applet implements ActionListener
{
Button b1, b2;
Image img;
public void init()
{
b1 = new Button("IMAGE");
b2 = new Button("AUDIO");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
if (ae.getSource() == b1)
{
img = getImage(getDocumentBase(), "Space.jpg");
repaint();
}

if (ae.getSource() == b2)
{
AudioClip ac = getAudioClip(getDocumentBase(),"Music.wav");
ac.play();
repaint();
}
}

public void paint(Graphics g)


{
g.drawImage(img, 0, 0, this);
}
protected void finalize() throws Throwable
{

super.finalize();
}
}

OUTPUT:

QUESTION 32: Create a Java applet with three buttons ‘red’,’green’,’blue’. Whenever user presses any
button the corresponding color should be seen as background color in an applet window.

CODE:

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*

<applet code="ChangeBackground.class" width=300 height=100>

</applet>

*/

public class ChangeBackground extends Applet implements ActionListener


{
Button Red,Blue,Green;

public void init()


{

Red = new Button("Red");

add(Red);

Red.addActionListener(this);

Blue = new Button("Blue");

add(Blue);

Blue.addActionListener(this);

Green = new Button("Green");

add(Green);

Green.addActionListener(this);

public void actionPerformed(ActionEvent e)


{
if (e.getSource() == Red)
{

setBackground(Color.red);

else if (e.getSource() == Blue)

setBackground(Color.blue);

else if (e.getSource() == Green)

setBackground(Color.green);

public void paint(Graphics g)


{

OUTPUT:
QUESTION 36: Write a Java program in Java to create database table using Java.
CODE:

import java.sql.*;
public class Jdbc36
{
public static void main(String[] args)
{
Connection connection = null;
String query;
ResultSet result;
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/","12345", "12345");

Statement stmt = connection.createStatement();


query = "CREATE DATABASE java_database";
stmt.executeUpdate(query);
System.out.println("Database Created Successfully!!");
connection.close();
}

catch (Exception exception)


{
System.out.println(exception);
}

}
}

OUTPUT:
QUESTION 37: Write a Java program in Java to insert, update, delete & select records.

CODE:

import java.sql.*;
public class Jdbc37
{
public static void main(String[] args)
{
Connection connection = null;
String query;
ResultSet result;
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/java_database","12345", "12345");

Statement stmt = connection.createStatement();

query = "INSERT INTO Recipies(recipe_id, recipe_name)"


+ " VALUES"
+ "(6,\"Momos\"), "
+ "(7,\"Spring Roll\"), "
+ "(8,\"Burger\"), "
+ "(9,\"Pizza\"), "
+ "(10,\"Garlic Bread\"); ";
stmt.executeUpdate(query);
System.out.println("Inserted records into the table...");
query = "SELECT * FROM Recipies;";
result = stmt.executeQuery(query);
while(result.next()){
System.out.print("Recipie ID: " + result.getInt("recipe_id"));
System.out.print("Recipie Name: " + result.getString("recipe_name"));
System.out.println("\n");
}

query = "UPDATE Recipies " +


"SET recipe_name = 'My Recipie' WHERE recipe_id = 4";
stmt.executeUpdate(query);
System.out.println("Record Successfully Updated!!!!\n");
query = "SELECT * FROM Recipies;";
result = stmt.executeQuery(query);
while(result.next()){
System.out.print("Recipie ID: " + result.getInt("recipe_id"));
System.out.print("Recipie Name: " + result.getString("recipe_name"));
System.out.println("\n");
}

query = "DELETE FROM Recipies where recipe_id = 3";


stmt.executeUpdate(query);
System.out.println("Record Successfully Deleted!!!!\n");
query = "SELECT * FROM Recipies;";
result = stmt.executeQuery(query);
while(result.next()){
System.out.print("Recipie ID: " + result.getInt("recipe_id"));
System.out.print("|Recipie Name: " + result.getString("recipe_name"));
System.out.println("\n");
}

connection.close();
}
catch (Exception exception)
{
System.out.println(exception);
}

}
}
OUTPUT:
QUESTION 38: Write Java program to read input from java console.

public class file {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.print("\n Enter a string: ");
String inputString = input.nextLine();
System.out.println("\n String: " + inputString);
input.close();

}
}

QUESTION 39: Write a Java program to implement file handling(both reading & writing to a file).

CODE:

import java.io.*;
import java.util.Scanner;

class FileHandling
{
static String fileName = "file.txt";

static void writeFile() throws IOException


{
FileWriter file = new FileWriter(fileName);
file.write("My Name Is Rahul Mishra.");
System.out.println("File is created successfully!!!");
file.close();
}

static void readFile() throws IOException


{
FileReader file = new FileReader(fileName);
Scanner reader = new Scanner(file);
String data = reader.nextLine();
System.out.println("Data in file: " + data);
reader.close();
file.close();
}

public static void main(String[] args)


{
try
{
writeFile();
readFile();
}

catch (IOException e)
{
System.out.println("Error occurred: " + e);
}
}
}

OUTPUT:

QUESTION 40: Write a Java program on anonymous classes.

class Demo
{
public void view()
{
System.out.println("Inside The Demo Class!");
}
}
class MyClass
{
public void myMethod()
{

Demo d1 = new Demo()


{
public void view()
{
System.out.println("Inside The Anonymous Class!!");
}
};
d1.view();
}
}

public class file {

public static void main(String[] args) {

MyClass cls = new MyClass();


cls.myMethod();

}
}

QUESTION 41: Write a Java program to highlight the structure/syntax of a lambda expression.

interface Operation
{
int calculate(int a);
}

public class file {

public static void main(String[] args) {

Operation square = (a) -> a * a;


int num = 3;
int result = square.calculate(num);
System.out.printf("Square Of %d: %d", num, result);

}
}

QUESTION 42: Write a Java program to check a word contains the character 'g' in a given string.
public class file {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.print("\n Enter A String: ");
String s = input.nextLine();

if (s.contains("g"))
{
System.out.println("\n String \"" + s + "\" contains character \'g\'!!");
}

else
{
System.out.println("\n String \"" + s + "\" does not contains character \'g\'!!");
}

}
}

QUESTION 42: Write a Java program to find sequences of lowercase letters joined with an underscore.

public class file {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);


System.out.print("\n Enter a string: ");
String s = input.nextLine();
if (s.matches("^[a-z]+_[a-z]+$"))
{
System.out.println("\n Match found!");
}

else
{
System.out.println("\n Match not found!");
}

}
}

You might also like