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

Java - PR Programs 21

The document contains code snippets from multiple Java programs demonstrating various programming concepts like checking if a number is even or odd using modulo operator, using ternary operator, switch case with character data type, for loop to print odd numbers, do-while loop, methods, constructors, inheritance, overriding methods, and exception handling. It provides examples of core Java programming constructs through small code examples to help explain different concepts.

Uploaded by

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

Java - PR Programs 21

The document contains code snippets from multiple Java programs demonstrating various programming concepts like checking if a number is even or odd using modulo operator, using ternary operator, switch case with character data type, for loop to print odd numbers, do-while loop, methods, constructors, inheritance, overriding methods, and exception handling. It provides examples of core Java programming constructs through small code examples to help explain different concepts.

Uploaded by

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

29EXP-3: Write a Program to check number is even or odd

public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = reader.nextInt();

if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}

1
EXP 4:
1:write a program to make use of ternary operator in java
public class TernaryOperatorExample
{
public static void main(String args[])
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}
Output
Value of y is: 90
Value of y is: 61

2.write a program to make switch case in charecter data type


public class Exp4 {
public static void main(String[] args)
{
int day = 5;
String dayString;
// switch statement with int data type
switch (day) {
case 1:
dayString = "Monday";
break;
case 2:
dayString = "Tuesday";
break;
case 3:
dayString = "Wednesday";
break;
case 4:
dayString = "Thursday";
break;
case 5:
dayString = "Friday";
break;
case 6:
dayString = "Saturday";
break;
case 7:
dayString = "Sunday";
break;
default:
dayString = "Invalid day";
}
System.out.println(dayString);
}
}

2
EXP-5

class Exp5c {

public static void main(String args[]){

for(int i=1; i<=20; i=i+2){

System.out.println("The odd number i is: "+i);

3
Exp 6:

Develop a program to logical operators in do-while loop

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

int sum = 0;
int number = 0;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

// do...while loop continues


// until entered number is positive
do {
// add only positive numbers
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
} while(number >= 0);
System.out.println("Sum = " + sum);

}
}

// write output of the following program page no 32


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

int a = 1;
do
{

System.out.println(a);
a=a+1;//or a++;
} while(a <=10);

}
}

4
// write output of the following program page no 32
class Test {
public static void main(String[] args) {

while(true)
{

System.out.println(1);
do{
System.out.println(2);
} while(false);
}

}
}

5
Page 33: Write a program to display the numbers from 1-50 using do while loop
class Exp6 {
public static void main(String args[]){
int i=1;
do{
System.out.print(" "+i);
i++;
}while(i<=50);
}
}

6
Exp-7

class Test_page44
{
public static void main(String args[])
{
double d=100.4;
long l=(long)d;
int i=(int)l;
System.out.println("Double value"+d);
System.out.println("Long value"+l);
System.out.println("Int value"+i);
}
}

class Test_page44_2
{
public static void main(String args[])
{
double b=50;
b=(byte)(b*2);
System.out.println(b);
}
}

7
Write a program for explicit example
class Exp7
{
public static void main(String[] args)
{
int i = 100;

// automatic type conversion


long l = i;

// automatic type conversion


float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}}

8
Exp-8

class Exp8
{
int id;
String name;
int age;
//creating two arg constructor
Exp8(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Exp8(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);
}

public static void main(String args[])


{
Exp8 s1 = new Exp8(111,"Karan");
Exp8 s2 = new Exp8(222,"Aryan",25);
s1.display();
s2.display();
}
}

9
Exp-9
Write a program to implement multidimensional array
class Exp9 {
public static void main(String[] args)
{

int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
System.out.print(arr[i][j] + " ");
}

System.out.println();
} } }

page no 63
// Java Program to Print Array Elements using For Loop
import java.util.Scanner;

public class Exp9a {


private static Scanner sc;
public static void main(String[] args) {
int i, Number;
sc = new Scanner(System.in);

System.out.print(" Please Enter Number of elements in an array : ");


Number = sc.nextInt();
int [] Array = new int[Number];

System.out.print(" Please Enter " + Number + " elements of an Array : ");


for (i = 0; i < Number; i++)
{
Array[i] = sc.nextInt();
}
System.out.println("\n **** Elements in this Array are **** ");
for (i = 0; i < Number; i++)
{
System.out.print(Array[i] + "\t");
} } }

10
EXP-10
import java.util.*;
public class EXP10b {
public static void main(String args[]) {
//Create an empty vector with initial capacity 4
Vector vec = new Vector(4);
//Adding elements to a vector
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Check size and capacity
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
}
}

11
EXP-11
public class EXP11{
public static void main(String args[]){
//Creating Wrapper class object
Integer obj = new Integer(100);

//Converting the wrapper object to primitive


int num = obj.intValue();

System.out.println(num+ " "+ obj);


}
}

//Java Program to Convert Wrapper Objects to Primitive Types

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

// creates objects of wrapper class


Integer obj1 = Integer.valueOf(23);
Double obj2 = Double.valueOf(5.55);
Boolean obj3 = Boolean.valueOf(true);

// converts into primitive types


int var1 = obj1.intValue();
double var2 = obj2.doubleValue();
boolean var3 = obj3.booleanValue();

// print the primitive values


System.out.println("The value of int variable: " + var1);
System.out.println("The value of double variable: " + var2);
System.out.println("The value of boolean variable: " + var3);
}
}

12
EXP-12
/* Demonstrate the use of overridding method display using super and sub classes*/
import java.lang.*;
class book {
String author=" "; String title=" ";
String publisher=" ";
book(String a, String b,String c)
{
author =a;
title=b;
publisher=c;
}
void display()
{
System.out.println("Book author is : "+author);
System.out.println("Book title is : "+title);
System.out.println("Book Publisher is : "+publisher);
}
}
class bookinfo extends book {
int price,stock;
bookinfo(String a, String b,String c,int z, int q)
{
super(a,b,c);
price=z;
stock=q;
}
void display() {
super.display();
System.out.println("Book price is : "+price);
System.out.println("Book Stock Position is : "+stock);
}
public static void main(String args[]) {
bookinfo b1=new bookinfo("Tech-max","JAVA","AJ",123,25);
b1.display();
System.out.println("\n");
bookinfo b2=new bookinfo("Bal Guru","OOPS","Tata",350,50);
b2.display();
System.out.println("\n");
bookinfo b3=new bookinfo("Nirali","HARDWARE","AJ",50,2);
b3.display();}
}

13
EXP-13
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();
}
}

14
develop a program to calculate the room area and volume using single inheritance
class Room
{
int length,width;
Room(int a,int b)
{
length = a;
width = b;
}
void area()
{
int area = length*width;
System.out.println("The area of the room is " +area);
}
}

class roomvol extends Room


{
int height;
roomvol(int a,int b,int c)
{
super(a,b);
height = c;
}
void volume()
{
int volume = length*width*height;
System.out.println("The volume of the room is " +volume);
}
class Exp13
{
public static void main(String args[])
{
roomvol room2 = new roomvol(10,40,20);
room2.area();
room2.volume();
}
}

15
EXP-14
interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}
public void travel() {
System.out.println("Animal is travelling");
}
}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}
}

16
write a program to find area rectangle of circle using interface
interface area
{
double pi = 3.14;
double calc(double x,double y); }
class rect implements area
{
public double calc(double x,double y)
{
return(x*y);
} }
class cir implements area
{
public double calc(double x,double y)
{
return(pi*x*x);
} }
class Exp14b
{
public static void main(String arg[])
{
rect r = new rect();
cir c = new cir();
area a;
a = r;
System.out.println("\nArea of Rectangle is : " +a.calc(10,20));

a = c;
System.out.println("\nArea of Circle is : " +a.calc(15,15));
}
}

17
EXP-15
/*Define a package named myInstitute include class named as department with one method
to display the staff of that department.Develop a program to import this package in java application and
call the method defined in the package.*/

package myInstitute;
import java.util.*;
public class department
{
String name;
public void display()
{
System.out.println("Enter the staff name");
Scanner sc = new Scanner(System.in);

// String input
String name = sc.nextLine();
System.out.println("The name of staff is :"+name);
}
}
import myInstitute.*;
public class Exp15a
{
public static void main(String args[])
{
department d1=new department();
d1.display();
}
}

18
EXP-15
/* Develop a program which consists of the package named let_me_calculate with a
class named calculator and a method named add two integer numbers.Import let_me_calcuate package
in another program to add two numbers.*/

package let_me_calculate;
import java.util.*;

public class calculator


{
public int x,y,sum;
public void put()
{

System.out.println("Enter the first number");


Scanner sc = new Scanner(System.in);

// Integer input
x = sc.nextInt();
System.out.println("The first numer is : "+x);
System.out.println("Enter the Second number");
y = sc.nextInt();
System.out.println("The second numer is : "+y);
sum=x+y;
System.out.println("The sum of number is :"+sum);
}
}
import let_me_calculate.*;
class Exp15b
{
public static void main(String args[])
{
calculator c1=new calculator();
c1.put();
}
}

19
EXP 16: Implement multithreading program to perform simultaneous process
class even extends Thread
{
int i;
public void run()
{
for( i=1;i<=10;i++)
{
if(i%2==0)
{
System.out.println("Even Thread i=" +i);
}
try
{
Thread.sleep(100);
}
catch(Exception e){}
}
}
}
class odd extends Thread
{
public void run()
{
int j;
for( j=1;j<=10;j++)
{
if(j%2!=0)
{
System.out.println("Odd Thread j="+j);
}
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
class Exp16_EvenOdd
{
public static void main( String args[])
{
even e1 = new even();
e1.start();
odd o1=new odd();
o1.start();
}
}

20
21
EXP 17: Develop a program to accept password from user and throw "Authentication Failure Exception"
if the password is incorrect.

import java.io.*;
class PasswordException extends Exception
{
PasswordException(String msg)
{
super(msg);
}
}
class Exp17
{
public static void main(String args[])
{
BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(bin.readLine().equals("abc123"))
{
System.out.println("Authenticated ");
}
else
{
throw new PasswordException("Authentication Fsailure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}

OUTPUT

22
EXP 18:
Write a simple program for throwing own Exception

class AgeException extends Exception


{
public AgeException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

public class Exp18b


{
void ageCheck(int age) throws AgeException{
if(age<18)
{
throw new AgeException("NotEligiblr for Voting");
}
}

public static void main(String args[])


{
Exp18b obj = new Exp18b();
try
{
obj.ageCheck(12);
}
catch (AgeException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
}
}

23
EXP 19: Develop a program to implement methods in th program

import java.awt.*;
import java.applet.*;
public class Exp19c extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<=4;i++)
{
if(i%2 == 0)
{
g.drawOval(90,i*50+10,50,50);

}
else
{
g.fillOval(90,i*50+10,50,50);
}
}
}
}
/* <applet code=Exp19c width=300 height=300>
</applet> */

24
EXP 20: Develop applet program to draw human face

import java.awt.*;
import java.applet.*;
public class Exp20 extends Applet
{
public void paint (Graphics g)
{
g.drawOval(40, 40, 120, 150); // Head
g.drawOval(57, 75, 30, 20); // Left Eye
g.drawOval(110, 75, 30, 20); // Right Eye
g.fillOval(68, 81, 10, 10); // Pupil (left)
g.fillOval(121, 81, 10, 10); // Pupil (right)
g.drawOval(85, 100, 30, 30); // Nose
g.fillArc(60, 125, 80, 40, 180, 180); // Mouth
g.drawOval(25, 92, 15, 30); // Left Ear
g.drawOval(160, 92, 15, 30); // Right Ear
}
}
/* <applet code=Exp20 width=300 height=300>
</applet> */

OUTPUT

25
EXP 20.A: Develop applet program to draw polygon
import java.awt.*;
import java.applet.*;
// Draw and fill polygons
import java.awt.Graphics;

public class Exp20b extends java.applet.Applet


{
int xCoords[] = { 50, 200, 300, 150, 50, 50 };
int yCoords[] = { 100, 0, 50, 300, 200, 100 };
int xFillCoords[] = { 450, 600, 700, 550, 450, 450 };
public void paint(Graphics g)
{
g.drawPolygon(xCoords, yCoords, 6);
g.fillPolygon(xFillCoords, yCoords, 6);
}
}
/* <applet code=Exp20b width=300 height=300>
</applet>
*/

OUTPUT

26
EXP 21: Enlist the methods required to draw cone/cylinder.
import java.io.*;
import java.awt.*;
import java.applet.*;
//<Applet code="Exp21" WIDTH="800" HEIGHT="400"></Applet>
public class Exp21 extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.yellow);
g.setColor(Color.black);
/* To draw an cone*/
g.drawOval(200,80,200,50);
g.drawLine(200,100,300,500);
g.drawLine(400,100,300,500);
/* To draw a cyclinder*/
g.drawOval(500,60,200,50);
g.drawLine(500,80,500,300);
g.drawLine(700,80,700,300);
g.drawOval(500,280,200,50);
}
}

OUTPUT

27
EXP 22://Develop a program to display the content of file supplied as a command line argument

import java.io.*;
class Exp22c
{
public static void main(String[] args)
{
FileInputStream in = null;
try
{
in = new FileInputStream(args[0]);
int c;
while((c=in.read())!=-1)
System.out.print((char)c);
in.close();
}
catch(Exception e)
{}
}
}

OUTPUT

28
EXP 22.A: Develop a program to write a byte to a File
import java.io.*;
public class Exp22b {
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

29

You might also like