Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
OOP THROUGH JAVA LAB 1A) Write a program to print prime numbers up to a given number. import java.util.Scanner; class Test { void check(int num) { System.out.println ("Prime numbers up to "+num+" are:"); for (int i=1;i<=num;i++) for (int j=2;j<i;j++) { if(i%j==0) break; else if((i%j!=0)&&(j==i-1)) System.out.print(“ “+i); } } } //end of class Test class Prime { public static void main(String args[ ]) { Test obj1=new Test(); Scanner input=new Scanner(System.in); System.out.println("Enter the value of n:"); int n=input.nextInt(); obj1.check(n); } } 1 B) Write a program to print roots of a quadratic equation ax2+bx+c=0. import java.io.*; import java.util.*; class quad{ public static void main(String args[]){ Scanner s=new Scanner(System.in); System.out.println("enter the values for a,b & c"); int a=s.nextInt(); int b=s.nextInt(); int c=s.nextInt(); double d,e; d=((b*b)-(4*a*c)); if(d==0){ System.out.println("expression has real&equal roots"); e=(-b)/(2*a); System.out.print("roots are:"+e+"\t"+e); } if(d>0){ System.out.println("expression has real&unreal roots"); e=(-b+Math.sqrt(d))/(2*a); System.out.print("roots are:"+e+"\t"); e=(-b-Math.sqrt(d))/(2*a); System.out.println(e); } if(d<0){ System.out.println("expression has imaginary rotts"); } } } 2 C) Write a program to print Fibonacci sequence up to a given number. import java.util.Scanner; class Fib { public static void main(String args[ ]) { Scanner input=new Scanner(System.in); int i,a=0,b=1,c=0,t; System.out.println("Enter value of t:"); t=input.nextInt(); System.out.print(a); System.out.print(" "+b); for(i=0;i<t-2;i++) { c=a+b; a=b; b=c; System.out.print(" "+c); } System.out.println(); System.out.print(t+"th value of the series is: "+c); } } 3 D) Write a program to print the following format. * * * * * * * * * * class star{ public static void main(String args[]){ for(int i=0;i<5;i++) { for(int k=30-i;k>0;k--) System.out.print(" "); for(int j=0;j<=i;j++){ System.out.print("* "); } System.out.println(" "); } } } 4 2A) Define a class to represent a bank account and include the following members Instance Variables: i) Name of depositor ii) Account no iii) Type of account iv) Balance amount in the account Instance Methods: i) To assign instance variables (Constructors-Zero argument and parameterized) ii) To deposit an amount iii) To withdraw amount after checking the balance iv) To display name and address Define ExecuteAccount class in which define main method to test above class. class BankAccount{ String name,type; int AcctNo; double balance; double wbalance; public BankAccount(){ name="abc"; type="saving"; AcctNo=1234567890; balance=00.00; } void deposit(){ balance=12000.00; } void withdraw(){ if(balance>0){ wbalance=balance; //balance=wbalance; //System.out.println("Withdraw Money: "+wbalance); } } void display(){ 5 System.out.println("Account Holder Name: "+name); System.out.println("Account Number: "+AcctNo); System.out.println("Withdraw Money: "+wbalance); System.out.println("Account Balance: "+balance); } } class ExecuteAccountA{ public static void main(String args[]){ BankAccount ba=new BankAccount(); ba.deposit(); ba.withdraw(); ba.display(); } } B) In the above account class, maintain the total number of account holders present in the bank and also define a method to display it. Change the main method appropriately. import java.util.Scanner; class BankAccount{ String name,type; int count,AcctNo1,AcctNo2,AcctNo3,AcctNo4,AcctNo5,AcctNo6; double balance; double wbalance; Scanner in=new Scanner(System.in); public BankAccount(){ System.out.println("Enter Account Numbers:"); count=0; AcctNo1=in.nextInt(); count++; AcctNo2=in.nextInt(); count++; 6 AcctNo3=in.nextInt(); count++; AcctNo4=in.nextInt(); count++; AcctNo5=in.nextInt(); count++; AcctNo6=in.nextInt(); count++; } void deposit(){ } void withdraw(){ } void display(){ System.out.println("Number of Accounts: "+count); } } class ExecuteAccountB{ public static void main(String args[]){ BankAccount ba=new BankAccount(); ba.display(); } } C) In main method of ExecuteAccount class, define an array to handle five accounts. import java.util.Scanner; class BankAccount{ String name,type; long AcctNo[]=new long[5]; double balance; double wbalance; Scanner in=new Scanner(System.in); 7 public BankAccount(){ System.out.println("Enter Account Numbers:"); for(int i=0;i<5;i++){ AcctNo[i]=in.nextLong(); } } void deposit(){ } void withdraw(){ } void display(){ System.out.println("Account Numbers:"); for(int i=0;i<AcctNo.length;i++){ System.out.println(AcctNo[i]); } } } class ExecuteAccountC{ public static void main(String args[]){ BankAccount ba=new BankAccount(); ba.display(); } } D) In Account class constructor, demonstrate the use of “this” keyword. class BankAccount{ String name,type; int AcctNo; double balance; 8 public BankAccount(String name,String type,int AcctNo,double balance){ this.name=name; this.type=type; this.AcctNo=AcctNo; this.balance=balance; } void deposit(){ } void withdraw(){ } void display(){ System.out.println("Account Holder Name: "+name); System.out.println("Account Number: "+AcctNo); System.out.println("Account Type: "+type); System.out.println("Account Balance: "+balance); } } class ExecuteAccountD{ public static void main(String args[]){ BankAccount ba=new BankAccount("abc","current",1234,15000.00); ba.display(); } } E) Modify the constructor to read data from keyboard. import java.util.Scanner; class BankAccount{ String name,type; long AcctNo; 9 double balance; double wbalance; Scanner input=new Scanner(System.in); public BankAccount(){ System.out.println("Enter AcctHolder Name,Type,AcctNo and Balance"); name=input.next(); type=input.next(); AcctNo=input.nextLong(); balance=input.nextDouble(); } void deposit(){ } void withdraw(){ } void display(){ System.out.println("Acct Holder Name :"+name); System.out.println("Acct Type :"+type); System.out.println("Acct Number :"+AcctNo); System.out.println("Acct Balance :"+balance); } } class ExecuteAccountE{ public static void main(String args[]){ BankAccount ba=new BankAccount(); ba.display(); } } F) Overload the method deposit () method (one with argument and another without argument) 10 import java.util.Scanner; class BankAccount{ String name,type; int AcctNo; double balance; double wbalance; Scanner input=new Scanner(System.in); public BankAccount(){ } void deposit(){ System.out.println("Enter Balance: "); balance=input.nextDouble(); System.out.println("Balance from deposit: "+balance); } void deposit(double bal){ balance=bal; System.out.println("Balance from deposit(arg): "+bal); } void withdraw(){ } void display(){ } } class ExecuteAccountF{ public static void main(String args[]){ BankAccount ba=new BankAccount(); ba.deposit(); ba.deposit(10000.00); } } 11 G) In Account class, define set and get methods for each instance variables. Example: For account number variable, define the methods. getAccountNo() and setAccountNo(int accno) In each and every method of Account class, reading data from and writing data to instance variables should be done through these variables. import java.util.Scanner; class BankAccount{ String AcctName,Type; long AcctNo; double balance; Scanner s=new Scanner(System.in); void getAcctNo(){ System.out.println("Acct Number is :"+AcctNo); } void setAcctNo(int acctno){ AcctNo=acctno; } void getAcctBalance(){ System.out.println("Acct balance is :"+balance); } void setAcctBalance(double bal){ balance=bal; } void setName(String s){ AcctName=s; } void getName(){ 12 System.out.println("AcctName is:"+AcctName); } void setType(String type){ Type=type; } void getType(){ System.out.println("Account type is: "+Type); } public BankAccount(String Name,String T,long AccNo,double bal){ AcctName=Name; Type=T; balance=bal; AcctNo=AccNo; } void deposit(){ getAcctBalance(); } void withdraw(){ double wbal; System.out.print("Enter with draw amount:"); wbal=s.nextLong(); System.out.println("with draw amount is:"+wbal); balance=balance-wbal; System.out.println("balance after with drawing: "+balance); } void display(){ getAcctNo(); getType(); getName(); } } class ExecuteAccountG{ public static void main(String args[]){ BankAccount ba=new BankAccount("abc","saving",1234,20000.00); ba.display(); ba.getAcctBalance(); ba.withdraw(); ba.deposit(); } } 13 3C). Write a program to demonstrate method overriding. class Vehicle{ void move(){ System.out.println("Vehicle"); } } class Car extends Vehicle{ void move(){ System.out.println("Car"); } } class Overriding{ public static void main(String args[]){ Vehicle v=new Vehicle(); v.move(); Car c=new Car(); c.move(); } } 3D). Write a program to demonstrate the uses of “super” keyword (three uses) 14 class A{ int a=10; A(){ System.out.println("In constructor A"); } void x(){ System.out.println("In method x of A"); } } class B extends A{ int a=20; B(){ System.out.println("In constructor B"); } void x(){ System.out.println("In method x of B"); } void z(){ System.out.println("Value of a in A: "+super.a); System.out.println("Value of a in B: "+a); } } class SuperD{ public static void main(String args[]){ B b=new B(); System.out.println("Calling overridden method"); b.x(); b.z(); } } 3E). Write a program to demonstrate dynamic method dispatch (ie. Dynamic polymorphism) class A{ void x(int a){ System.out.println("Value passed is: "+a); } void x(char b){ System.out.println("Character passed: "+b); 15 } } class PolymorphismE{ public static void main(String args[]){ int integer=43; char character='a'; A c=new A(); c.x(integer); } } 4A) Write a program to check whether the given string is palindrome or not. import java.io.*; import java.lang.*; class PalindromA{ public static void main(String args[]){ int p=0; int n=args[0].length(); for(int i=0;i<n;i++){ if(args[0].charAt(i)!=args[0].charAt(n-i-1)) p=1; } if(p==0) System.out.println("The given String is a Palindrome"); else System.out.println("The given String is not a Palindrome"); } } 16 B) Write a program for sorting a given list of names in ascending order. class StringSortB{ public static void main(String args[]){ String name[]=new String[5]; for (int i = 0; i < args.length; i++){ name[i]=args[i]; } int size=args.length; System.out.println(size); for(int i=0;i<size;i++){ for(int j=i+1;j<size;j++){ if(name[i].compareTo(name[j])>0){ String temp=name[i]; name[i]=name[j]; name[j]=temp; } } } for(int i=0;i<size;i++){ System.out.println(name[i]); } } } 17 C) Write a program to count the number of words in a given text. import java.io.*; import java.util.*; public class WordsCountC{ public static void main(String args[ ])throws IOException{ long nl=0,nw=0,nc=0; String line; BufferedReader br=new BufferedReader(new FileReader(args[0])); while ((line=br.readLine())!=null){ nl++; nc=nc+line.length(); StringTokenizer st = new StringTokenizer(line); nw += st.countTokens(); } System.out.println("Number of Characters: "+nc); System.out.println("Number of Words: "+nw); System.out.println("Number of Lines: "+nl); } } 5A) Define an interface “GeometricShape” with methods area () and perimeter () (both methods return type and parameter list should be void and empty respectively). Define classes like Triangle, Rectangle and Circle implementing the “GeometricShape” 18 Interface and also define “ExecuteMain” class in which include main method to test the above class. import java.util.Scanner; interface GeometricShape{ void area(); void perimeter(); } class Triangle implements GeometricShape{ double a=1,b=2,c=1,h=4; public void area(){ System.out.println(""); double area1=0.5*b*h; System.out.println("Area of a Triangle: "+area1); } public void perimeter(){ double per=a+b+c; System.out.println("Perimeter of a Triangle: "+per); System.out.println(""); } } class Rectangle implements GeometricShape{ int length=15,width=10,per,area1; public void area(){ area1=length*width; System.out.println("Area of Rectangle: "+area1); } public void perimeter(){ per=2*length+2*width; System.out.println("Perimeter of Rectangle: "+per); System.out.println(""); } } class Circle implements GeometricShape{ int r=10; double p=3.141,area1=0.0,per=0.0; public void area(){ area1=p*r*r; System.out.println("Area of Circle: "+area1); } public void perimeter(){ per=2*p*r; System.out.println("Perimeter of Circle: "+per); System.out.println(""); } } 19 class ExecuteMainA{ public static void main(String args[]){ Triangle t=new Triangle(); t.area(); t.perimeter(); Circle c=new Circle(); c.area(); c.perimeter(); Rectangle r=new Rectangle(); r.area(); r.perimeter(); } } B) Define a package with name “sortapp” in which declare an interface “SortInterface” with method sort () whose return type and parameter type should be void and empty. Define “subsortapp” as sub package of “sortapp” package in which define class “SortImpl” implementing “SortInterface” in which sort() method should print a message Linear sort is used. Define a package “searchingapp” in which declare an interface “SearchInterface” with search () method whose return type and parameter list should be void and empty respectively. Define “serachingimpl” package in which define a “SearchImpl” class implementing “SearchInterface” defined in “searchingapp” package in which define a search() method which should print a message linear search is used. Define a class ExecutePackage with main method using the above packages (classes and it’s methods). package sortapp; interface SortInterface{ void sort(); } import sortapp.*; 20 package sortapp.subsortapp; class SortImpl implements SortInterface{ void sort(){ System.out.println("Sort Interface......."); } } package searchingapp; interface SearchInterface{ void search(); } import searchingapp; package searchingimpl; class SearchImpl implements SearchInterface{ void search(){ System.out.println("Search Interface......."); } } import sortapp.SortInterface; import sortapp.subsortapp.SortImpl; import searchingapp.SearchInterface; import searchingimpl.SearchImpl; class ExecutePackageB{ public static void main(String args[]){ SortImpl sort1=new SortImpl(); SearchImpl search1=new SearchImpl(); sort1.sort(); search1.search(); } } 6). Modify the withdraw() method of Account class such that this method should throw “InsufficientFundException” if the account holder tries to withdraw an amount that leads to condition where current balance becomes less than minimum balance otherwise allow the account holder to withdraw and update balance accordingly. import java.util.Scanner; class InsufficientException extends Exception{ double balance; double wbalance; public InsufficientException(String msg){ super(msg); } void withdraw(){ double balance=25000.00; System.out.println("Current Balance: "+balance); try{ System.out.print("Enter withdraw amount: "); Scanner in=new Scanner(System.in); 21 double wamount=in.nextDouble(); if(wamount>balance){ throw new InsufficientException("Insufficient balance in account....."); } else System.out.println("Transaction Successfully Completed..............."); double rembal=balance-wamount; System.out.println("Withdrawal Amount :"+wamount); System.out.println("After transaction current balance :"+rembal); } catch(InsufficientException e){ System.out.println("Caught:"+e.getMessage()); } } } class ExecuteAccount6{ public static void main(String args[]) { InsufficientException ie=new InsufficientException("Insufficient balance in account"); ie.withdraw(); } } 7A) Define two threads such that one thread should print even numbers and another thread should print even numbers. import java.lang.*; import java.util.Scanner; class EvenOdd extends Thread{ 22 public void run(){ System.out.print("Enter nth value: "); Scanner in=new Scanner(System.in); int n=in.nextInt(); int eo[]=new int[n]; System.out.print("Enter values: "); for(int i=0;i<eo.length;i++){ eo[i]=in.nextInt(); } int even[]=new int[10]; int odd[]=new int[10]; for(int i=0;i<eo.length;i++){ if(eo[i]%2==0){ even[i]=eo[i]; } else{ odd[i]=eo[i]; } } System.out.print("Even Numbers:"); for(int i=0;i<even.length;i++){ if(even[i]!=0){ System.out.print(" "+even[i]); } } System.out.println(""); System.out.print("Odd Numbers:"); for(int i=0;i<odd.length;i++){ if(odd[i]!=0){ System.out.print(" "+odd[i]); } } } } class EvenOddA{ public static void main(String args[]){ EvenOdd e=new EvenOdd(); e.start(); } } 23 7B). Modify the Account class to implement synchronization concept. class Account3 extends Thread { int accno; float balance; float amount; Account3(int ano,float bal,float withdrawAmount) { accno=ano; balance=bal; amount=withdrawAmount; } synchronized public void withdraw() { System.out.println("Trying to withdraw Rs."+amount); System.out.println("Getting the balance:"+"\nbalance="+balance); if(balance>=amount) { System.out.println("please collect the cash:"+amount); try { Thread.sleep(1500); } catch(InterruptedException e) { } balance=balance-amount; } else System.out.println("Insufficient funds"); System.out.println("A/C balance is updated to Rs."+balance); } public void run() { 24 withdraw(); } }//Account3 class ThreadSyncB { public static void main(String args[]) { Account3 a1=new Account3(1001,6000,5000); Account3 a2=new Account3(1002,6000,5000); Thread t1=new Thread(a1); Thread t2=new Thread(a2); t1.start(); t2.start(); } } 7D). Write a program to implement thread priority. class Demo extends Thread { public void run() { for(int i=1;i<=3;i++) { System.out.println(getName()+" "+i); } } } class ThprDemoD { public static void main(String args[]) { Demo obj=new Demo(); Demo obj1=new Demo(); Demo obj2=new Demo(); obj.setPriority(Thread.MAX_PRIORITY); 25 obj1.setPriority(Thread.MIN_PRIORITY); obj2.setPriority(Thread.NORM_PRIORITY); obj.start(); obj1.start(); obj2.start(); } } 8). Design the user screen as follows and handle the events appropriately. import java.awt.*; import java.awt.event.*; public class AddWindow extends Frame implements ActionListener{ Label l1,l2,l3; TextField t1,t2,t3; Button b1,b2; AddWindow() { super("add window"); //setting the size of the window setSize(250,400); l1=new Label("First Number :"); l2=new Label("Second Number:"); l3=new Label("RESULT :"); t1=new TextField(10); t2=new TextField(10); t3=new TextField(10); b1=new Button("add "); b2=new Button("subtract "); //setting the layout of the container window setLayout(new FlowLayout()); //adding the controls to the container window add(l1); 26 add(t1); add(l2); add(t2); add(l3); add(t3); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); setVisible(true); } public void actionPerformed(ActionEvent ae) { int n1=Integer.parseInt(t1.getText()); int n2=Integer.parseInt(t2.getText()); if(ae.getSource()==b1) { int add=n1+n2; t3.setText(add+""); } if(ae.getSource()==b2) { int subtract=n1-n2; t3.setText(subtract+""); } }//actionPerformed method public static void main(String args[]) { new AddWindow(); }//main method }//class 27 11). Develop a simple client server program (one way communication) import java.io.*; import java.net.*; class Client1 { public static void main(String args[])throws Exception { Socket s=new Socket("localhost",777); InputStream obj=s.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(obj)); String str; while((str=br.readLine())!=null) System.out.println("From server:"+str); br.close(); s.close(); } } import java.io.*; 28 import java.net.*; class Server1 { public static void main(String args[])throws Exception { ServerSocket ss=new ServerSocket(777); Socket s=ss.accept(); System.out.println("Connection Established\n"); OutputStream obj=s.getOutputStream(); PrintStream ps=new PrintStream(obj); String str="Hello client"; ps.println(str); ps.println("bye"); ps.close(); ss.close(); s.close(); } } 12). Develop a client that sends data to the server and also develop a server that sends data to the client (two way communication) import java.io.*; import java.net.*; class Client2 { public static void main(String args[])throws Exception { 29 Socket s=new Socket("localhost",777); DataOutputStream dos=new DataOutputStream(s.getOutputStream()); InputStream obj=s.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(obj)); BufferedReader kb=new BufferedReader(new InputStreamReader(System.in)); String str,str1; while(!(str=kb.readLine()).equals("exit")) { dos.writeBytes(str+"\n"); str1=br.readLine(); System.out.println(str1); } dos.close(); br.close(); kb.close(); s.close(); } } import java.io.*; import java.net.*; class Server2 { public static void main(String args[])throws Exception { ServerSocket ss=new ServerSocket(777); Socket s=ss.accept(); System.out.println("Connection Established\n"); OutputStream obj=s.getOutputStream(); PrintStream ps=new PrintStream(obj); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedReader kb=new BufferedReader(new InputStreamReader(System.in)); while(true) { String str,str1; while((str=br.readLine())!=null) { System.out.println(str); str1=kb.readLine(); ps.println(str1); } ps.close(); br.close(); kb.close(); ss.close(); s.close(); 30 System.exit(0); } } } 31 32