0% found this document useful (0 votes)
18 views25 pages

Document From Chhaya Shah

The document contains multiple Java programs demonstrating various concepts such as class definitions, constructors, method overloading, inheritance, nested classes, and the use of collections like arrays and vectors. Each program includes code snippets along with expected outputs, showcasing practical applications of Java programming principles. The programs cover a range of topics from basic class structure to more advanced features like multilevel inheritance and wrapper classes.

Uploaded by

chhayashah2207
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)
18 views25 pages

Document From Chhaya Shah

The document contains multiple Java programs demonstrating various concepts such as class definitions, constructors, method overloading, inheritance, nested classes, and the use of collections like arrays and vectors. Each program includes code snippets along with expected outputs, showcasing practical applications of Java programming principles. The programs cover a range of topics from basic class structure to more advanced features like multilevel inheritance and wrapper classes.

Uploaded by

chhayashah2207
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
You are on page 1/ 25

PROGRAM 1

Write Java Program to define a class, describe its constructor, overload the constructors and
instantiate its object.

import java.lang.*;
class student {
String name;
int reg_no;
int marks1, marks2, marks3;

// Null constructor
student() {
name = "Raju";
reg_no = 123456;
marks1 = 34;
marks2 = 46;
marks3 = 85;
}

// Parameterized constructor
student (String n, int r, int m1, int m2, int m3) {
name = n;
reg_no = r;
marks1 = m1;
marks2 = m2;
marks3 = m3;
}

// Copy constructor
student (student s) {
name = s.name;
reg_no = s.reg_no;
marks1 = s.marks1;
marks2 = s.marks2;
marks3 = s.marks3;
}

void display() {
System.out.println(name + "\t" + reg_no + "\t" + marks1 + "\t" + marks2 + "\t" + marks3);
}
}

public class Constructors {

21-B-CSE-029 1
public static void main(String[] args) {
student s1 = new student();
student s2 = new student("john", 253345, 45, 46, 87);
student s3 = new student(s1);

s1.display();
s2.display();
s3.display();
}
}

OUTPUT

Raju 123456 34 46 85
john 253345 45 46 87
Raju 123456 34 46 85

21-B-CSE-029 2
PROGRAM 2
Write a Java Program to define a class, define instance, methods for setting and Retrieving
values of instance variable and instantiate its object.
class emp {
String name;
int id;
String address;

void getData (String name, int id, String address){


this.name = name;
this.id = id;
this.address = address;
}

void putData () {
System.out.println("Employee details are: ");
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Address: " + address);
}
}

public class ClassInstance {


public static void main(String[] args) {
emp e = new emp();
e.getData("Smith", 5234, "Gulbarga");
e.putData();
}
}

OUTPUT

Employee details are:


Name: Smith
ID: 5234
Address: Gulbarga

21-B-CSE-029 3
PROGRAM 3
Write a Java Program to define a class, define instance, methods and overload them for
dynamic method invocation.
class add {
void display(int a, int b) {
int c = a + b;
System.out.println("The sum of " + a + " & " + b + " is " + c);
}

void display (double a, double b) {


double c = a + b;
System.out.println("The sum of " + a + " & " + b + " is " + c);
}
}

public class InstanceMethodOverload {


public static void main(String[] args) {
add obj = new add();
obj.display(12,43);
obj.display(18.4, 34.6);
}
}

OUTPUT

The sum of 12 & 43 is 55


The sum of 18.4 & 34.6 is 53.0

21-B-CSE-029 4
PROGRAM 4
Write a Java Program to demonstrate use of sub class.
class parent {
int m;

void get_m(int m) {
this.m = m;
}

void display_m() {
System.out.println("This is from parent: m = " + m);
}
}

class child extends parent {


int n;

void get_n(int n) {
this.n = n;
}

void display_n(){
System.out.println("This is from child: n = " + n);
}
}

public class SubClasses {


public static void main(String[] args) {
child c = new child();
c.get_m(19);
c.get_n(25);
c.display_m();
c.display_n();
}
}

OUTPUT

This is from parent: m = 19


This is from child: n = 25

21-B-CSE-029 5
PROGRAM 5
Write a Java Program to demonstrate use of nested class.
class outer {
int m = 10;

class inner {
int n = 20;

void display () {
System.out.println("m = " + m);
System.out.println("n = " + n);
}
}
}

public class NestedClass {


public static void main(String[] args) {
outer outObj = new outer();
outer.inner inObj = outObj.new inner();
inObj.display();
}
}

OUTPUT

m = 10
n = 20

21-B-CSE-029 6
PROGRAM 6
Write a Java Program to implement array of objects.
public class ArrayOfObject {
public static void main(String[] args) {
Employee[] staff = new Employee[3];

staff[0] = new Employee("Harry", 3424);


staff[1] = new Employee("Vishal", 87966);
staff[2] = new Employee("Karan", 16565);

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


staff[i].print();
}
}
}

class Employee {
private String name;
private double salary;

public Employee(String n, double s) {


name = n;
salary = s;
}

public void print() {


System.out.println(name + " " + salary);
}
}

OUTPUT

Harry 3424.0
Vishal 87966.0
Karan 16565.0

21-B-CSE-029 7
PROGRAM 7(A)
Write a java program to practice using string, class and its methods.
import java.lang.String;
public class StringAndClass {
public static void main(String[] args) {
String s1 = new String("gptgulbarga");
String s2 = "GPT GULBARGA";

System.out.println("The string s1 is : " + s1);


System.out.println("The string s2 is : " + s2);

System.out.println("Length of the string s1 is: " + s1.length());

System.out.println("The first occurrence of 'r' is at the position: " + s1.indexOf('r'));

System.out.println("The String in Upper Case: " + s1.toUpperCase());

System.out.println("The String in Lower Case: " + s1.toLowerCase());

System.out.println("s1 equals to s2: " + s1.equals(s2));

System.out.println("s1 equals ignore case to s2: " + s1.equalsIgnoreCase(s2));

int result = s1.compareTo(s2);


System.out.println("After compareTo(): ");
if (result == 0) {
System.out.println(s1 + " is equal to " + s2);
} else if (result > 0) {
System.out.println(s1 + " is greater than " + s2);
} else {
System.out.println(s1 + " is smaller than " + s2);
}

System.out.println("Character at an index of 6 in s1 is: " + s1.charAt(6));

String s3 = s1.substring(3, 11);


System.out.println("Extracted substring is: " + s3);

System.out.println("After replacing 'g' with 'a' in s1: " + s1.replace('g', 'a'));

String s4 = " This is a book ";


System.out.println("The string s4 is: " + s4);
System.out.println("After trim(): " + s4.trim());

21-B-CSE-029 8
}
}

OUTPUT

The string s1 is : gptgulbarga


The string s2 is : GPT GULBARGA
Length of the string s1 is: 11
The first occurrence of 'r' is at the position: 8
The String in Upper Case: GPTGULBARGA
The String in Lower Case: gptgulbarga
s1 equals to s2: false
s1 equals ignore case to s2: false
After compareTo():
gptgulbarga is greater than GPT GULBARGA
Character at an index of 6 in s1 is: b
Extracted substring is: gulbarga
After replacing 'g' with 'a' in s1: aptaulbaraa
The string s4 is: This is a book
After trim(): This is a book

21-B-CSE-029 9
PROGRAM 7(B)
Write a java program to practice stringbuffer class and its methods.
public class StringBufferClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("This is my college");

System.out.println("The string sb is: " + sb);


System.out.println("The length of the string sb is: " + sb.length());
System.out.println("The capacity of the string sb is: " + sb.capacity());
System.out.println("The character at index 6 is: " + sb.charAt(6));

sb.setCharAt(3, 'x');
System.out.println("After setting char 'x' at position 3: " + sb);
System.out.println("After appending: " + sb.append("ingulbarga"));
System.out.println("After inserting 'gpt ': " + sb.insert(19, "gpt "));
System.out.println("After deleting characters from index 19 to 22: " + sb.delete(19, 22));
}
}

OUTPUT

The string sb is: This is my college


The length of the string sb is: 18
The capacity of the string sb is: 34
The character at index 6 is: s
After setting char 'x' at position 3: Thix is my college
After appending: Thix is my collegeingulbarga
After inserting 'gpt ': Thix is my collegeigpt ngulbarga
After deleting characters from index 19 to 22: Thix is my collegei ngulbarga

21-B-CSE-029 10
PROGRAM 8
Write a java program to implement vector class and its methods.
import java.util.Vector;
import java.util.Enumeration;

public class VectorMethods {


public static void main(String[] args) {
Vector<String> v = new Vector<>();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("zero", 0);
v.insertElementAt("oops", 3);
v.insertElementAt("four", 5);

System.out.println("Vector Size: " + v.size());


System.out.println("Vector Capacity: " + v.capacity());

System.out.println("The elements of the vector are:");


Enumeration<String> e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}

System.out.println("The first element is: " + v.firstElement());


System.out.println("The last element is: " + v.lastElement());
System.out.println("The object 'oops' is found at position: " + v.indexOf("oops"));

v.removeElement("oops");
v.removeElementAt(1);

System.out.println("After removing 2 elements");


System.out.println("Vector Size: " + v.size());
System.out.println("The elements of the vector are:");
for (int i = 0; i < v.size(); i++) {
System.out.println(v.elementAt(i));
}
}
}

21-B-CSE-029 11
OUTPUT

Vector Size: 6
Vector Capacity: 10
The elements of the vector are:
zero
one
two
oops
three
four
The first element is: zero
The last element is: four
The object 'oops' is found at position: 3
After removing 2 elements
Vector Size: 4
The elements of the vector are:
zero
two
three
four

21-B-CSE-029 12
PROGRAM 9
write a java program to implement wrapper classes and their methods.
import java.io.*;
import java.lang.Float;

public class WrapperClasses {


public static void main(String args[]) {
Float P = 0f;
Float I = 0f;
int y = 0;

try {
DataInputStream ds = new DataInputStream(System.in);
System.out.println("ENTER THE PRINCIPAL AMOUNT");
System.out.flush();
String sp = ds.readLine();
P = Float.valueOf(sp);

System.out.println("ENTER THE INTEREST RATE");


System.out.flush();
String SI = ds.readLine();
I = Float.valueOf(SI);

System.out.println("ENTER THE NUMBER OF YEARS");


System.out.flush();
String sy = ds.readLine();
y = Integer.parseInt(sy);
} catch (Exception e) {
System.out.println("INPUT OUTPUT ERROR");
System.exit(1);
}

float value = loan(P.floatValue(), I.floatValue(), y);


System.out.println("FINAL VALUE IS: " + value);
}

static float loan(float P, float I, int y) {


int year = 1;
float sum = P;
while (year <= y) {
sum = sum + (P * I) / 100;
year++;
}

21-B-CSE-029 13
return sum;
}
}

OUTPUT

ENTER THE PRINCIPAL AMOUNT


1000
ENTER THE INTEREST RATE
2
ENTER THE NUMBER OF YEARS
1
FINAL VALUE IS: 1020.0

21-B-CSE-029 14
PROGRAM 10
Write a java program to implement inheritance and demonstrate use of method overriding.
class A {
void display() {
System.out.println("This is from class A");
}
}

class B extends A {
void display() {
System.out.println("This is from class B");
}
}

public class InheritanceClass {

public static void main(String arg[]) {


B obj = new B();
obj.display();
}

OUTPUT

This is from class B

15
21-B-CSE-029
PROGRAM 11
Write a java program to implement multilevel inheritance by applying various access controls
to its data members and methods.
import java.io.DataInputStream;
class Student {
private int rollno;
private String name;
DataInputStream dis = new DataInputStream(System.in);

public void getrollno() {


try {
System.out.println("Enter rollno: ");
rollno = Integer.parseInt(dis.readLine());
System.out.println("Enter name: ");
name = dis.readLine();
} catch (Exception e) {}
}

void putrollno() {
System.out.println("Roll No = " + rollno);
System.out.println("Name = " + name);
}
}

class Marks extends Student {


protected int m1, m2, m3;

void getmarks() {
try {
System.out.println("Enter marks:");
m1 = Integer.parseInt(dis.readLine());
m2 = Integer.parseInt(dis.readLine());
m3 = Integer.parseInt(dis.readLine());
} catch (Exception e) {}
}

void putmarks() {
System.out.println("m1 = " + m1);
System.out.println("m2 = " + m2);
System.out.println("m3 = " + m3);
}
}

21-B-CSE-029 16
class Result extends Marks {
private float total;

void compute_display() {
total = m1 + m2 + m3;
System.out.println("Total marks: " + total);
}
}

public class MultilevelInheritance {


public static void main(String arg[]) {
Result r = new Result();
r.getrollno();
r.getmarks();
r.putrollno();
r.putmarks();
r.compute_display();
}

OUTPUT

Enter rollno:
246
Enter name:
Vishal
Enter marks:
45
65
31
Roll No = 246
Name = Vishal
m1 = 45
m2 = 65
m3 = 31
Total marks: 141.0

21-B-CSE-029 17
PROGRAM 12(A)
Write a program to demonstrate use of implementing interfaces.
import java.lang.*;
interface Area {
final static float pi = 3.14F;
float compute(float x, float y);
}

class Rectangle implements Area {


public float compute(float x, float y) {
return (x * y);
}
}

class Circle implements Area {


public float compute(float x, float y) {
return (pi * x * x);
}
}

public class ImplementInterfaces {


public static void main(String a[]) {
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area A;

A = rect;
System.out.println("Area of rectangle = " + A.compute(10, 20));

A = cir;
System.out.println("Area of circle = " + A.compute(30, 0));
}
}

OUTPUT

Area of rectangle = 200.0


Area of circle = 2826.0002

21-B-CSE-029 18
PROGRAM 12(B)
Write a program to demonstrate use of extending interfaces.
import java.lang.*;
interface Area {
final static float pi = 3.14F;
float compute(float x, float y);
}

class Rectangle implements Area {


public float compute(float x, float y) {
return (x * y);
}
}

class Circle implements Area {


public float compute(float x, float y) {
return (pi * x * x);
}
}

public class ImplementInterfaces {


public static void main(String a[]) {
Rectangle_1 rect = new Rectangle_1();
Circle cir = new Circle();
Area A;

A = (Area) rect;
System.out.println("Area of rectangle = " + A.compute(10, 20));

A = cir;
System.out.println("Area of circle = " + A.compute(30, 0));
}
}

OUTPUT

The Area is: 125.46

21-B-CSE-029 19
PROGRAM 13
Write a Java program to implement the concept of importing classes from user defined
package and creating packages.
// creating package for importing class
package p1;
public class Student {
int regno;
String name;

public void getdata(int r, String s) {


regno = r;
name = s;
}

public void putdata() {


System.out.println("Regno = " + regno);
System.out.println("Name = " + name);
}
}
// class that import class from package
// File path: C:\jdk1.6.0_26\bin\StudentTest.java
import p1.Student;

class StudentTest {
public static void main(String[] args) {
Student s = new Student();
s.getdata(123, "xyz");
s.putdata();
}
}

OUTPUT

Regno = 123
Name = xyz

21-B-CSE-029 20
PROGRAM 14(A)
Write a program to implement the concept of threading by extending Thread Class.
import java.lang.Thread;
class A_1 extends Thread {
public void run() {
System.out.println("Thread A_1 is started:");
for (int i = 1; i <= 5; i++) {
System.out.println("\tFrom Thread A_1: i = " + i);
}
System.out.println("Exit from Thread A_1:");
}
}

class B_1 extends Thread {


public void run() {
System.out.println("Thread B_1 is started:");
for (int j = 1; j <= 5; j++) {
System.out.println("\tFrom Thread B_1: j = " + j);
}
System.out.println("Exit from Thread B_1:");
}
}

class C extends Thread {


public void run() {
System.out.println("Thread C is started:");
for (int k = 1; k <= 5; k++) {
System.out.println("\tFrom Thread C: k = " + k);
}
System.out.println("Exit from Thread C:");
}
}

public class ExtendingThreadClass {


public static void main(String[] args) {
new A_1().start();
new B_1().start();
new C().start();
}
}

21-B-CSE-029 21
OUTPUT

Thread A_1 is started:


Thread B_1 is started:
Thread C is started:
From Thread C: k = 1
From Thread C: k = 2
From Thread C: k = 3
From Thread C: k = 4
From Thread B_1: j = 1
From Thread B_1: j = 2
From Thread B_1: j = 3
From Thread C: k = 5
Exit from Thread C:
From Thread B_1: j = 4
From Thread A_1: i = 1
From Thread B_1: j = 5
From Thread A_1: i = 2
From Thread A_1: i = 3
Exit from Thread B_1:
From Thread A_1: i = 4
From Thread A_1: i = 5
Exit from Thread A_1:

21-B-CSE-029 22
PROGRAM 14(B)
Write a program to implement the concept of threading by implementing Runnable Interface.
import java.lang.Runnable;
class X implements Runnable {
public void run() {
for (int i = 1; i < 10; i++) {
System.out.println("\tThread X: " + i);
}
System.out.println("End of Thread X");
}
}

public class RunnableInterface {


public static void main(String arg[]) {
X r = new X();
Thread t = new Thread(r);
t.start();
}
}
OUTPUT

Thread X: 1
Thread X: 2
Thread X: 3
Thread X: 4
Thread X: 5
Thread X: 6
Thread X: 7
Thread X: 8
Thread X: 9
End of Thread X

21-B-CSE-029 23
PROGRAM 15(A)
Write a program to implement the concept of Exception Handling using predefined
exception.
import java.lang.*;
class ExceptionHandle {
public static void main(String argv[]) {
int a = 10, b = 5, c = 5, x, y;

try {
x = a / (b - c);
} catch (ArithmeticException e) {
System.out.println("DIVISION BY ZERO");
}

y = a / (b + c);
System.out.println("y = " + y);
}
}

OUTPUT

DIVISION BY ZERO
y=1

21-B-CSE-029 24
PROGRAM 15(B)
Write a program to implement the concept of Exception Handling by creating user defined
exceptions.
import java.io.DataInputStream;
import java.lang.Exception;

class MyException extends Exception {


MyException(String message) {
super(message);
}
}

class UserDefinedException {
public static void main(String a[]) {
int age;
DataInputStream ds = new DataInputStream(System.in);
try {
System.out.println("Enter the age (above 15 and below 25):");
age = Integer.parseInt(ds.readLine());
if (age < 15 || age > 25) {
throw new MyException("Age not in range");
}
System.out.println("The age is: " + age);
} catch (MyException e) {
System.out.println("Caught MyException");
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e);
}
}
}

OUTPUT

Enter the age (above 15 and below 25):


5
Caught MyException
Age not in range

21-B-CSE-029 25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy