0% found this document useful (0 votes)
11 views31 pages

Java Practical File

The document outlines a series of Java programming experiments focusing on command line arguments, arrays, object-oriented programming concepts, and inheritance. It includes objectives, required apparatus, theoretical explanations, and source code examples for various programs such as checking for prime numbers, palindromes, and implementing classes with encapsulation. Each section concludes with execution formats and outputs for the provided code examples.

Uploaded by

singhisha4554
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)
11 views31 pages

Java Practical File

The document outlines a series of Java programming experiments focusing on command line arguments, arrays, object-oriented programming concepts, and inheritance. It includes objectives, required apparatus, theoretical explanations, and source code examples for various programs such as checking for prime numbers, palindromes, and implementing classes with encapsulation. Each section concludes with execution formats and outputs for the provided code examples.

Uploaded by

singhisha4554
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

2400970100093 ISHITA SINGH

EXPERIMENT – 1
Objec ve: - Create simple java programs using command line arguments.
Apparatus Required: - Computer/Laptop, Java Development Kit(JDK),
Command Prompt / Terminal, Opera ng System (Window/Linux/macOS)
Theory: - Command line arguments are values passed to a Java program at the
me of execu on through the command prompt. These arguments are received
in the String[] args parameter of the main() method. Each argument is stored as
an element of the args array (e.g., args[0], args[1]). They allow users to provide
input to a program without using interac ve input methods.
Syntax of main method with command line arguments:
public sta c void main (String[] args)
• args is an array of strings.
• Arguments are accessed using index values like args[0], args[1], etc.
• These arguments are always treated as strings and must be converted if
numerical opera ons are required.
Execu on format:
To Compile: javac fi[Link]
To Run: java ClassName arg1 arg2 arg3
2400970100093 ISHITA SINGH
1A) WAP that takes input from user through command line argument
and then prints whether a number is prime or not.
SOURCE CODE: -
public class Exp_1a {
public sta c void main(String []args){
int num = [Link](args[0]);
boolean isPrime = true;

if(num<=1)
[Link]("Neither Prime Nor Composite");

for(int i=2;i*i<=num;i++){
if(num%i==0){
isPrime = false;
break;
}
}
if( isPrime )
[Link](num+" is a Prime Number");
else
[Link](num+" is not a Prime Number");
}
}

OUTPUT: -
2400970100093 ISHITA SINGH
1B) Write a program to enter number through command line and check
whether it is palindrome or not.
SOURCE CODE: -
public class Exp_1b {
public sta c void main(String []args) {
int num = [Link](args[0]);
int rev = 0 , copy = num;
while(copy>0) {
rev = rev * 10 + copy % 10;
copy /= 10;
}
if(rev == num)
[Link](num+" is a Palindrome Number");
else
[Link](num+" is not a Palindrome Number");
}
}
OUTPUT: -
2400970100093 ISHITA SINGH
EXPERIMENT – 2
OBJECTIVE: -Understand Array in Java
APPARATUS REQUIRED: -Computer / Laptop, Java Development Kit (JDK),
Command Prompt / Terminal, Operating System (Windows / Linux / macOS).
THEORY:
Array in Java
An array is a collection of elements of the same data type stored in contiguous
memory locations. It allows multiple values to be stored in a single variable. Each
element is accessed using an index, starting from 0.
Example:
int arr[] = {10, 20, 30, 40};
[Link](arr[0]); // Output: 10
Here, arr is an array that stores integer values, and elements are accessed using
their index.
Jagged Array in Java
A jagged array is a two-dimensional array where each row can have a different
number of columns. Unlike a regular 2D array, the size of rows is not fixed.
Example:
int arr[][] = new int[3][];
arr[0] = new int[2]; arr[1] = new int[3]; arr[2] = new int[1];

Two-Dimensional Array in Java


A two-dimensional (2-D) array is an array of arrays used to store data in the form
of rows and columns, similar to a matrix or table. It allows multiple values to be
stored in a structured format and each element is accessed using two indices:
row and column.
2400970100093 ISHITA SINGH
Example: -
int arr[][] = { {1, 2, 3}, {4, 5, 6} };
[Link](arr[0][1]); // Output: 2
Here, arr[0][1] represents the element in the first row and second column.

Execu on format:
To Compile: javac [Link]
To Run: java ClassName
2400970100093 ISHITA SINGH
2A) Write a program in java which creates the variable size array
(Jagged Array) and print all the values using loop statement.
SOURCE CODE: -
public class Exp_2a {
public sta c void main(String[] args) {
int[][] arr = new int[3][];

arr[0] = new int[2];


arr[1] = new int[4];
arr[2] = new int[3];

arr[0][0] = 7;
arr[0][1] = 14;

arr[1][0] = 98;
arr[1][1] = 100;
arr[1][2] = 144;
arr[1][3] = 18;

arr[2][0] = 70;
arr[2][1] = 80;
arr[2][2] = 90;
for(int i = 0; i < [Link]; i++) {
for(int j = 0; j < arr[i].length; j++) {
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}
OUTPUT: -
2400970100093 ISHITA SINGH
2B) Write a Java program to take user input and display the reverse of
a string.
SOURCE CODE: -
import [Link]; public class Exp_2b {
public static void main(String[] args) { Scanner sc = new Scanner([Link]);
[Link]("Enter a String : "); String str = [Link]();

String rev = "";


int n = [Link]();

for(int i=n-1;i>=0;i--) {
rev = rev + [Link](i);
}
[Link]("Reversed String : "+rev);
}
}

OUTPUT: -
2400970100093 ISHITA SINGH
2C) Write a program to print addi on of 2 matrices in java .
SOURCE CODE: -
public class Exp_2c {
public static void main(String[] args) {

int [][] arr1 = { {1,2,3,4} , {5,6,7,8} , {9,10,11,12} };


int [][] arr2 = { {100,101,102,103} , {104,105,106,107} , {108,109,110,111}
};

int rows = 3 , cols = 4;


int [][] arrSum = new int[rows][cols]; [Link]("Array After Sum ");
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
arrSum[i][j] = arr1[i][j] + arr2[i][j];
[Link](arrSum[i][j]+" ");
}
[Link]();
}
}
}

OUTPUT: -
2400970100093 ISHITA SINGH
EXPERIMENT – 3
OBJECTIVE: Understand OOP concepts and basics of Java programming
APPARATUS REQUIRED: Computer / Laptop, Java Development Kit (JDK),
Command Prompt / Terminal, Operating System (Windows / Linux / macOS).
THEORY:
Class in Java
A class is a blueprint or template used to create objects. It defines the variables
(attributes) and methods (functions) that describe the properties and behavior
of objects.
Example:
class Person { String name; int age;
}
Object in Java
An object is an instance of a class. It represents a real-world entity and
contains actual values for the attributes defined in the class.
Example:
Person p1 = new Person(); Person p2 = new Person();
Here p1 and p2 are objects of the Person class.

Constructor in Java
A constructor is a special method that is automatically called when an object of
a class is created. It is used to initialize the attributes of the object.

Example: -
Person(String n, int a) {name = n;
age = a;
}
The constructor assigns values to the name and age attributes when the object
is created.
Encapsula on in Java
Encapsulation is the process of wrapping data (variables) and methods together
in a single unit (class) and restricting direct access to the data. The data members
2400970100093 ISHITA SINGH
are declared private, and they can only be accessed or modified through public
getter and setter methods.
For example, in a Person class, the attributes name, age, and country can be
declared as private, and their values can be accessed or modified using getter
and setter methods.
private instance variables (name, age, country) → Data hiding
public ge er and se er methods → Controlled access to data

Execu on format:
To Compile: javac [Link]
To Run: java ClassName
2400970100093 ISHITA SINGH
3A) Write a Java program to create a class called "Person" with a name
and age a ribute. Create two instances of the "Person" class, set their
a ributes using the constructor, and print their name and age.
SOURCE CODE: -
class Person {
String
name;
int age;
Person(String name, int age) { [Link] = name;
[Link] = age;
}
void display() {
[Link]("Name: " + name + " Age: " + age);
}
}
public class Exp_3a {
public static void main(String[] args) {

Person p1 = new Person("Ishita", 21); Person p2 = new Person("Aditi", 25);

[Link]();
[Link]();
}
}

OUTPUT: -
2400970100093 ISHITA SINGH
3B) Write a Java program to create a class called Person with private
instance variables name, age. and country. Provide public ge er and
se er methods to access and modify these variables.
SOURCE CODE: -
class Person { private String name; private int age;
private String country;

// Setter methods
public void setName(String name) { [Link] = name;
}

public void setAge(int age) { [Link] = age;


}

public void setCountry(String country) { [Link] = country;


}

// Getter methods
public String getName() { return name;
}

public int getAge() { return age;


}

public String getCountry() { return country;


}
}

public class Exp_3b {

public static void main(String[] args) {

Person p1 = new Person();

[Link]("ishita"); [Link](21); [Link]("India");

[Link]("Name: " + [Link]()); [Link]("Age: " +


[Link]()); [Link]("Country: " + [Link]());
}
2400970100093 ISHITA SINGH
}

OUTPUT: -
2400970100093 ISHITA SINGH

EXPERIMENT – 4
OBJECTIVE: Create Java programs using inheritance and
polymorphism.
APPARATUS REQUIRED: Computer / Laptop, Java Development Kit (JDK),
Command Prompt / Terminal, Operating System (Windows / Linux / macOS).
THEORY:
Inheritance in Java
Inheritance is an important concept of Object-Oriented Programming in which
one class acquires the properties and methods of another class. The class whose
properties are inherited is called the parent class (superclass), and the class that
inherits those properties is called the child class (subclass).
Inheritance helps in code reusability, reducing redundancy, and creating a
hierarchical relationship between classes. It allows a programmer to use the
existing functionality of a class and extend it with new features.
Types of Inheritance in Java
1. Single Inheritance
In this type, one subclass inherits from only one superclass. Example: Dog
inherits from Animal.
2. Mul level Inheritance
In this type, a class inherits from another class, which itself inherits from
another class, forming a chain of inheritance.
Example: Animal → Dog → Puppy.
3. Hierarchical Inheritance
In this type, multiple subclasses inherit from the same superclass.
Example: Animal → Dog, Animal → Cat.
4. Mul ple Inheritance
In this type, one subclass inherits from more than one superclass.
Java does not support multiple inheritance with classes, but it can be
2400970100093 ISHITA SINGH
achieved using interfaces.
Polymorphism in Java
Polymorphism is an important concept of Object-Oriented Programming which
means “many forms.” It allows a method or object to perform different tasks
depending on the context. In Java, polymorphism enables the same method
name to be used for different implementations, improving code flexibility and
reusability.
Types of Polymorphism
1. Compile-Time Polymorphism (Method Overloading)
This type of polymorphism occurs when multiple methods have the same
name different parameters within the same class. The method to be
executed is decided at compile time.

2. Run-Time Polymorphism (Method Overriding)


This occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass. The method to be
executed is determined at runtime.

Execu on format:
To Compile: javac [Link]
To Run: java ClassName
2400970100093 ISHITA SINGH

4A) “Java does not support mul ple inheritance but we can achieve it
by interface”. Write a program to jus fy the above statement.
SOURCE CODE: -
// Interface 1 interface A {
void showA();
}
// Interface 2 interface B {
void showB();
}
// Child class implementing both interfaces class C implements A, B {
public void showA() { [Link]("Interface A method");
}

public void showB() { [Link]("Interface B method");


}
}
// Main class
public class Exp_4a {
public static void main(String[] args) { C obj = new C();
[Link]();
[Link]();
}
}

OUTPUT: -
2400970100093 ISHITA SINGH

4B) Write a program in java to implement the following types of


inheritance: • Single Inheritance • Mul level Inheritance
# SINGLE INHERITENCE
SOURCE CODE: -
class Parent {
void displayMessage1() {
[Link]("Hi from Parent");
}
}
class Child extends Parent {
void displayMessage2() {
[Link]("Hi from Child");
}
}
public class Exp_4b1 {
public sta c void main(String[] args) {
Parent ob = new Parent();
ob.displayMessage1(); // Parent class method
Child ob1 = new Child();
ob1.displayMessage2(); // Child class method
}
}
OUTPUT: -
2400970100093 ISHITA SINGH

# MULTILEVEL INHERITENCE
SOURCE CODE: -
// Parent class
class A {
void showA() {
[Link]("This is Class A");
}
}
// Child class (inherits A)
class B extends A {
void showB() {
[Link]("This is Class B");
}
}
// Grandchild class (inherits B)
class C extends B {
void showC() {
[Link]("This is Class C");
}
}
// Main class
public class Exp_4b2 {
public sta c void main(String[] args) {
C obj = new C();

[Link](); // From class A


[Link](); // From class B
[Link](); // From class C
}
}

OUTPUT: -
2400970100093 ISHITA SINGH

4C) Create a superclass Animal with a method makeSound(). Then,


create subclasses Dog and Cat that override the method.
SOURCE CODE: -
class Animal {
void makeSound() {
[Link]("Animals make sound");
}
}
class Dog extends Animal {
void makeSound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
void makeSound() {
[Link]("Cat meows");
}
}
public class Exp_4c {
public sta c void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
}
}
OUTPUT: -
2400970100093 ISHITA SINGH

4D) (d) Create a class Calculator that overloads a method add() to: •
Add two integers. • Add three int egers. • Add two double values.
SOURCE CODE: -
class Exp_4d {
int add(int a, int b) {
return (a + b);
}
int add(int a, int b, int c) {
return (a + b + c);
}
double add(double a, double b) {
return (a + b);
}
public sta c void main(String[] args) {
Exp_4d ob = new Exp_4d();
[Link]([Link](10, 20)); // int, int
[Link]([Link](10, 20, 30)); // int, int, int
[Link]([Link](10.5, 10.8)); // double, double
}
}
OUTPUT: -
2400970100093 ISHITA SINGH

EXPERIMENT – 5
OBJECTIVE: Implement error-handling techniques using exception handling
and multithreading.
APPARATUS REQUIRED: Computer / Laptop, Java Development Kit (JDK),
Command Prompt / Terminal, Operating System (Windows / Linux / macOS).
THEORY:
Excep on Handling in Java
Exception Handling is a mechanism used to handle runtime errors so that the
normal flow of the program is not interrupted. An exception is an event that
occurs during program execution which disrupts the normal flow of instructions.
Java provides several keywords for handling exceptions such as try, catch,
finally, throw, and throws. The try block contains code that may cause an
exception, the catch block handles the exception, and the finally block is used
to execute important code regardless of whether an exception occurs or not.
Exception handling helps in maintaining program stability and preventing
program crashes.
Threads and Mul threading in Java
A thread is a lightweight unit of execution within a program. It represents a
single sequence of instructions that can run independently as part of a larger
process.
Multithreading is the process of executing multiple threads simultaneously
within a single program. It allows a program to perform several tasks at the
same time, improving efficiency, performance, and better utilization of CPU
resources.
In Java, multithreading is commonly used for tasks such as running background
operations, handling multiple users, and performing parallel processing within
applications.
Execu on format:
To Compile: javac [Link]
To Run: java ClassName
2400970100093 ISHITA SINGH

5A) Write a Java program to implement user defined excep on


handling for nega ve amount entered.
SOURCE CODE: -
import java.u l.*;
// User defined excep on class
class Nega veNumberExcep on extends Arithme cExcep on{
Nega veNumberExcep on(String msg)
{
super(msg);
}
}
public class Exp_5a {
sta c void valideNumber(int num){ if(num<0)
throw new Nega veNumberExcep on("Nega ve number entered");
}
public sta c void main(String []args){
[Link]("Enter a number");
Scanner sc=new Scanner([Link]);
try{
int number=[Link]();
valideNumber(number);
[Link]("Number is valid");
}
catch(Nega veNumberExcep on e){
[Link]();
}
}
}
OUTPUT: -
2400970100093 ISHITA SINGH

5B) Write a program in java which creates two threads, “Even” thread
and “Odd” thread and print the even no using Even Thread a er every
two seconds and odd no using Odd Thread a er every five second.
SOURCE CODE: -
class ThreadODD extends Thread {
public void run() {
try {
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
[Link]("Thread1 " + i);
[Link](3000);
}
}
} catch (InterruptedExcep on e) {
[Link]();
}
}
}

class ThreadEVEN extends Thread {


public void run() {
try {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
[Link]("Thread2 " + i);
[Link](5000);
}
}
} catch (InterruptedExcep on e) {
[Link]();
}
}
}

public class Exp_5b {


public sta c void main(String[] args) {
ThreadODD ob1 = new ThreadODD();
ThreadEVEN ob2 = new ThreadEVEN();
[Link]();
[Link]();
2400970100093 ISHITA SINGH

}
}
OUTPUT: -
2400970100093 ISHITA SINGH

EXPERIMENT – 6
OBJECTIVE: Create simple java program to implement the concept of
Packages in Java.
APPARATUS REQUIRED: Computer / Laptop, Java Development Kit
(JDK), Command Prompt / Terminal, Operating System (Windows / Linux /
macOS).
THEORY :
A package in Java is a namespace that groups related classes and interfaces
together into a hierarchical structure. It is similar to a folder in a file system and is
used to organize large programs into smaller, manageable units.
Packages help in avoiding class name conflicts, as classes with the same name
can exist in different packages. They also provide access control by using access
modifiers such as public, protected, and default, ensuring proper security and
visibility of classes and members.
Java packages promote code reusability and modularity, making it easier to
maintain and update programs. They also simplify locating and using classes in
large projects.
There are two types of packages in Java:
 Built-in packages: Predefined packages like [Link], java.u l, and [Link]
that provide standard func onality.
 User-defined packages: Created by programmers using the package keyword
to organize their own classes.
Packages are created using the package keyword, and classes from a package are
accessed using the import keyword or by using their fully qualified names.
Thus, packages play a crucial role in organizing, securing, and managing Java
programs efficiently.

Execu on format:
To Compile: javac [Link]
To Run: java ClassName arg1 arg2 arg3
2400970100093 ISHITA SINGH

6 – A) Create a package named Mathema cs and add a class Matrix


with methods to perform addi on and subtrac on opera ons on two
2×2 matrices. Write a Java program that imports the Mathema cs
package and uses the Matrix class to perform these opera ons.
SOURCE CODE : -

[Link] (inside Mathema cs package)


package Mathematics; public class Matrix {
public int[ ][ ] add(int[ ][ ] a, int[ ][ ] b) {
int[ ][ ] result = new int[2][2];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
result[ i ][j ] = a[i ][j ] + b[i ][j];
}
}
return result;
}
public int[ ][ ] subtract(int[ ][ ] a, int[ ][ ] b) {
int[ ][ ] result = new int[2][2];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
result[i][j] = a[i][j] - b[i][j];
}
}
return result;
}
}

[Link]
import [Link];
public class Main {
public static void main(String[] args) {
int[ ][ ] a = {{1, 2}, {3, 4}};
int[ ][ ] b = {{5, 6}, {7, 8}};
Matrix m = new Matrix();
2400970100093 ISHITA SINGH

int[ ][ ] sum = [Link](a, b);


int[ ][ ] diff = [Link](a, b);
[Link]("Addition:");
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
[Link](sum[i][j] + " ");
}
[Link]();
}
[Link]("Subtraction:");
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
[Link](diff[i][j] + " ");
}
[Link]();
}
}
OUTPUT: -
2400970100093 ISHITA SINGH

EXPERIMENT – 7
OBJECTIVE: Create simple java programs to show different Input-Output
Methods.
APPARATUS REQUIRED: Computer / Laptop, Java Development Kit (JDK),
Command Prompt / Terminal, Opera ng System (Windows / Linux / macOS).
THEORY : Java provides different input methods to interact with users using
packages like [Link] and java.u l.
Command Line Arguments
• Input is passed at the me of program execu on.
• Stored as strings in main() method.
• Simple and useful for small programs.
DataInputStream
• Used to read input in byte form.
• Can read primi ve data types.
• Less commonly used in modern Java.
BufferedReader
• Reads text efficiently using buffering.
• Faster than basic input methods.
• Reads input as strings.
• Requires excep on handling.
Scanner Class
• Most commonly used input method.
• Can read different data types (int, float, string).
• Easy to use and flexible.
Console Class
• Used for secure input like passwords.
• Does not display typed password on screen.
• Mainly used in system-level applica ons.
2400970100093 ISHITA SINGH

Different input methods are chosen based on need such as speed, simplicity,
and security.
Execu on format:
To Compile: javac fi[Link]
To Run: java ClassName arg1 arg2 arg3
7 – A) Construct java program using Java I/O package, Write a
program in java to take input from user by using all the following
methods: • Command Line Arguments • DataInputStream Class •
BufferedReader Class • Scanner Class • Console Class
SOURCE CODE: -
Command Line Arguments
class CommandLineDemo {
public sta c void main(String args[]) {
[Link]("Name: " + args[0]);
[Link]("Age: " + args[1]);
}
}
OUTPUT: -

DataInputStream
import [Link].*;
class DataInputDemo {
public sta c void main(String args[]) throws Excep on {
DataInputStream dis = new DataInputStream([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Name: " + name);
}
2400970100093 ISHITA SINGH

OUTPUT: -

BufferedReader
import [Link].*;
class BufferedReaderDemo {
public sta c void main(String args[]) throws Excep on {
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Enter your city: ");
String city = [Link]();
[Link]("City: " + city);
}
}
OUTPUT: -

Scanner
import java.u l.*;
class ScannerDemo {
public sta c void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
2400970100093 ISHITA SINGH

[Link]("Number: " + num);


}}
OUTPUT: -

Console
import [Link].*;
class ConsoleDemo {
public sta c void main(String args[]) {
Console c = [Link]();
if(c != null) {
String name = [Link]("Enter username: ");
char[] password = [Link]("Enter password: ");
[Link]("Username: " + name);
} else {
[Link]("Console not available");
}
}
}
OUTPUT: -

You might also like