0% found this document useful (0 votes)
137 views

Java Programming Lab

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Java Programming Lab

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

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 java.util.Scanner;
2. public class QuadraticEquationExample1
3. {
4. public static void main(String[] Strings)
5. {
6. Scanner input = new Scanner(System.in);
7. System.out.print("Enter the value of a: ");
8. double a = input.nextDouble();
9. System.out.print("Enter the value of b: ");
10.double b = input.nextDouble();
11.System.out.print("Enter the value of c: ");
12.double c = input.nextDouble();
13.double d= b * b - 4.0 * a * c;
14.if (d> 0.0)
15.{
16.double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a);
17.double r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a);
18.System.out.println("The roots are " + r1 + " and " + r2);
19.}
20.else if (d == 0.0)
21.{
22.double r1 = -b / (2.0 * a);
23.System.out.println("The root is " + r1);
24.}
25.else
26.{
27.System.out.println("Roots are not real.");
28.}
29.}
30.}

Output 1:

Output 2:

b. non recursive
import java.util.Scanner;

class Fib {

public static void main(String args[ ]) {

Scanner input=new Scanner(System.in);

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

System.out.print("Enter value of n: ");

n=input.nextInt();

System.out.print(a);

System.out.print(" "+b);

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

c=a+b;

a=b;

b=c;
System.out.print(" "+c);

System.out.println();

System.out.print(n+"th number of the series is: "+c);

Output

Recursive Solution
import java.io.*;

import java.lang.*;

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(System.in);

BufferedReader br=new BufferedReader(obj);

System.out.print("Enter value of n: ");

int n=Integer.parseInt(br.readLine());

Fib1 ob=new Fib1();

System.out.print("Fibonaccie Series is:");

int res=0;

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

res=ob.fib(i);

System.out.print(" "+res);

System.out.println();

System.out.println(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. System.out.println("Elements of original array: ");
7. for (int i = 0; i < arr.length; i++) {
8. System.out.print(arr[i] + " ");
9. }
10. //Sort the array in ascending order
11. for (int i = 0; i < arr.length; i++) {
12. for (int j = i+1; j < arr.length; 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. System.out.println();
22. //Displaying elements of array after sorting
23. System.out.println("Elements of array sorted in ascending order: ");

24. for (int i = 0; i < arr.length; i++) {


25. System.out.print(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
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//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 java.util.*;
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(System.in);
8. System.out.println("Enter a string/number to check if it is a palindro
me");
9. original = in.nextLine();
10. int length = original.length();
11. for ( int i = length - 1; i >= 0; i-- )
12. reverse = reverse + original.charAt(i);
13. if (original.equals(reverse))
14. System.out.println("Entered string/number is a palindrome.");
15. else
16. System.out.println("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
b.sorting names
// Java Program to Sort Names in an Alphabetical Order
import java.io.*;

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


System.out.println(
"The names in alphabetical order are: ");
for (int i = 0; i < n; i++) {
System.out.println(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){
System.out.println("Arguments: " + a);
}
private static void display(int a, int b){
System.out.println("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. System.out.println("this a default constructor");
8. }
9.
10.Student(int i, String n){
11.id = i;
12.name = n;
13.}
14.
15.public static void main(String[] args) {
16.//object creation
17.Student s = new Student();
18.System.out.println("\nDefault Constructor values: \n");
19.System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21.System.out.println("\nParameterized Constructor values: \n");
22.Student student = new Student(10, "David");
23.System.out.println("Student Id : "+student.id + "\nStudent Name : "+stu
dent.name);
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(){System.out.println("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(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16.}

Output:

17.Bike 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 java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(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 ( )
{
System.out.println(“Implement meth1().”);
}
public void meth2()
{
System.out.println (“Implement meth2().”);
}
public void meth3()
{
System.out.println (“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() {
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();
}
}
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 java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter num1: ");
String num1 = scanner.next();
System.out.print("Enter num2: ");
String num2 = scanner.next();

try {
int result = Integer.parseInt(num1) / Integer.parseInt(num2);
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Both arguments must be integers");
} catch (ArithmeticException e) {
System.out.println("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 java.io.*;

import java.util.*;

class AboutFile{

public static void main(String[] args){

Scanner input = new Scanner(System.in);


System.out.print("Enter the name of the file:");

String file_name = input.nextLine();

File f = new File(file_name);

if(f.exists())

System.out.println("The file " +file_name+ " exists");

else

System.out.println("The file " +file_name+ " does not exist");

if(f.exists()){

if(f.canRead())

System.out.println("The file " +file_name+ " is readable");

else

System.out.println("The file " +file_name+ " is not readable");

if(f.canWrite())

System.out.println("The file " +file_name+ " is writeable");

else

System.out.println("The file " +file_name+ " is not writeable");

System.out.println("The file type is: "


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

System.out.println("The Length of the file:" +f.length());

Output:

You might also like