[Go to site: main page, start]

0% found this document useful (0 votes)
85 views17 pages

Java Programming Lab Exercises

Here is a Java program to create an interface with two methods and implement it in another class: 1. interface A { 2. public void meth1(); 3. public void meth2(); 4. } 5. public class B implements A { 6. public void meth1() { 7. System.out.println("Method 1 implemented"); 8. } 9. public void meth2() { 10. System.out.println("Method 2 implemented"); 11. } 12. public static void main(String[] args) { 13. B obj = new B(); 14. obj.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views17 pages

Java Programming Lab Exercises

Here is a Java program to create an interface with two methods and implement it in another class: 1. interface A { 2. public void meth1(); 3. public void meth2(); 4. } 5. public class B implements A { 6. public void meth1() { 7. System.out.println("Method 1 implemented"); 8. } 9. public void meth2() { 10. System.out.println("Method 2 implemented"); 11. } 12. public static void main(String[] args) { 13. B obj = new B(); 14. obj.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING LAB

WEEK – 1 JAVA BASICS


a. Write a java program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use the quadratic formula.
b. The Fibonacci sequence is defined by the following rule. The first two values
in the sequence are 1 and 1. Every subsequent value is the sum of the two
values preceding it. Write a java program that uses both recursive and non-
recursive functions.

a. QuadraticEquation
1. import [Link];
2. public class QuadraticEquationExample1
3. {
4. public static void main(String[] Strings)
5. {
6. Scanner input = new Scanner([Link]);
7. [Link]("Enter the value of a: ");
8. double a = [Link]();
9. [Link]("Enter the value of b: ");
[Link] b = [Link]();
[Link]("Enter the value of c: ");
[Link] c = [Link]();
[Link] d= b * b - 4.0 * a * c;
[Link] (d> 0.0)
15.{
[Link] r1 = (-b + [Link](d, 0.5)) / (2.0 * a);
[Link] r2 = (-b - [Link](d, 0.5)) / (2.0 * a);
[Link]("The roots are " + r1 + " and " + r2);
19.}
[Link] if (d == 0.0)
21.{
[Link] r1 = -b / (2.0 * a);
[Link]("The root is " + r1);
24.}
[Link]
26.{
[Link]("Roots are not real.");
28.}
29.}
30.}

Output 1:

Output 2:

b. non recursive
import [Link];

class Fib {

public static void main(String args[ ]) {

Scanner input=new Scanner([Link]);

int i,a=1,b=1,c=0,n;

[Link]("Enter value of n: ");

n=[Link]();

[Link](a);

[Link](" "+b);

for(i=0;i<n-2;i++) {

c=a+b;

a=b;

b=c;
[Link](" "+c);

[Link]();

[Link](n+"th number of the series is: "+c);

Output

Recursive Solution
import [Link].*;

import [Link].*;

class Fib1 {

int fib(int n) {

if(n==1)

return (1);

else if(n==2)

return (1);

else

return (fib(n-1)+fib(n-2));

class FibR {
public static void main(String args[])throws IOException {

InputStreamReader obj=new InputStreamReader([Link]);

BufferedReader br=new BufferedReader(obj);

[Link]("Enter value of n: ");

int n=[Link]([Link]());

Fib1 ob=new Fib1();

[Link]("Fibonaccie Series is:");

int res=0;

for(int i=1;i<=n;i++) {

res=[Link](i);

[Link](" "+res);

[Link]();

[Link](n+"th number of the series is: "+res);

Output

WEEK – 2 ARRAYS
a. Write a java program to sort given list of integers in ascending order.
b. Write a java program to multiply two given matrice
a.
sorting of arrays
1. public class SortAsc {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {5, 2, 8, 7, 1};
5. int temp = 0;
//Displaying elements of original array
6. [Link]("Elements of original array: ");
7. for (int i = 0; i < [Link]; i++) {
8. [Link](arr[i] + " ");
9. }
10. //Sort the array in ascending order
11. for (int i = 0; i < [Link]; i++) {
12. for (int j = i+1; j < [Link]; j++) {
13. if(arr[i] > arr[j]) {
14. temp = arr[i];
15. arr[i] = arr[j];
16. arr[j] = temp;
17. }
18. }
19. }
20.
21. [Link]();
22. //Displaying elements of array after sorting
23. [Link]("Elements of array sorted in ascending order: ");

24. for (int i = 0; i < [Link]; i++) {


25. [Link](arr[i] + " ");
26. }
27. }
28.}

Output:

Elements of original array:


52871
Elements of array sorted in ascending order:
12578
c. Multiply matrix

public class MatrixMultiplicationExample{


public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
[Link](c[i][j]+" "); //printing matrix element
}//end of j loop
[Link]();//new line
}
}}

Output:

666
12 12 12
18 8 18

WEEK – 3 STRINGS
a. Write a java program to check whether a given string is palindrome.
b. Write a java program for sorting a given list of names in ascending order.
a. Palindrome Program in Java

1. import [Link].*;
2. class PalindromeExample2
3. {
4. public static void main(String args[])
5. {
6. String original, reverse = ""; // Objects of String class
7. Scanner in = new Scanner([Link]);
8. [Link]("Enter a string/number to check if it is a palindro
me");
9. original = [Link]();
10. int length = [Link]();
11. for ( int i = length - 1; i >= 0; i-- )
12. reverse = reverse + [Link](i);
13. if ([Link](reverse))
14. [Link]("Entered string/number is a palindrome.");
15. else
16. [Link]("Entered string/number isn't a palindrome.");
17. }
18.}
Output :
Enter a string/number to check if it is a palindrome lol
Entered string/number is a palindrome
[Link] names
// Java Program to Sort Names in an Alphabetical Order
import [Link].*;

class GFG {
public static void main(String[] args)
{
// storing input in variable
int n = 4;

// create string array called names


String names[]
= { "Rahul", "Ajay", "Gourav", "Riya" };
String temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {

// to compare one string with other strings


if (names[i].compareTo(names[j]) > 0) {
// swapping
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}

// print output array


[Link](
"The names in alphabetical order are: ");
for (int i = 0; i < n; i++) {
[Link](names[i]);
}
}
}
Output :The names in alphabetical order are :
The names in alphabetical order are :Ajay
Gourav
Rahul
Riya
WEEK – 4 OVERLOADING & OVERRIDING
a. Write a java program to implement method overloading and constructors
overloading.
b. Write a java program to implement method overriding.
a.
method overloading

class MethodOverloading {
private static void display(int a){
[Link]("Arguments: " + a);
}
private static void display(int a, int b){
[Link]("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}

Output:

Arguments: 1
Arguments: 1 and 4

Constructor overloading
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. [Link]("this a default constructor");
8. }
9.
[Link](int i, String n){
[Link] = i;
[Link] = n;
13.}
14.
[Link] static void main(String[] args) {
16.//object creation
[Link] s = new Student();
[Link]("\nDefault Constructor values: \n");
[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);
20.
[Link]("\nParameterized Constructor values: \n");
[Link] student = new Student(10, "David");
[Link]("Student Id : "+[Link] + "\nStudent Name : "+stu
[Link]);
24.}
25.}

Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

b.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){[Link]("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){[Link]("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. [Link]();//calling method
15. }
16.}

Output:

[Link] is running safely

WEEK – 5 INHERITANCES
Write a java program to create an abstract class named Shape that contains
two integers and an empty method named print Area (). Provide three classes
named Rectangle, Triangle and Circle such that each one of the classes extends
the class Shape. Each one of the classes contains only the method print Area ()
that prints the area of the given shape.

import [Link].*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
[Link]("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
[Link]("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
[Link]("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
[Link](2,5);
Circle c=new Circle();
[Link](5,5);
Triangle t=new Triangle();
[Link](2,5);
}
}

Output:
Area of rectangle is :10.0
Area of circle is :78.5
Area of triangle is :5.0

WEEK – 6 INTERFACES
a. Write a program to create interface A in this interface we have two method
meth1 and meth2. Implements this interface in another class named My Class.
b. Write a program to give example for multiple inheritances in Java.
a.
// One interface an extend another.

interface A
{
void meth1();
void meth2();
}
// B now includes meth1() and meth2()–it adds meth3().
interface B extends A
{
void meth3();
}
// This class must implement all of A and B
class MyClass implements B
{
public void meth1 ( )
{
[Link](“Implement meth1().”);
}
public void meth2()
{
[Link] (“Implement meth2().”);
}
public void meth3()
{
[Link] (“Implement meth().” );
}
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

output:
method 1
method 2
method 3

b.
interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
[Link]("Animal is eating");
}
public void travel() {
[Link]("Animal is travelling");
}
}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
[Link]();
[Link]();
}
}
Output
Animal is eating
Animal is travelling

WEEK – 7 EXCEPTION HANDLING


Write a program that reads two numbers Num1 and Num2. If Num1 and Num2
were not integers, the program would throw a Number Format Exception. If
Num2 were zero, the program would throw an Arithmetic Exception Display
the exception.

import [Link];

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter num1: ");
String num1 = [Link]();
[Link]("Enter num2: ");
String num2 = [Link]();

try {
int result = [Link](num1) / [Link](num2);
[Link]("Result: " + result);
} catch (NumberFormatException e) {
[Link]("Both arguments must be integers");
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
}
}
Output :
Eneter num1: 10
Enter num2:5
Result:2
Eneter num1:1
Eneter num 2:0
Cannot divide by zero
Enter num1 :1
Enter num 2:a
Both arguments must be integers
WEEK – 8 I/O STREAMS
a. Write a java program that reads a file name from the user, and then displays
information about whether the file exists, whether the file is readable,
whether the file is writable, the type of file and the length of the file in bytes.
b. Write a java program that displays the number of characters, lines and
words in a text file.
a.
import [Link].*;

import [Link].*;

class AboutFile{

public static void main(String[] args){

Scanner input = new Scanner([Link]);


[Link]("Enter the name of the file:");

String file_name = [Link]();

File f = new File(file_name);

if([Link]())

[Link]("The file " +file_name+ " exists");

else

[Link]("The file " +file_name+ " does not exist");

if([Link]()){

if([Link]())

[Link]("The file " +file_name+ " is readable");

else

[Link]("The file " +file_name+ " is not readable");

if([Link]())

[Link]("The file " +file_name+ " is writeable");

else

[Link]("The file " +file_name+ " is not writeable");

[Link]("The file type is: "


+file_name.substring(file_name.indexOf('.')+1));

[Link]("The Length of the file:" +[Link]());

Output:

Common questions

Powered by AI

The recursive Fibonacci sequence generation uses a function call stack that calls itself with a reduced parameter until a base case is reached, making it less efficient due to repeated calculation of the same values. In contrast, the non-recursive version uses an iterative approach with a loop to calculate each term, storing intermediate results, which is generally more efficient and easier to debug .

Abstract classes in Java, such as the `Shape` class, provide a blueprint for subclasses by defining abstract methods like `area()` that must be implemented by subclasses. This design enforces a common protocol for all shapes, ensuring uniformity in operations like area calculation, while allowing customization via subclass-specific implementations. This approach fosters code reusability and an organized hierarchy .

The program handles exceptions using a try-catch block. It reads two strings, attempts to convert them into integers, and divides them. If the input strings cannot be converted, a `NumberFormatException` is thrown and caught, displaying an error message. If division by zero is attempted, an `ArithmeticException` is thrown and caught, indicating division by zero is not possible .

The QuadraticEquationExample1 program determines if a quadratic equation has real solutions by calculating the discriminant of the equation, which is `b*b - 4*a*c`. If the discriminant is greater than zero, there are two real solutions. If it equals zero, there is one real solution. If it is less than zero, the roots are not real .

The `Animal` class example in Java demonstrates the use of interfaces `AnimalEat` and `AnimalTravel` to implement multiple inheritance. Since Java does not support multiple inheritance with classes, interfaces provide a way to achieve similar functionality. The `Animal` class implements both interfaces, allowing it to inherit the methods `eat` and `travel`, thereby achieving multiple inheritance in a controlled and flexible manner .

The AboutFile Java program reads file attributes by checking if a file exists, is readable, or is writable, using file object methods `exists()`, `canRead()`, and `canWrite()`. It also extracts the file type by parsing its name and calculates the file's length in bytes using `length()`. This information is then printed to the console .

Recursive approaches for generating Fibonacci numbers in Java involve exponential time complexity due to repeated calculations of the same subproblems, leading to significant overhead with deep recursion calls. Non-recursive approaches, however, employ iterative loops with linear time complexity, which are more efficient, as they avoid repeated work and large call stacks by storing intermediate results .

Method overloading is demonstrated by defining multiple methods with the same name `display` but with different parameters within the `MethodOverloading` class. One method takes a single integer, while the other takes two integers. This allows method calls with different argument lists to invoke the appropriate overloaded variant .

The `Shape` abstract class in Java implements polymorphism by providing a method `area()` that is inherited by its subclasses `Rectangle`, `Circle`, and `Triangle`. Each subclass implements the `area()` method differently, calculating and printing the area specific to its geometric shape. This design allows objects of the different subclasses to be handled through references of the abstract class, leveraging runtime polymorphism to execute the appropriate method implementation based on the actual object type .

The Java program sorts an array of integers in ascending order by using a simple selection sort algorithm. It repeatedly finds the smallest element from the unsorted part and swaps it with the first unsorted element, gradually expanding the sorted section of the array .

You might also like