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

Java

The document provides details about the Java Programming Lab course conducted at Shri Jagdishprasad Jhabarmal Tibrewala University for the academic year 2023-2024. It includes the name of the faculty, student details, list of exercises to be covered along with their schedule and a brief overview of the content covered in the first two exercises on arrays and object-oriented programming concepts like constructors, methods and parameter passing.

Uploaded by

FUN FACTZ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java

The document provides details about the Java Programming Lab course conducted at Shri Jagdishprasad Jhabarmal Tibrewala University for the academic year 2023-2024. It includes the name of the faculty, student details, list of exercises to be covered along with their schedule and a brief overview of the content covered in the first two exercises on arrays and object-oriented programming concepts like constructors, methods and parameter passing.

Uploaded by

FUN FACTZ
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

JAVA PROGRAMMING LAB

Department of Computer Science & Engineering


2023-2024

SHRI JAGDISHPRASAD JHABARMAL TIBREWALA UNIVERSITY


Vidya Nagari, Jhunjhunu-Churu Road, Village-Chudela, Dist.-Jhunjhunu, Rajasthan-
333001
Conducted by-Shri Rajasthani Seva Sangh (Mumbai)

Faculty Name:
Arti Panwar Student Name: Piyush Saini
Roll No.: 21BC8003
Course: BCA
Semester: V
Batch: 2023-2024
INDEX
S. Name of the Exercise Date Signatu Remark
N. re & s
Date
1 Simple java standalone programs, arrays 12-7-23

2 Constructors, methods, parameter passing 16-7-23

3 Overloading methods and constructors, 14-8-23


recursion, garbage collection,
4 Inheritance – Inheritance hierarchies super 16-8-3
and sub classes, Member access rules
5 Super keyword, preventing inheritance: 6-9-23
final classes and methods, the Object class,
and its methods.
6 Polymorphism – dynamic binding, method 20-9-23
overriding,
7 Packages- Defining, creating, and accessing a 2—10-23
package,
8 Exception handling- Dealing with errors 10-10-23

9 Usage of try, catch, throw 12-11-23

10 Creating threads, interrupting threads, 15-11-23


thread priorities, synchronizing threads
1.Simple java standalone programs, arrays
1.1Print Array Elements:
public class PrintArrayElements {
public static void main (String [] args) {
int [] numbers = {1, 2, 3, 4, 5};
// Print array elements
for (int i = 0; i < numbers. Length; i++) {
System.out.println(numbers[i]);
}
}
}
Output

1.2. Sum of Array Elements:


public class SumOfArrayElements {
public static void main (String [] args) {
int [] numbers = {1, 2, 3, 4, 5};
int sum = 0;
// Calculate the sum of array elements
for (int i = 0; i < numbers. Length; i++) {
sum += numbers[i];
}
System.out.println("Sum of array elements: " + sum);
}

1.3 Find Maximum Element in an Array:

public class FindMaxElement {


public static void main (String [] args) {
int [] numbers = {23, 45, 12, 67, 89, 34};
int max = numbers [0];
// Find the maximum element in the array
for (int i = 1; i < numbers. Length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum element in the array: " + max);
}
}

1.4 Copy One Array to Another:


public class Copy Array {
public static void main (String [] args) {
int [] source Array = {1, 2, 3, 4, 5};
int [] destination Array = new int [sourceArray.length];
// Copy elements from source Array to destination Array
for (int i = 0; i < sourceArray.length; i++) {
destination Array[i] = source Array[i];
}
// Print the copied array
for (int i = 0; i < destinationArray.length; i++) {
System.out.println(destination Array[i]);
}
}
}

2.Constructors, methods, parameter passing.


Ans public class Person {
// Instance variables
private String name;
private int age;

// Constructor with parameters


public Person (String name, int age) {
this.name = name;
this. Age = age;
}
// Getter method for name
public String get Name () {
return name;
}

// Setter method for name


public void set Name (String name) {
this.name = name;
}

// Getter method for age


public int getAge () {
return age;
}

// Setter method for age


public void setAge (int age) {
this.age = age;
}

// Method to display information about the person


public void display Info () {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main (String [] args) {


// Create a Person object using the constructor
Person person1 = new Person ("Alice", 25);

// Call the display Info method to display person1's information


System.out.println("Person 1:");
person1.displayInfo();

// Use setter methods to update person1's information


person1.setName("Bob");
person1.setAge(30);

// Call the display Info method again to display updated information


System.out.println("\updated Person 1:");
person1.displayInfo();
}
}

OUTPUT

3.Overloading methods and constructors, recursion, garbage collection

1. Method Overloading:
Code:
public class Calculator {
public int add (int a, int b) {
return a + b;
}

public double adds (double a, double b) {


return a + b;
}

public String add (String a, String b) {


return a. concat(b);
}

public static void main (String [] args) {


Calculator calc = new Calculator ();
System.out.println("Sum of integers: " + calc.add (5, 3));
System.out.println("Sum of doubles: " + calc.add (2.5, 3.7));
System.out.println("Concatenation of strings: " + calc.add ("Hello, ",
"world!"));
}
}

OUTPUT:

2. Constructor Overloading:
public class Student {
private String name;
private int age;

public Student () {
name = "Unknown";
age = 0;
}

public Student (String name) {


this.name = name;
age = 0;
}

public Student (String name, int age) {


this.name = name;
this.age = age;
}

public void display Info () {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main (String [] args) {


Student student1 = new Student ();
Student student2 = new Student("Alice");
Student student3 = new Student ("Bob", 25);

student1.displayInfo();
student2.displayInfo();
student3.displayInfo();
}
}

OUTPUT:
3. Recursion:
public class Factorial {
public static int calculate Factorial (int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculate Factorial (n - 1);
}
}

public static void main (String [] args) {


int number = 5;
int factorial = calculate Factorial(number);
System.out.println("Factorial of " + number + " is " + factorial);
}
}

OUTPUT:

4. inheritance – Inheritance hierarchies super and sub classes,


Member access rules give output for the same

Program Code:
// Superclass
class Animal {
String name;

Animal (String name) {


this.name = name;
}

void eat () {
System.out.println(name + " is eating.");
}
}

// Subclass 1
class Dog extends Animal {
Dog (String name) {
super(name);
}

void bark () {
System.out.println(name + " is barking.");
}
}

// Subclass 2
class Cat extends Animal {
Cat (String name) {
super(name);
}

void meow () {
System.out.println(name + " is meowing.");
}
}

public class Inheritance Example {


public static void main (String [] args) {
Dog dog = new Dog("Buddy");
Cat cat = new Cat("Whiskers");

dog.eat ();
dog.bark();

cat.eat();
cat.meow();
}
}

OUTPUT:

5. Super keyword, preventing inheritance: final classes and methods,


the Object class, and its methods. give output for the same.
Program Code:
1. Using the super Keyword:
class Parent {
int number;

Parent(int number) {
this.number = number;
}

void display() {
System.out.println("Number from Parent: " + number);
}
}

class Child extends Parent {


Child(int number) {
super(number);
}

@Override
void display() {
super.display(); // Calls the display method of the superclass
System.out.println("Number from Child: " + number);
}
}

public class SuperKeywordExample {


public static void main(String[] args) {
Child child = new Child(10);
child. Display();
}
}
OUTPUT:

2. Preventing Inheritance with final Classes and Methods:


final class FinalClass {
// Some code here
}

class Subclass /*extends FinalClass*/ { // Uncommenting this line


will result in a compilation error.
// Some code here
}

class Parent {
final void finalMethod() {
// Some code here
}
}

class Child extends Parent {


/*@Override
void finalMethod() { // Uncommenting this line will result in a
compilation error.
// Some code here
}*/
}

public class FinalExample {


public static void main(String[] args) {
// Some code here
}
}

3. The Object Class and Its Methods:


class MyClass {
String data;

MyClass(String data) {
this.data = data;
}

@Override
public String toString() {
return "MyClass[data=" + data + "]";
}
}

public class ObjectClassExample {


public static void main(String[] args) {
MyClass obj1 = new MyClass("Hello");
MyClass obj2 = new MyClass("World");

System.out.println(obj1.toString());
System.out.println(obj2.toString());

System.out.println(obj1.equals(obj2)); // Default behavior


(compares references)
}
}

OUTPUT:

6. Polymorphism – dynamic binding, method overriding give output


for the same.
Program Code:
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Woof!");
}
}

class Cat extends Animal {


@Override
void makeSound() {
System.out.println("Meow!");
}
}
public class PolymorphismExample {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.makeSound(); // Calls Dog's makeSound method


animal2.makeSound(); // Calls Cat's makeSound method
}
}
OUTPUT:

7.Packages- Defining, creating, and accessing a package, give


output for the same.
In Java, packages are used to organize and manage classes and provide
a namespace for them.
Step 1: Defining a Package
You define a package by including a package statement at the
beginning of your Java source file. For example, let us create a package
called comma:
Step 2: Creating a Package
To create a package structure on your file system, you need to organize
your source files in a directory hierarchy that matches the package
structure. In this case, create a directory named com in the same
directory as your Java source file and then create a subdirectory
myapp within com. Place your MyClass.java file inside the myapp
directory.
Your directory structure should look like this:

Step 3: Accessing a Package


Now, let us create another Java class that accesses the MyClass class
from the com.myapp package:

Step 4: Compile and Run


Compile both MyClass.java and AnotherClass.java. Make sure you
are in the directory containing the com directory and use the -d option
to specify the output directory for the compiled .class files:
This will generate a directory structure that matches the package
structure:

you can run the AnotherClass program:

OUPUT

8Exception handling- Dealing with errors give output for the same

Exception handling is a crucial part of Java programming that allows


you to gracefully handle errors and unexpected situations. Here is an
example that demonstrates exception handling, along with expected
outputs for different scenarios:
Program Code:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Scenario 1: Arithmetic Exception (Division by Zero)
int result = 5 / 0;
System.out.println("Result: " + result); // This line will not be
reached
} catch (Arithmetic Exception e) {
System.err.println("Arithmetic Exception: " + e.getMessage());
}

try {
// Scenario 2: Array Index Out of Bounds Exception
int[] numbers = {1, 2, 3};
int value = numbers[4];
System.out.println("Value: " + value); // This line will not be
reached
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("ArrayIndexOutOfBoundsException: " +
e.getMessage());
}

// Scenario 3: Unchecked Exception (NumberFormatException)


try {
String str = "abc";
int num = Integer.parseInt(str);
System.out.println("Number: " + num); // This line will not be
reached
} catch (NumberFormatException e) {
System.err.println("NumberFormatException: " +
e.getMessage());
}

// Scenario 4: Handling multiple exceptions


try {
int result = 10 / 0; // ArithmeticException
String str = null;
System.out.println(str.length()); // NullPointerException
} catch (ArithmeticException e) {
System.err.println("ArithmeticException: " + e.getMessage());
} catch (NullPointerException e) {
System.err.println("NullPointerException: " + e.getMessage());
} catch (Exception e) {
System.err.println("Generic Exception: " + e.getMessage());
} finally {
System.out.println("Finally block always executes.");
}
}
}

Output:
p

9 Usage of try, catch, throw give output for the same


Certainly! In Java, you can use the try, catch, and throw keywords to
handle exceptions. Here is an example that demonstrates their usage,
along with expected output for different scenarios:
Program Code
public class TryCatchThrowExample {
public static void main(String[] args) {
try {
// Scenario 1: Attempt to divide by zero
int result = divide(10, 0);
System.out.println("Result: " + result); // This line will not be
reached
} catch (ArithmeticException e) {
System.err.println("ArithmeticException: " + e.getMessage());
}

try {
// Scenario 2: Attempt to access a null reference
String str = null;
int length = getStringLength(str);
System.out.println("String Length: " + length); // This line will
not be reached
} catch (NullPointerException e) {
System.err.println("NullPointerException: " + e.getMessage());
}

try {
// Scenario 3: Custom exception handling
int number = -5;
if (number < 0) {
throw new IllegalArgumentException("Number cannot be
negative.");
}
} catch (IllegalArgumentException e) {
System.err.println("IllegalArgumentException: " +
e.getMessage());
}
}

public static int divide(int a, int b) {


if (b == 0) {
throw new ArithmeticException("Division by zero is not
allowed.");
}
return a / b;
}

public static int getStringLength(String str) {


if (str == null) {
throw new NullPointerException("Input string is null.");
}
return str.length();
}
}

Output:

10.Creating threads, interrupting threads, thread priorities,


synchronizing threads give output for the same.

Program Code:
class MyThread extends Thread {
private int count;

public MyThread(int count) {


this.count = count;
}

public void run() {


for (int i = 0; i < count; i++) {
System.out.println("Thread " + Thread.currentThread().getId()
+ ": Count = " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
// Creating threads
MyThread thread1 = new MyThread(5);
MyThread thread2 = new MyThread(5);

// Setting thread priorities


thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);

// Starting threads
thread1.start();
thread2.start();

// Interrupting a thread
thread1.interrupt();
try {
// Waiting for threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.err.println("Main thread interrupted");
}

System.out.println("Main thread finished.");


}
}

You might also like