0% found this document useful (0 votes)
43 views28 pages

Javasepprogramsmuntaha

The document is a lab manual for object-oriented programming in Java, containing various programming exercises. It includes examples of basic Java programs such as displaying 'Hello World', implementing static and local variables, string operations, and handling exceptions. The manual also covers concepts like inheritance, method overloading, and runtime polymorphism, providing outputs for each program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
43 views28 pages

Javasepprogramsmuntaha

The document is a lab manual for object-oriented programming in Java, containing various programming exercises. It includes examples of basic Java programs such as displaying 'Hello World', implementing static and local variables, string operations, and handling exceptions. The manual also covers concepts like inheritance, method overloading, and runtime polymorphism, providing outputs for each program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 28
is Appendix A OBJECT-ORIENTED PROGRAMMING LAB LAB MANUAL 1, Java program to display “Hello World” and display the size of all the data types. class Size Of DataTypes { Public static void main(String[] args) { System.out printIn(“Hello World”); System.outprintin(“S.No,\t Data Type\t Size”); System.out.printin(“I\t\t Byte\t\\t" + Byte. SIZE); System.out.printIn(“2\tt Short\t\\t" + Short. SIZE); System.out.printIn(“3\\t Integerit\t” + Integer SIZE); System.out.printin(“4\\t Floai\t\t\e" + Float.SIZE); System.outprintin(“S\t\t Long\t\t\t” + Long. SIZE); System.out.printIn(“6\t\t Double\t\t” + Double.SIZE); System.out.printin(“7\\t Character\t\t” + Character.SIZE); } } OUTPUT: Hello World S.No. Data Type Size 1 Byte 8 2: Short 16 3 Integer 32 4 Float 32 5 Long 64 6 Double 64 7 Character 16 | 474 Object-Oriented Programming: Usin ; ‘JAY, 2. Java program to implement the usage of static, local and global variables, public class InstaneeCounter { Statie/Global variable numlnstances private static int numInstances = 0; protected static int getCount() { return numInstances; } private static void addInstance() { numInstances++; } InstanceCounter() { InstanceCounter.addinstance(); } public static void main(String{] arguments) { // Local variable pi float pi=22/7f; System. out printin(“"Value of Pi = “ + pi); System. out printin(“Starting with “+ InstanceCounter.getCount() + “ instances”) for (int i= 0; 1<5; ++i) { new InstanceCounter(); } System.out.println(“Created “ + InstanceCounter.getCount() + “ instances”); 3 j OUTPUT: Value of Pi = 3.142857 Starting with 0 instances Created 5 instances acti > ppendix:LAB Manual i768 3, Java program to implement string operations string length, string concatenate, substring class StringOperations { public static void main(String{] args) { String firstname="Sachin”; String middlename=” Ramesh”; String lastname=” Tendulkar”; String name=firstname.concat(middlename).concat(lastname); System.out.printIn(“Name is: “ + name); System.out.printIn(“Lenth of name is: “ + name.length()); System.out printIn(“substing of name is: “ + name.substring(7,13)); OUTPUT: ‘Name is: Sachin Ramesh Tendulkar Lenth of name is: 23 substing of name is: Ramesh 4, Java program to find the maximum of three numbers import java.util. Seanner; class MaxOfThreeNumbers { public static void main(String[] args) { int a, b, c, largest, temp; Scanner sc = new Scanner(System.in); System.out printIn(“Enter the first number:”); a= se.nextintQ; ‘System.out.printin(“Enter the second number:”); | b= se.nextInt(; System.out.printIn(“Enter the third number:"); "c= sc.nextint(); //comparing a and b and storing the largest number in a temp variable SALE SPECIMEN Cory NOF COR 176 Object-Oriented Programming Using ava temp=a>b7a:b; largest=c>temp?c:temp; } i in the variab| //comparing the temp variable with c and storing the result in the variable System.out printIn(“The largest number is: “+largest); OUTPUT: Enter the first number: 12 Enter the second number: 47 Enter the third number: 15 ‘The largest number is: 47 5. Java program to check whether the number is odd or even, import java.util. Scanners Public class EvenOdd { Public static void main(String{] args) { System.out.print(“Enter a number: « int num = reader.nextint(); iffnum % 2 = 0) System.out.printin(num + « else System.out.printin(num + } Scanner reader = new Scanner(System, is even”); is odd”); 3 | oar ———__| Enter a number: 5 Sis odd Appendix-LAB Manual 6, Java program to i plement default and parameterized constructors. import java.util, class Box { double width; double height; double depth; Box() { width = 12.7d; height = 15.0 ‘anner;, depth = 5.64; } Box(double w, double h, double d) { width = w; double volume() { return width * height * depth; } } class Main { public static void main(String{] args) { Box Box! = new Box(); Box Box2 = new Box(4.74, 8.54, 6.34); double vol; // get volume of first box vol = Box1.volume(); System.out.printIn(“Volume of Box1: “ + vol); // get volume of second box vol = Box2.volume(); System.out. printIn(“Volume of Box2: “ + vol); 3 OUTPUT: Volume of Box1: 1066.8 Volume of Box2: 251.685 177 178 > Object-Oriented Programming Using jay, Java program to implement an array of objects. import java.util Scanner; class Car { public String name; public int miles; public Car(String name, int miles) { this.name = name; this.miles = miles; public void printDetails() { System.out.printIn(name+” - “+miles); } } class Main { public static void main(String[] args) { Car cars{] = { new Car(““Tesla”, 142000), new Car(“BMW”, 485000), new Car(“Tata”, 564000), new Car(“Ford”, 580000) 8 for(Car car: cars) car-printDetails(); OUTPUT: Tesla - 142000 BMW - 485000 Tata - 564000 Ford — 580000 appendiccLAB Manual oy ¢ Java program to implement ingle Inheritance public int g« public int speed; public Bicycle(int gear, int speed) { this.gear = gear; this.speed = speed; } public void applyBrake(int decrement) { speed = decrement; } public void speedUp(int increment) { speed += increment; 3 public String toString() { return (“No of gears are “ + gear + "\n” + “speed of bicycle is “ + speed); // derived class/sub class class MountainBike extends Bicycle { public int seatHeight; public MountainBike(int gear, int speed, int startHeight) ~ Object-Oriented Programming Using jay, 180 super(gear, speed); seatHeight = startHeight; : i yValue) Public void setHeight(int new Val { seatHeight = newValue; } Public String toString) ' ight is “ return (super.toString() + “\nseat height is + seatHeight); } class Main { Public static void main(String] args) { MountainBike mb = new MountainBike(3, 100, 25); System.out.printin(mb toString()); } } OUTPUT; Speed of bicycle is 199 Seat height is 25 aracter | Void attack), imerface Weapon Void use(), ce aa Manual galas Warrior implements Character, Weapon { ublic void attack() { gystem.out-printin(“Warrior attacks with a sword. } public void use ( system. out-printin(“Warrior uses a sword.”); } } jes Mage implements Character, Weapon { public void attack() { ystem.out printin(“Mage attacks with wand.”); } public void use() { system.out.printin(“Mage uses @ wand.”); } class Main { public static void main(String{] args) { Warrior warrior = new Warrior); Mage mage = new Mage()s warrior.attack(); warrior.useQs mage.attack(); mage.use(); 3 } OUTPUT: Warrior attacks with a sword. Warrior uses 4 sword. Mage attacks with a wand. Mage uses a wand. 181 NOT FOR SALE _, 182 Object-Oriented Programming Using AY, 10. Java program to implement an applet //SumNumslnteractive..java import java.applet. Applet; import java.awt.*; Public class SumNumsInteractive extends Applet { TextField text, text2; public void init() { text] = new TextField(10); text2 = new TextField(10); text setText(“0"); text2.setText(“0”); add(text); add(text2); 3 Public void paint(Graphics g) { int num] = 0; int num2 = 0; int sum; String s1, 82, s3; gdrawString(“Input a number in each box “, 10, 50); try { sl] = text] getText(); num = Integer.parseInt(s1); 82 = text2.getText(); num2 = Integer.parseInt(s2); } catch(Exception e1) } sum = num] + num2; String str = “THE SUM I +String.valueOf(sum); ea ea eine (ir 100, 125); } ‘i , wablic poolean action(Event ev, Object obj) { repaints return true; } } OUTPUT: eee Sum of Numbers Input a number in each box THE SUMIS: 15 11. Java program to demonstrate a division by zero exception import java.util.Scanner; public class Division_By_Zero_Exception { public static void main(String[] args) { try{ Scannet int number, number2, output; sc=new Scanner(System.in); 183 Cuter cary NOT FOR SALE srrcimen | 184 Object-Oriented Programming yg “RIAy, A System.out.print(“Enter first number : “); numberl=se.nextInt(); System.out.print(“Enter second number : “); number2=se.nextint(); output=number! /number2; System.out.printIn(“Result:”+output); } catch(ArithmeticException e) { System.out printIn(“Error:”+e.getMessage()); System.out printIn(“Exror:”+e); } System.out.printIn(“...End of Program...”); ) } ee. yy’... Outputs Enter first number : 20 Enter second number : 10 Result:2 .End of Program... Output Enter first number : 25 Enter second number : 0 Error:/ by zero Error;java.lang. ArithmeticException: / by zero .oEnd of Program... yn endE Manual _ java program (0 add Ovo integers and two float numbers. When no arguments a pplied give a default value to os thod overloading, Fmport java public class MethodOverload { [Method to add two integers public int add(int a, int b) { return a +b; 1 Method to add two float numbers public float add(float a, float b) { return a + b; // Method to add two integers with default values public int addQ) { retu add(5, 10); / default values // Method to add two float numbers with default values public float add(float a) { return add(a, 2.50; /default value } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); MethodOverload calculator = new MethodOverload(); System.out.printIn(““Enter two integers (separated by space) (or press Enter for default):”); String intInput = scanner.nextLine(); if (intInput.isEmpty()) { r FOR SALE NOT SPECIMEN cory > 186 Object-Oriented Programming y,, 8 ayy }else { String[] intValues = intInput.split(* “); int a = Integer.parselnt(intValues[0]); int b = Integer.parseInt(intValues{1]); System.out.printIn(“Sum of integers: “+ calculator.add(a, b)); } System.out printIn(“Enter two float numbers (separated by space) (or press Enter for default):”); String floatInput = scanner.nextLine(); if (floatInput.isEmpty() { System. out printin(“Sum of default floats: “ + calculator.add(1.5f); }else { String[] floatValues = floatInput.split(“ “); float x = Float parseFloat(floatValues[0]); float y = Float parseFloat(floatValues{1]); System.out.printIn(“Sum of floats: “ + calculator.add(x, y)); } scanner.close(); } OUTPUT Output: When user enters both values Enter two integers (separated by space) (or press Enter for default): 15.25 Sum of integers: 40 Enter two float numbers (separated by space) (or press Enter for default): 63.2 56.1 Sum of floats: 119.3 > appendix LA 13. B Manual user is not enteril ue and press enters Enter for default): Output: Whi Enter two integers (or pres sum of default integers: 15 ter two float numbers (or press Enter for default): 0 Ent ‘Sum of default floats: Java program that demonstrates run-time polymorphism. class Employee { 1 Method to be overridden public void work() { ‘System.out printIn(“Employee is working”); } class Developer extends Employee { / Overriding the work method @Override public void work() { system.out.printin(“Developer is writing code”); class Manager extends Employee { W/Overriding the work method @Override public void work() { ystem.out.printin(*Manager is managing the team”); 3 ‘ pe a 187 : = TT Object-Oriented Programming Using JAVA class Designer extends Employee { 4 Overriding the work method @Override Public void work() { System.out.printin(“Designer is creating designs”); } } Public class RunTimePolymorphism { Public static void main(Stringf] args) { System.out.printin(“Demo for Runtime Polymorphism”); System.out. Print In ys Employee reference but Developer object Employee emp = new Developer(); emp.work(); 7 Employee reference but Manager object emp = new Manager(); emp.workQ; 7 Employee reference but Des igner object emp = new Designer(); emp.work(); ~ new Employee(); emp.work(); } } oo appendixcLAB Manual 189 OUTPUT Demo for Runtime Polymorphism —_—— Developer is writing code Manager is managing the team Designer is creating designs Employee is working 14. Java program to catch negative array size Exception. This exception is caused when the array is initialized to negative values. [import java.util.*; public class Negative_array Exception { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the size of the array: “); int size = scanner.nextInt(); try { // Attempt to create an array with the specified size int{] array = new int{size]; System.out.printIn(“Array of size “ + size + “ created successfully.”); } catch (NegativeArraySizeException e) { System.out.printIn(“Error: Array size cannot be negative.”); } catch (InputMismatchException e) { System.out.printIn(“Error: Invalid input. Please enter a valid integer.”); seannernext(); // Clear the invalid input finally { scanner.close(); System.out.printin(* ™ 190 Object-Oriented Prog, je Bramming Using ayy OUTPUT: Output for positive integer Enter the size of the array: 10 Array of size 10 created successfully. ——END OF THE PROGRAM. Output for negative integer Enter the size of the array: -6 4 Error: Array size cannot be negative. ‘ —END OF THE PROGRAM—— H Output for other than integer d Enter the size of the array: C Exception in thread “main” java.util.InputMismatchException at java. base/java.util.Scanner.throwFor(Scanner,java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java. base/java.util.Scanner.nextInt(Scanner,java:2258) at java. base/java.util.Scanner.nextInt(Scannerjava:2212) at Book_Java_Lab/LabPrograms.Negative_array_Exception.main(Negative_array Exception,java:11) 15. Java program to handle null pointer exception and use the “finally” method to display a message to the user. import java.util.*; public class NullPointer_Exception { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ndix-LAB Manual Apre! 55% System.out.print(“Enter a string: "); String input = scanner.nextLine(); try { if (input.isEmpty() { input = null; } System.out.printIn(“Length of the string: “ + input.length()); } catch (NullPointerException e) { System.out.printIn(“A null pointer exception occurred.”); } finally { System.out.printin(*——END OF PROGRAM——"); scanner.close(); OUTPUT Output 1: Input is entered ser Enter a string: Java World Length of the string: 10 ——END OF PROGRAM—— Output 1: No Input Enter a string: ‘A null pointer exceptio ___END OF PROGRAM yn occurred. i ™“ 192 Object-Oriented Programming Using. JAVA 16, Java program to import user-defined packages. Step 1: Create a package “shape” inside ‘sre’ folder in the working project. Step 2: Inside ‘shape’ create three classes ‘Circle,java’, ‘Square java’, “Triangle jayg? Step 3: Outside the ‘shape’ package create main class file ‘CustomPack java’ Step 4: Run the ‘CustomPack.java’ Circle.java package shape; public class Circle { private double radius; public Circle(double r) { radius=r; } public double area() { return (3.14*radius*radius); ‘Square.java package shape; public class Square { private int side; public Square(int s) { side=s; i public int area() { return (side*side); bo - appendix-LAB Manual nes Triangle.java ‘package shape; public class Triangle { private int sidel,side2,side3; public Triangle(int s1,int s2,int s3) { sidel=s1; side2=s2; side3=s3; } public double area() { double s=(sidel +side2+side3)/2; double a=Math.sqrt((s-side1)+(s-side2)+(s-side3)); return a; CustomPack.java package LabPrograms; import shape.*; import java.util.*; public class CustomPack { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.printIn(“Enter The side of the Square : “); int s=sc.nextInt(); Square sq=new Square(s); System.out.printin(“Area of Square is “ + sq.area()); “Enter The radius of the Circle : System.out.printIn(“ double r=sc.nextDoubleQ); Circle cmnew Cire System.out printn(‘Area of Cirele is “+ ¢ tem. out printin(“Enter The Sides of the Triangle : “); int s]=se.nextInt(); int s2=se.nextInt(); int s3=se.nextInt(); shape. Triangle t=new shape. Triangle(s1,s2,s3); System.out.printin(“Area of Triangle is “+ tarea()); } } é t y OUTPUT ; Enter the side of the Square: 7 i Area of Square is 49 ) Enter the radius of the Circle: 6 Area of Circle is 153.86 Enter The Sides of the Triangle: 6 a 8 Area of Triangle is 2.8284271247461903 appendix: LAB Manual 17. Java program to check whether a number is palindrome or not import java.util.Scanner; public class PalindromeChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a number: “); int number = scanner.nextInt(); int originalNumber = number; int reversedNumber = 0; while (number != 0) { int digit = number % 10; reversedNumber = reversedNumber * 10 + digit; number /= 10; if (originalNumber = reversedNumber) { System. out.printIn(originalNumber + “ is a palindrome.”); } else { } scanner.close(); System.out printIn(originalNumber + “ is not a palindrome.”); 195 ON 196 Object-Oriented Programming Using A Output: Enter a number: 78524 78524 is not a palindrome Output 2: Enter a number: 9669 9669 is a palindrome. 18. Java program to find the factorial of a list of numbers reading input as command line argument. import java.math. BigInteger; public class FactorialDemo { public static void main(String{] args) { for (String arg : args) { try { int number = Integer.parselnt(arg); System.out.println(“Factorial of “ + number + “= “+ factorial(number)); } catch (NumberFormatException e) { System.out printin(arg + “ is not a valid number.”); 3 Private static BigInteger factorial(int number) { BigInteger result = Biginteger.ONE; for (int i = 2; 5 1<= number; i++) { resull = result multiply(Biginteger.valueOf{i)); y icc LAB Manual 497 return result; } } + InEclipse IDE open Run => Run Configurations. « Click on ‘Arguments’ tab. « Inside ‘Program Arguments’ enter list of numbers one by one. + Finally click on ‘Run’ to see the output. OUTPUT Factorial of 5 = 120 Factorial of 4 = 24 Factorial of 7 = 5040 19, Java program to display all prime numbers between two limits. import java.util. Scanner; public class PrimeNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the lower limit: “); int lowerLimit = scanner.nextInt(); System.out.print(“Enter the upper limit: “); int upperLimit = scanner.nextInt(); System outprintin(“Primenumbers between “+ TowerLimit+**and"+-upperLimit+“are:") for (int num = lowerLimit; num <> upperLimit; num++) { if (isPrime(num)) { System.out.print(num + “ ‘5 4 ? 198 } } Public static boolean isPrime(int number) { if (number <= 1) { return false; } for (int i = 2; i <= Math.sqrt(number); i++) { if (umber % i == 0) { return false; 3 } return true; 3 i OUTPUT Enter the lower limit: 12 Enter the upper limit: 40 Prime numbers between 12 and 40 are: class My Thread implements Ramnable private String threadName; public MyThread(String threadName) { this.threadName = threadName; t @Override public void run() { System.out.printIn(threadName + “ started.”); for (int i= 0; i< 5; i+) { System.out println(threadName + “+ i); try { 13 17 19 23 29 31 37 20. Java program to create a thread using Runnable Interface, ON Object-Oriented Programming Using ay ‘A Thread.sleep(1000); W Sleep for 1 second } catch (InterruptedException e) { System.out printIn(threadName +“ interrupted.”); } TT 199 System.out.printn(t hreadName + ie + “ finished.”); "ys } } ublic class ThreadRunnable { public static void main(Strin; Create two threads BU] args) { MyThread thread =n ew MyThread(“ » MyThread thread? = new My eae 5 Create Thread objects and pass the aba lara "ys ‘Thread tl = new Thread(thread1); fe instances ‘Thread t2 = new ‘Thread(thread2); start the threads , t1.start(; t2.start(); OUTP! Thread-2 started. Thread-2: 0 Thread-1 started. Thread-1: 4 Thread-2 finished. Thread-1 finished. yurse of Bengaluru city emester BCA Co aluru yniversity For 274 Si University and Beng:

You might also like