Java File
Java File
class demo{
System.out.println("Hello World"); }
}
P- 2 WAP to calculate room area using multiple classes.
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
double area=l*b;
System.out.println("Area of Rectangle is: " + area);
}
}
P-3 WAP to demonstrate the use of command line arguments.
class demo{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
P-4. WAP to explain the basic data types used in java.
class demo {
public static void main(String args[])
{
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;
Implicit Typecasting :
class demo {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt;
System.out.println(myInt);
System.out.println(myDouble);
}
}
Explicit Typecasting:
class demo {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble;
System.out.println(myDouble);
System.out.println(myInt);
}
}
P-6 WAP to demonstrate java expressions using different operators
in java like relational, logical, bitwise operators etc.
Unary Operator:
class demo{
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
Arithmetic Operator:
class demo{
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}}
Java Left Shift Operator:
class demo{
System.out.println(10<<2);
System.out.println(10<<3);
System.out.println(20<<2);
System.out.println(15<<4);
}}
class demo{
System.out.println(10>>2);
System.out.println(20>>2);
System.out.println(20>>3);
}}
class demo{
int b=5;
int c=20;
System.out.println(a<b&&a<c);
System.out.println(a<b&a<c);
}}
class demo{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);
System.out.println(a>b|a<c);
System.out.println(a>b||a++<c);
System.out.println(a);
System.out.println(a>b|a++<c);
System.out.println(a);
}}
Ternary Operator:
class demo{
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Assignment Operator:
class demo{
int a=10;
int b=20;
a+=4;
b-=4;
System.out.println(a);
System.out.println(b);
}}
P-7. WAP to demonstrate if-else, nested if-else, if-else ladder.
publicclass Condition {
publicstaticvoidmain(String[] args)
{
ifElse(10);
nestedIfElse(12);
ifElseLadder(1000);
// If Else
publicstaticvoidifElse(int a)
{
if (a<5)
{
System.out.println("Value is below 5 i.e." + a);
}
else
{
System.out.println("Value is greater than 5 i.e." +a );
}
}
// nested if-else
publicstaticvoidnestedIfElse(int a)
{
if (a<10) {
if(a<5)
{
System.out.println("Value is less than 5 i.e. "+a);
}
else
{
System.out.println("Value is greater than 5 i.e."+a);
}
}
else
System.out.println("Value is greater than 10 i.e." +a);
}
}
P-8. WAP to demonstrate switch statements.
publicclass Switch {
publicstaticvoidmain(String[] Args )
{
switchUse("Robin") ;
}
publicstaticvoidswitchUse(String name)
{
switch(name)
{
case "Robin":
{
System.out.println("Robin is being printed.");
break;
}
case "Tom":
{
System.out.println("Tom is being printed.");
break;
}
case "Zoobie":
{
System.out.println("Zoobie is being printed.");
break;
}
case "Alex":
{
System.out.println("Alex is being printed.");
break;
}
default:
System.out.println("Name is not in the switch statement.");
}
P-9. WAP to demonstrate “? :” operator.
publicclassTernaryOperator {
publicstaticvoidmain(String [] Args)
{
ternaryOperator("Tom");
}
publicstaticvoidternaryOperator(String name)
{
name = (name.equals("Robin"))? "Yes, the name is Robin": "Name is not Robin" ;
System.out.println(name);
}
P-10. WAP to explain the working of while, for and do while loops.
publicclass Loops {
publicstaticvoidmain(String[] args)
{
forLoop();
whileLoop();
do_WhileLoop();
}
publicstaticvoidforLoop()
{
{
System.out.println("Using For Loop");
for(int x=1;x<=5;x++)
{
System.out.println("value of x is = "+x );
}
System.out.println("__________________");
}
}
publicstaticvoidwhileLoop()
{
{
System.out.println("Using While Loop");
int y = 6;
while(y<=10)
{
System.out.println("value of y is = "+y);
y++;
}
System.out.println("__________________");
}
publicstaticvoiddo_WhileLoop()
{
{
System.out.println("Using Do_While Loop");
int z = 11;
do
{
System.out.println("value of z is = "+z);
z++;
}
while(z<=15);
}
}
}
P-11. WAP to demonstrate different types of constructors in java like default and
parameterize.
publicclassConstructorCaller {
publicstaticvoidmain(String[] args) {
Constructor c1 = newConstructor();
Constructor c2 = newConstructor("Rahul" , 12);
Constructor c3 = new Constructor("Rohit");
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
publicclass Constructor {
String name;
int age;
publicConstructor()
{
System.out.println("This is the user defined no arg constructor.");
}
publicConstructor(String name , int age)
{
this.name = name;
this.age = age;
System.out.println("This is the constructor which initializes the value for the instance variabel name
and age");
}
publicConstructor(String name)
{
this(name, 23);
System.out.println("This is the constructor which is calling the other constructor");
}
publicintgetAge()
{
return age;
}
@Override
public String toString()
{
returngetName()+ " " + getAge();
}
}
P-12. WAP to explain method overloading and constructor overloading.
package college;
class Box
{
double width, height, depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = height = depth = 0;
}
// constructor used when cube is created
Box(doublelen)
{
width = height = depth = len;
}
// compute and return volume
doublevolume( )
{
return width * height * depth;
}
}
publicclass test
{
publicstaticvoidmain(String args[])
{
// create boxes using the various constructors
Box mybox1 = newBox(10, 20, 15);
Box mybox2 = newBox();
Box mycube = newBox(7);
double vol;
OUTPUT
P-13. WAP to explain static methods and static members.
package college;
//Java program to demonstrate execution of static methods and static members
class test {
// static variable
staticinta = m1();
// static block
static
{
System.out.println("Inside static block");
}
// static method
staticint m1()
{
System.out.println("from m1");
return 20;
}
OUTPUT
P-14. WAP to demonstrate multilevel inheritance and super keyword.
package college;
class One
{
voidmessage()
{
System.out.println("This is One");
}
}
class test2
{
publicstaticvoidmain(String args[])
{
Three s = newThree();
package college;
class A
{
publicvoidmethod()
{
System.out.println("method of Class A");
}
}
class B extends A
{
publicvoidmethod()
{
System.out.println("method of Class B");
super.method();
}
}
class C extends A
{
publicvoidmethod()
{
System.out.println("method of Class C");
super.method();
}
}
class D extends A
{
publicvoidmethod()
{
System.out.println("method of Class D");
}
}
publicclass test15 {
publicstaticvoidmain(String args[])
{
B obj1 = newB( );
C obj2 = newC( );
D obj3 = newD( );
obj1.method( );
obj2.method( );
obj3.method( );
}
}
OUTPUT
P-16. WAP to explain the working of final classes and also use final methods and final
variables in your program.
package college;
finalpublicclass test16
{
finalvoidgetMethod()
{
System.out.println("method has been called");
}
publicstaticvoidmain(String[] args)
finalint hours=24;
}
}
OUTPUT
P-17. WAP to explain the concept of finalization.
package college;
class Bye {
publicstaticvoidmain(String[] args)
{
Bye m = newBye();
Note : As finalize is a method and not a reserved keyword, so we can call finalize method Explicitly, then it will be
executed just like normal method call but object won’t be deleted/destroyed.
OUTPUT
P-18. WAP to demonstrate the use of abstract methods and abstract classes.
package college;
abstractclass Base {
Base(){System.out.println("Base Constructor Called");}
abstractvoidfun();
}
class Derived extends Base {
Derived(){System.out.println("Derived Constructor Called");}
voidfun() { System.out.println("Derived fun() called"); }
}
class Main {
publicstaticvoidmain(String args[]) {
package college;
publicclass Access
{ //Class is having Public access modifier
publicvoiddisplay()
{
System.out.println("Public:Accessible from Everywhere");
}
publicstaticvoidmain(String[] args) {
D_Access d = newD_Access();
Pri_Accessp = newPri_Access();
Pro_Accesspr = newPro_Access();
Access pb = newAccess();
d.display();
//p.display(); This cannot be called as display is Private
pr.display();
pb.display();
}
}
OUTPUT
P-20. WA menu driven program to add, subtract and multiply two matrices.
package college;
importjava.util.Scanner;
publicclass matrix {
publicstaticvoidmain(String...args)
{
Scanner scanner = newScanner(System.in);
System.out.print("Enter number of rows in matrix : ");
int rows = scanner.nextInt();
System.out.print("Enter number of columns in matrix : ");
int columns = scanner.nextInt();
int[][] matrix1 = newint[rows][columns];
int[][] matrix2 = newint[rows][columns];
if(a==1) {
//Addition of matrices.
int[][] resultMatix = newint[rows][columns];
for (inti = 0; i< rows; i++)
{
for (int j = 0; j < columns; j++)
{
resultMatix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
if(a==2) {
//Subtraction of matrices.
int[][] resultMatix2 = newint[rows][columns];
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatix2[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
System.out.println("\nThe subtraction of the two matrices is : ");
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatix2[i][j] + " ");
}
System.out.println();
}
}
if(a==3) {
//Multiply matrices
int[][] productMatrix = newint[rows][columns];
for (inti = 0; i< rows; i++) {
for (int j = 0; j < columns; j++) {
for (int k = 0; k < columns; k++) {
productMatrix[i][j] = productMatrix[i][j] + matrix1[i][k] * matrix2[k][j];
}
}
}
P-23..WAP to demonstrate the commonly used “String” and “String Buffer” class
methods.
package college;
import java.io.*;
class Str {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("the end is near");
int p = s.length(); //Gives the Length of String
int q = s.capacity(); //Gives the Capacity Of String
System.out.println("Length of string the end is near=" + p);
System.out.println("Capacity of string the end is near=" + q);
s.append(": 2019"); //Adds : 2019 to the existing string
System.out.println(s);
s.insert(0,4 ); //Inserts 4 at position 0
System.out.println(s);
s.delete(0, 4); //Delete 4char from position 0
System.out.println(s);
s.deleteCharAt(6); //Performs char deletion at 6
System.out.println(s);
s.replace(5, 7, "ar "); //replaces the char from 5 to 7 by ar
System.out.println(s);
s.reverse(); //Reverses the String
System.out.println(s);
}
}
OUTPUT
P-24.WAP to demonstrate Wrapper class methods.
package college;
OUTPUT
P-25.WAP to explain interfaces in java.
package college;
importjava.io.*;
OUTPUT-
P 27- WAP to demonstrate package in java
//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-
P-28: WAP to explain static import in java with package.
class demo{
out.println("Java");
}
P 29- WAP to demonstrate threading in java using thread class
class Multi extendsThread{
publicvoidrun(){
System.out.println("thread is running...");
}
publicstaticvoidmain(String args[]){
Multi t1=newMulti();
t1.start();
}
}
OUTPUT-
P-30: WAP to demonstrate threading in java using Runnable interface.
class RunnableDemo {
+ Thread.currentThread().getName());
t1.start();
System.out.println(Thread.currentThread().getName()
}
P31-WAP to explain try and catch statements in java
publicclass TryCatchExample2 {
publicstaticvoidmain(String[] args) {
try
{
intdata=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
OUTPUT-
P 32- WAP to demonstrate exception handling using multiple catch statements and finally
block
publicclass MultipleCatchBlock1 {
publicstaticvoidmain(String[] args) {
try{
inta[]=newint[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
finally {
System.out.println("rest of the code");
}
}
}
OUTPUT-
P 33- WAP to demonstrate the use of throw and throws keyword in java
classThrowExcep
{
staticvoidfun()
{
try
{
thrownewNullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside fun().");
throw e; // rethrowing the exception
}
}
publicstaticvoidmain(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
System.out.println("Caught in main.");
}
}
}
OUTPUT-
classtst
{
publicstaticvoidmain(String[] args)throwsInterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
OUTPUT-
P 34- WAP to demonstrate Applet with all the states used in it.
package java_program;
import java.awt.*;
import java.applet.Applet;
import javax.swing.JOptionPane;
public AppletLifecycle() {
add(messages);
messages.append("Constructor executed\n");
}
public void init() {
messages.append("init method executed\n");
}
public void start() {
messages.append("start method executed\n");
}
public void paint(Graphics g) {
messages.append("Paint called\n");
}
}
P-35: WAP to make graphic calculator.
package java_program;
import java.awt.*;
import java.awt.event.*;
String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0",
"+/-", "." };
String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+", "=" };
String memoryButtonText[] = {"MC", "MR", "MS", "M+" };
String specialButtonText[] = {"Backspc", "C", "CE" };
MyCalculator(String frameText)//constructor
{
super(frameText);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{System.exit(0);}
});
setLayout(null);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
}
if(tempText.equals("."))
{
if(cl.setClear)
{cl.displayLabel.setText("0.");cl.setClear=false;}
else if(!isInString(cl.displayLabel.getText(),'.'))
cl.displayLabel.setText(cl.displayLabel.getText()+".");
return;
}
int index=0;
try{
index=Integer.parseInt(tempText);
}catch(NumberFormatException e){return;}
if(cl.setClear)
{cl.displayLabel.setText(""+index);cl.setClear=false;}
else
cl.displayLabel.setText(cl.displayLabel.getText()+index);
}//actionPerformed
}//class defination
cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());
if(opText.equals("1/x"))
{
try
{double tempd=1/(double)temp;
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(opText.equals("sqrt"))
{
try
{double tempd=Math.sqrt(temp);
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(!opText.equals("="))
{
cl.number=temp;
cl.op=opText.charAt(0);
return;
}
// process = button pressed
switch(cl.op)
{
case '+':
temp+=cl.number;break;
case '-':
temp=cl.number-temp;break;
case '*':
temp*=cl.number;break;
case '%':
try{temp=cl.number%temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
case '/':
try{temp=cl.number/temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
}//switch
cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
//cl.number=temp;
}//actionPerformed
}//class
switch(memop)
{
case 'C':
cl.memLabel.setText(" ");cl.memValue=0.0;break;
case 'R':
cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));break
;
case 'S':
cl.memValue=0.0;
case '+':
cl.memValue+=Double.parseDouble(cl.displayLabel.getText());
if(cl.displayLabel.getText().equals("0") ||
cl.displayLabel.getText().equals("0.0") )
cl.memLabel.setText(" ");
else
cl.memLabel.setText("M");
break;
}//switch
}//actionPerformed
}//class
import java.io.*;
class CopyDataFiletoFile
{
public static void main(String args[])throws IOException
{
FileInputStream Fread =new FileInputStream("Hello.txt");
FileOutputStream Fwrite=new FileOutputStream("Hello1.txt") ;
System.out.println("File is Copied");
int c;
while((c=Fread.read())!=-1)
Fwrite.write((char)c);
Fread.close();
Fwrite.close();
}
}
OUTPUT:-
try
{
Dread = new FileInputStream("Anuj.txt");
Dwrite = new FileOutputStream ("Anuj1.txt");
OUTPUT::-
P 37- Write a Java application to print Pascal’s triangle
classPascalTriangle
{
publicstaticvoidmain(String args[])
{
inti,r=5,number,k,j;
// r is number of rows
for(i=0; i<r; i++)
{
for(k=r; k>i; k--)
{
System.out.print(" ");
}
number = 1;
for(j=0; j<=i; j++)
{
System.out.print(number+ " ");
number = number * (i-j) / (j+1);
}
System.out.println();
}
}
}
OUTPUT-
P 38- Write a Java program to compute the following series-
1 – x + x^2/2! – x^3/3! + x^4/4!....+(-/+1)nx^n/n! where x and n is accepted by user
importjava.util.Scanner;
classFactorialSeries
{
publicstaticintfact(int index)
{
int f=1,i;
for(i=1; i<=index; i++)
{
// to find factorial
f = f*i;
}
return f;
}
publicstaticvoidmain(String[] args)
{
intn,x,i,num=-1;
doublefrac,sum = 0;
Scanner sc = newScanner(System.in);
System.out.println("Enter n: ");
n =sc.nextInt();
System.out.println("Enter x: ");
x = sc.nextInt();
for(i=1; i<=n; i++)
{
frac = Math.pow(num,i)*((i*Math.pow(x,i))/fact(i));
sum = sum + frac;
}
System.out.println("Answer = " +sum);
}
}
OUTPUT-
P-39. Define a class BankAccount with appropriate member variables and methods
to deposit and withdraw amount. Refine BankAccount to SavingBankAccount and
CurrentBankAccount using inheritance. Use them in main class to demonstrate
dynamic method dispatch.
package college;
import java.util.Scanner;
class BankAccount
{
String Name;
int Amount;
int Balance=1000;
Scanner sc = new Scanner(System.in);
void showinfo()
{
System.out.println("Enter Name");
Name = sc.next();
System.out.println("Name = " +Name);
System.out.println("Balance = "+Balance);
}
void deposit()
{
System.out.println("Enter Amount to be Deposited");
Amount = sc.nextInt();
Balance = Balance + Amount ;
System.out.println("Updated Balance = "+Balance);
}
void withdraw()
{
System.out.println("Enter Amount to be Withdraw");
Amount = sc.nextInt();
if(Amount<Balance){
Balance = Balance - Amount ;}
else { System.out.println("Amount = Aukat se Bahar");}
System.out.println("Balance After withdrawing = "+Balance);
}
}
class SavingBankAccount extends BankAccount
{
void svaccount()
{
System.out.println("\nThis is savings Account ");
super.showinfo();
super.deposit();
super.withdraw();
}
}
OUTPUT:
P 40- Create an abstract class Shape and derived classes Rectangle and Circle from Shape class.
Implement abstract method of shape class in Rectangle and Circle class. Shape class contains:
origin (x,y) as data member, display() and area() as abstract methods. Circle class contains: radius
as data member. Rectangle class contains: length and width. (Use Inheritance, overloading and
overriding concept)
import java.util.Scanner;
abstract class Shape
{
public double x;
public float y;
abstract void display();
abstract void area();
}
class Circle extends Shape
{
private float radius;
x=(3.14*radius*radius);
}
class TestShapeLen
{
public static void main(String an[])
{
Shape ob;
System.out.println(" \n 1 Circle \n 2 Rectangle");
System.out.println("\n Enter your Choice \n");
Scanner sc = new Scanner(System.in);
int ch=sc.nextInt();
if(ch==1)
{
ob= new Circle();
ob.area();
ob.display();
}
else if(ch==2)
{
ob = new Rectangle();
ob.area();
ob.display();
}
}
}
OUTPUT:-
41. Create a package named as MyPackage with a class named as Calculate. The class
should contain three methods with the following specifications:
Volume(): Accepts three double type arguments i.e. width, height, depth; calculate
volume and return double type value.
Add(): Accepts two integer type values, adds them and returns the value.
Divide(): Accepts two integer type values, divides them and returns results.
Import this package into a file named as PackageDemo and call the above three
methods.
package MyPackage;
public class Calculate
{
public double Volume()
{
double width = 5.2;
double height = 4.2;
double depth = 3.0;
double v = width * height * depth ;
System.out.println("Volume is "+v);
return v;
}
public void Add()
{
int x = 2;
int y = 5;
int sum = x+y;
System.out.println("Add: sum is "+sum);
}
public void Divide()
{
int p = 10;
int q = 2;
int Div = p/q;
System.out.println("Division of p and q is "+Div);}
}
import MyPackage.Calculate;
public class packagedemo
{
public static void main(String[] args)
{
Calculate c = new Calculate();
c.Volume();
c.Add();
c.Divide();
}
}
OUTPUT
42. Write a program that will count number of characters, words and lines in a file.
The name should be passes as command line argument.
package college;
import java.io.*;
import java.util.Scanner;
String line;
// Initializing counters
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
int paragraphCount = 1;
int whitespaceCount = 0;
characterCount += line.length();
countWord += wordList.length;
whitespaceCount += countWord -1;
sentenceCount += sentenceList.length;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
package college;
import java.io.*;
import java.io.PipedWriter;
import java.io.PipedReader;