Вы находитесь на странице: 1из 40

1.

Menu Driven Program

package demo;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
int s,n,ch,i;
char ans;
Scanner S=new Scanner(System.in);
do
{
System.out.println("Enter a Number - \n");
n=S.nextInt();
System.out.println("Enter 1 to check even/odd ");
System.out.println("Enter 2 to check Prime/NonPrime ");
System.out.println("Enter 3 to print Factorial ");
System.out.println("Enter 4 t122o print Fibonacci ");
System.out.println("Enter 5 to check Armstrong ");
System.out.println("Enter 6 to check Palindrome ");
System.out.println("Enter 7 to print Tables ");
ch=S.nextInt();
switch(ch)
{
case 1:
if(n%2==0)
System.out.println("Even");
else
System.out.println("Odd");
break;
case 2:
boolean flag=false;
for(i=2;i<n/2;i++)
{
if(n%i==0)
{
flag=true;
break;
}
}
if(flag)
System.out.println("Not Prime ");
else
System.out.println("Prime ");
break;
case 3:
s=1;
for(i=1;i<n;i++)
{
s+=s*i;
}
System.out.println("Factorial is - "+s);
break;
case 4:
int a=0; int b=1; int c;
c=a+b;
System.out.println(a+" ,"+b+" ,"+c);
for(i=0;i<n-3;i++)
{
a=b;
b=c;
c=a+b;
System.out.print(" ,"+c);
}
break;
case 5:
int on,rem,re= 0,po=0;
on=n;
while(on!=0){
on=on/10;
po++;
}
on=n;
while(on!=0){
rem=on%10;
re+=Math.pow(rem,po);
on=on/10;
}
if(re==n)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n+ " is not an Armstrong number.");
break;
case 6:
int rev=0,rema,oi;
oi=n;
while(oi!=0){
rema=oi%10;
rev=rev*10+rema;
oi=oi/10;
}
if(rev==n)
System.out.println(n + " is a palindrome.");
else
System.out.println(n + " is not a palindrome.");
break;
case 7:
System.out.println("Tables of "+n);
for(i=1;i<=10;i++){
System.out.println(n*i);
}
break;
}
System.out.println("Continue? (Y/N)");
ans=S.next().charAt(0);
}while(ans=='y');
}
}
2. Write a program to find SUM AND PRODUCT of a given Number’s Digits.

import java.util.Scanner;
public class Digits {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Digits Sum and Product");
System.out.println("-----------------------");
System.out.print("Enter Number: ");
int number = in.nextInt();
int remainder, temp, sum=0, product=1;
temp = number;
while (temp!=0) {
remainder = temp % 10;
sum = sum + remainder;
product = product * remainder;
temp = temp / 10; }
System.out.println("Sum of digits of Number '"+number+"'': "+sum);
System.out.println("Product of digits of Number "+number+" '': "+product);
}
}
3. Write a program to find sum of all integers greater than 100 and less than 200
that are divisible by 7

package javaapplication1;
public class div7
{
public static void main(String args[])
{
int sum=0;
for(int i=100;i<=200;i++)
{
if(i%7==0)
sum=sum+i;
}
System.out.println("The sum of integers divisible by 7 is "+sum);
}
}
4.Given a string, return a new string where the first and last chars have been
exchanged.
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"

package javaapplication1;
import java.util.Scanner;
public class str1
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a string");
s=in.next();
System.out.println("The entered string is "+s);
int len=s.length();
if(len==1)
System.out.println("Converted string is "+s);
else
{
String ch1=s.substring(0,1);
String ch2=s.substring(len-1,len);
String s1;
s1=ch2+s.substring(1, len-1)+ch1;
System.out.println("Coverted String is "+s1);
}
}
}
5.Given a string, take the last char and return a new string with the last char
added at the front and back, so "cat" yields "tcatt". The original string will be
length 1 or more.
backAround("cat") → "tcatt"
backAround("Hello") → "oHelloo"
backAround("a") → "aaa"

package javaapplication1;
import java.util.Scanner;
public class str2 {
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String s;
System.out.println("Enter a string");
s=in.next();
System.out.println("The entered string is "+s);
int len=s.length();
String ch1=s.substring(len-1,len);
String s1;
s1=ch1+s.substring(0, len)+ch1;
System.out.println("Coverted String is "+s1);
}
}
6.Design a class to represent a bank account. Include the following members:
Data Members
->Name of the depositor
->Account Number
->Type of Account
->Balance amount in the account
Methods
->To assign initial values
->To deposit an amount
->To withdraw an amount after checking balance
->To display the name and balance

package javaapplication1;
import java.util.Scanner;
class bank
{
String name,type;
int accno,bal;
bank()
{
name="N/A";
type="N/A";
bal=accno=0;
}
void enter()
{
Scanner in=new Scanner(System.in);
System.out.println("Fill up the fields:");
System.out.println("Enter the Name of Depositer:");
name=in.nextLine();
System.out.println("Enter the Account Number:");
accno=in.nextInt();
System.out.println("Enter the Type of Account:");
type=in.next();
System.out.println("Enter the Balance:");
bal=in.nextInt();
System.out.println("");
}
void display()
{
System.out.println("");
System.out.println("Name of the Depositor: "+name);
System.out.println("Account Number: "+accno);
System.out.println("Type of Account: "+type);
System.out.println("Balance Amount: "+bal);
System.out.println("");
}
void withdraw(int a)
{
System.out.println("");
if(bal<a)
System.out.println("NOT ENOUGH BALANCE!!! WITHDRAW CANCELLED!!");
else
{
bal=bal-a;
System.out.println("WITHDRAWN...");
System.out.println("New balance is "+bal);
}
System.out.println("");
}
void deposit(int b)
{
bal=bal+b;
System.out.println("");
System.out.println("DEPOSITED...");
System.out.println("New balance is "+bal);
System.out.println("");
}
}
public class bank1 {
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
bank b1=new bank();
b1.enter();
b1.display();
System.out.println("Enter the balance amount to be deposited: ");
int a=in.nextInt();
b1.deposit(a);
b1.display();
System.out.println("Enter the balance amount to be withdrawn: ");
int b=in.nextInt();
b1.withdraw(b);
b1.display();
}

}
7.Create a superclass, Student, and two subclasses, Undergrad and Grad.
 The superclass Student should have the following data members: name, ID, grade,
age, and address.
 The superclass, Student should have at least one method: boolean is Passed (double
grade)
The purpose of the is Passed method is to take one parameter, grade (value between 0 and
100) and check whether the grade has passed the requirement for passing a course. In the
Student class this method should be empty as an abstract method.
 The two subclasses, Grad and Undergrad, will inherit all data members of the Student
class and override the method is Passed. For the UnderGrad class, if the grade is
above 70.0, then is Passed returns true, otherwise it returns false. For the Grad class,
if the grade is above 80.0, then is Passed returns true, otherwise returns false.
 Create a test class for your three classes. In the test class, create one Grad object and
one Undergrad object. For each object, provide a grade and display the results of the
is Passed method.

package javaapplication1;
import java.util.Scanner;
abstract class Student
{
String name,address;
int ID,age;
double grade;
abstract boolean isPassed(double grade);
void enter()
{
Scanner in=new Scanner(System.in);
System.out.println("");
System.out.println("Enter the name of Student: ");
name=in.next();
System.out.println("Enter the Address: ");
address=in.next();
System.out.println("Enter ID: ");
ID=in.nextInt();
System.out.println("Enter age: ");
age=in.nextInt();
System.out.println("Enter the Grade: ");
grade=in.nextDouble();
System.out.println("");
}
}
class Undergrad extends Student
{
boolean isPassed(double grade)
{
if(grade>70.0)
return true;
else
return false;
}
}
class Grad extends Student
{
boolean isPassed(double grade)
{
if(grade>80.0)
return true;
else
return false;
}
}
public class test {
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
Grad g=new Grad();
Undergrad u=new Undergrad();
g.enter();
if(g.isPassed(g.grade))
System.out.println("Student can Graduate");
else
System.out.println("Student cannot Graduate");
if(u.isPassed(g.grade))
System.out.println("Student can be Undergraduate");
else
System.out.println("Student cannot be Undergraduate");
}
}
8.Write a program to create abstract class Name Figure having data members of
Double type, X and Y. Also have abstract method call double area(). Also create
an interface called shape having a method name getdata and put data to take input
and display output. Create a Demo class that uses both abstract class and interface
and show the area of rectangle and square, Triangle.

package javaapplication1;
import java.util.Scanner;
abstract class Figure
{
public double type,X,Y;
abstract double area();
}
public interface shape
{
void getdata();
void putdata();
}

class Demo extends Figure implements shape


{
Scanner in=new Scanner(System.in);
public void getdata()
{
System.out.println("Select a shape from following: ");
System.out.println("1.Triangle");
System.out.println("2.Square");
System.out.println("3.Rectangle");
type=in.nextDouble();
if(type==1)
{
System.out.println("Enter Base and Height of Triangle:");
X=in.nextDouble();
Y=in.nextDouble();
}
else if(type==2)
{
System.out.println("Enter the side of square:");
X=in.nextDouble();
Y=X;
}
else
{
System.out.println("Enter length and breadth:");
X=in.nextDouble();
Y=in.nextDouble();
}
}
public void putdata()
{
System.out.println("");
System.out.println("The Sides are "+X+" "+Y);
}
public double area()
{
double ar;
if(type==1)
ar=0.5*X*Y;
else
ar=X*Y;
return ar;
}
}
class A
{
public static void main(String args[])
{
Demo d=new Demo();
double ar1;
d.getdata();
d.putdata();
ar1=d.area();
System.out.println("Area is "+ar1);
}
}
9.a) Write a program to implement arithmetic exception, array indexoutof bound
Exception, Number format Exception.
b) Write a program to show the difference between throw and throws and also
discuss checked and unchecked exception.
a)
public class Exceptions
{
public static void main(String[] args) {
try {
int[] a = new int[3];
// a[4] = 5;
// int x = 4 / 0;
int y = Integer.parseInt("abc");
} catch (IndexOutOfBoundsException e) {
System.out.println("Array out of bounds!");
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception!");
} catch (NumberFormatException e) {
System.out.println("Number format exception!");
}
}
}
b)
package javaapplication2;
import java.util.Scanner;
public class Bexception {
static void throw1()
{
try
{
throw new ArrayIndexOutOfBoundsException("THROWDEMO");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Inside throw catch");
System.out.println("Handling Unchecked Exception");
throw e;
}
}
static void throws1() throws NoSuchFieldException
{
System.out.println("Inside throws catch");
System.out.println("Handling Checked Exception");
throw new NoSuchFieldException("THROWSDEMO");
}
public static void main(String args[])
{
try
{
throw1();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Recaught "+e);
System.out.println("");
}
try
{
throws1();
}
catch(NoSuchFieldException e)
{
System.out.println("Caught "+e);
}
}
}
10.Write a program to create a user defined exception name VoterEligibility
exception. Create a Demo Class which show that: If a voter is less than 18 then
throw VoterEligibility exception else issue the voter card.

package javaapplication2;
import java.util.Scanner;
class VoterEligibility extends Exception
{
public String toString()
{
return "VoterEligibilityException: Age Less than 18";
}
}
public class Demo {
static void check(int b) throws VoterEligibility
{
if(b<18)
throw new VoterEligibility();
else
System.out.println("Voter card Issued.");
}
public static void main(String args[])
{
int age;
try
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the age of candidate");
age=in.nextInt();
check(age);
}
catch(VoterEligibility e)
{
System.out.println("Caught "+e);
System.out.println("Voter Card not issued.");
}
}
}
12.Create an applet program for mouse events it should recognize mouse entry,
exit, and its coordinates.

package appl;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class NewApplet extends Applet implements MouseListener,MouseMotionListener {
String msg; int x,y;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
public void mouseClicked(MouseEvent e) {
x=100; y=100; msg="Clicked";
}
public void mousePressed(MouseEvent e) {
x=e.getX(); y=e.getY(); msg="Pressed Down"; repaint();
}
public void mouseReleased(MouseEvent e) {
x=e.getX(); y=e.getY(); msg="Up"; repaint();
}
public void mouseEntered(MouseEvent e) {
x=100; y=100; msg="Entered"; repaint();
}
public void mouseExited(MouseEvent e) {
x=100; y=100; msg="Exiting out"; repaint();
}
public void mouseDragged(MouseEvent e) {
showStatus("Mouse Dragged "+e.getX()+"--"+e.getY());
}
public void mouseMoved(MouseEvent e) {
showStatus("Mouse Moved "+e.getX()+"--"+e.getY());
}
public void paint(Graphics g){
g.drawString(msg, x, y);
}
}
13.Create an applet program for key events it should recognize normal as well as
special keys & should be displayed on the panel.

package newpackage;
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener{
Label l;
TextArea area;
KeyListenerExample(){
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l); add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}

14. Draw a smiling face using graphics

package newpackage;
import java.awt.*;
import java.applet.*;
public class Smiley extends Applet{
public void paint(Graphics g){
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}
}
15. Simple Calculator using AWT

package newpackage;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class Cal extends Applet

implements ActionListener

String msg=" ";

int v1,v2,result;

TextField t1;

Button b[]=new Button[10];

Button add,sub,mul,div,clear,mod,EQ;

char OP;

public void init()

Color k=new Color(120,89,90);

setBackground(k);

t1=new TextField(10);

GridLayout gl=new GridLayout(4,5);

setLayout(gl);

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

b[i]=new Button(""+i);
}

add=new Button("add");

sub=new Button("sub");

mul=new Button("mul");

div=new Button("div");

mod=new Button("mod");

clear=new Button("clear");

EQ=new Button("EQ");

t1.addActionListener(this);

add(t1);

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

add(b[i]);

add(add);

add(sub);

add(mul);

add(div);

add(mod);

add(clear);

add(EQ);

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

b[i].addActionListener(this);

}
add.addActionListener(this);

sub.addActionListener(this);

mul.addActionListener(this);

div.addActionListener(this);

mod.addActionListener(this);

clear.addActionListener(this);

EQ.addActionListener(this);

public void actionPerformed(ActionEvent ae)

String str=ae.getActionCommand();

char ch=str.charAt(0);

if ( Character.isDigit(ch))

t1.setText(t1.getText()+str);

else

if(str.equals("add"))

v1=Integer.parseInt(t1.getText());

OP='+';

t1.setText("");

else if(str.equals("sub"))

v1=Integer.parseInt(t1.getText());

OP='-';
t1.setText("");

else if(str.equals("mul"))

v1=Integer.parseInt(t1.getText());

OP='*';

t1.setText("");

else if(str.equals("div"))

v1=Integer.parseInt(t1.getText());

OP='/';

t1.setText("");

else if(str.equals("mod"))

v1=Integer.parseInt(t1.getText());

OP='%';

t1.setText("");

if(str.equals("EQ"))

v2=Integer.parseInt(t1.getText());

if(OP=='+')

result=v1+v2;
else if(OP=='-')

result=v1-v2;

else if(OP=='*')

result=v1*v2;

else if(OP=='/')

result=v1/v2;

else if(OP=='%')

result=v1%v2;

t1.setText(""+result);

if(str.equals("clear"))

t1.setText("");

}
16. Program to demonstrate Packages and their Accessibilities and Visibilities
a)Parent.java

package f1;

public class parent {

int i=1;

final private int j=2;

protected int k=3;

public int l=4;

public void disp(){

System.out.println("Default "+i);

System.out.println("Private "+j);

System.out.println("Protected "+k);

System.out.println("Public "+l);

Child1.java

package f1;

public class child1 extends parent{

@Override

public void disp(){

System.out.println("Default "+i);

//System.out.println("Private "+j);

System.out.println("Protected "+k);

System.out.println("Public "+l);

} }
NonSC1.java

package f1;

public class nonsc1 {

public void disp(){

parent t=new parent();

System.out.println("Default "+t.i);

//System.out.println("Private "+j);

System.out.println("Protected "+t.k);

System.out.println("Public "+t.l);

Demo.java

package f1;

public class demo {

public static void main(String args[]){

parent p=new parent();

child1 c1=new child1();

nonsc1 non=new nonsc1();

p.disp();

c1.disp();

non.disp();

b)Child2.java
package f2;
import f1.parent;

public class child2 extends parent {

@Override

public void disp(){

//System.out.println("Default "+i);

//System.out.println("Private "+j);

System.out.println("Protected "+k);

System.out.println("Public "+l);

NonSC2.java

package f2;

import f1.parent;

public class nonsc2 {

public void disp(){

parent t=new parent();

//System.out.println("Default "+t.i);

//System.out.println("Private "+j);

//System.out.println("Protected "+t.k);

System.out.println("Public "+t.l);

Demo2.java

package f2;

public class demo2 {


public static void main(String args[]){

child2 c2=new child2();

nonsc2 non=new nonsc2();

c2.disp();

non.disp();

}
18.Design the following form using AWT

import java.awt.*;
public class form extends java.applet.Applet
{
@Override
public void init()
{
add(new Label("Application for Admission"));
add(new Label("1.Name"));
add(new TextField(10));
add(new Label("2.DOB"));
add(new TextField(2));
add(new TextField(2));
add(new TextField(4));
add(new Label("Gender"));
CheckboxGroup gender = new CheckboxGroup();
Checkbox m=new Checkbox("Male",gender,false);
Checkbox f=new Checkbox("Female",gender,false);
add(m);
add(f);
add(new Button("Register"));
}}
17) Design an Applet to show various figures. Draw color lines, Rectangle, Filled
Rectangle, Rounded Rectangle, Filled Rounded Rectangle, Oval, Filled oval, arc, fill arc,
& polygon every drawing shape should be in different color, Write a text “hello
everyone” at the center.

import java.applet.Applet;

import java.awt.*;

public class SmileyExc extends Applet {

public void paint(Graphics g) {

g.setColor(Color.yellow);

g.drawOval(20,20,40,40);

g.setColor(Color.black);

g.fillOval(120,30,15,25);

int x[] = {95,85,106,95};

int y[] = {85,104,104,85};

g.setColor(Color.red);

g.drawPolygon(x, y, 4);

int x1[] = {95+30,85+30,106+30,150};

int y1[] = {85+30,104+30,104+30,150};

g.setColor(Color.green);

g.fillPolygon(x1, y1, 4);

g.setColor(Color.blue);

g.drawArc(175,95,78,50,0,-180);

g.setColor(Color.gray);

g.fillArc(95+50,105+50,78,50,0,-180);

g.drawString("Hello Everyone", 175, 60);


g.setColor(Color.black);

g.drawRect(20,70,30,50);

g.setColor(Color.cyan);

g.fillRect(20,130,30,50);

g.setColor(Color.red);

g.drawRoundRect(220,70,30,50,5,10);

g.setColor(Color.blue);

g.fillRoundRect(70,130,30,50,5,5);

}
11. Odd Even Thread -
public class OddEvenPrintMain {

boolean odd;
int count = 1;
int MAX = 20;

public void printOdd() {


synchronized (this) {
while (count < MAX) {
System.out.println("Checking odd loop");

while (!odd) {
try {
System.out.println("Odd waiting : " + count);
wait();
System.out.println("Notified odd :" + count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Odd Thread :" + count);
count++;
odd = false;
notify();
}
}
}

public void printEven() {

try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (this) {
while (count < MAX) {
System.out.println("Checking even loop");

while (odd) {
try {
System.out.println("Even waiting: " + count);
wait();
System.out.println("Notified even:" + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even thread :" + count);
count++;
odd = true;
notify();

}
}
}

public static void main(String[] args) {

OddEvenPrintMain oep = new OddEvenPrintMain();


oep.odd = true;
Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
oep.printEven();

}
});
Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
oep.printOdd();

}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}

Вам также может понравиться