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

Java Practical

The document outlines a series of Java programming experiments aimed at developing various skills, including string manipulation, array handling, exception handling, and file operations. Each experiment includes a specific aim, source code, and expected output. The topics covered range from parsing telephone numbers to handling exceptions and displaying directory contents.

Uploaded by

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

Java Practical

The document outlines a series of Java programming experiments aimed at developing various skills, including string manipulation, array handling, exception handling, and file operations. Each experiment includes a specific aim, source code, and expected output. The topics covered range from parsing telephone numbers to handling exceptions and displaying directory contents.

Uploaded by

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

List of Experiment

S.N
o
1 Write a java program that accepts10-digit string as a
telephone number and extracts the 3-digit are a code,
3-digit exchange and the remaining 4-digit number
as a separate string and print them.
2 Write a Java program to count the number of word sign
a given sentences.
3 Write a java code to create a 2-D array having 5
rows, with first row having 1element, second row
having 2 elements and so on. Store numbers in these
cells by taking input from user and find the sum of
the numbers ofeach row.
4 Write a program that creates an abstract class called
Shape. Create two subclasses rectangle and triangle.
Include appropriate methods for both the subclasses
that calculate and display the area of the
rectangle and triangle.
5 Write a java source code to accept elements
of an integer array from command line and
sort the array.
6 Define an exception Neg Arg Exception that is
thrown if the argument is negative. Write a
program to find the factorial of a number that
uses thisexception when the number is negative.
7 Create an exception called “No Match Exception” that
is thrown if the string is note equal to “India” .Handle
the exception in your java program.
8 Write Java code to see the all the IP addresses of
“www.google.com” using Inet Address class.
9 Write a java program to read a character file
line by line and displayits contents with line
numbers.
10 Write a java program that display the contents of a
directory passed through command line argument.

RSR rungta College of Engineering & Technology, Bhilai pg. 1


CSE Department
JAVA LAB
MCA-II

Experiment-01

Aim:- 1.Write a java program that accepts10-digit string as a telephone numberand


extracts the 3-digit area code, 3-digit exchange and the remaining 4-digit number as a
separate string and print them.
SourceCode:-
import java.util.Scanner;

public class TelephoneNumberParser { public


static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a 10-digit telephone number: ");String
phoneNumber = scanner.nextLine();

if (phoneNumber.length() == 10) {
String areaCode = phoneNumber.substring(0, 3); String
exchange = phoneNumber.substring(3, 6); String
remainingNumber = phoneNumber.substring(6);

System.out.println("Area Code: " + areaCode); System.out.println("Exchange: "


+ exchange); System.out.println("Remaining Number: " + remainingNumber);
} else {
System.out.println("Invalid telephone number format. Please enter a 10-digit
number.");
}
scanner.close();
}
}

RSR rungta College of Engineering & Technology, Bhilai pg. 2


CSE Department
JAVA LAB
MCA-II

Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 3


CSE Department
JAVA LAB
MCA-II

Experiment-02

Aim:- 2 Write a Java program to count the number of word sign a givensentences.
Source Code:-
import java.util.Scanner;

public class WordCount {


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

int wordCount = countWords(sentence);

System.out.println("Number of words: " + wordCount);

scanner.close();
}

public static int countWords(String sentence) {


if (sentence == null ||
sentence.trim().isEmpty()) {return 0;
}

String[] words =

RSR rungta College of Engineering & Technology, Bhilai pg. 4


CSE Department
JAVA LAB
MCA-II

sentence.trim().split("\\s+");return
words.length;
}
}

Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 5


CSE Department
JAVA LAB
MCA-II
Experiment-03

Aim:- 3 Write a java code to create a 2-D array having 5 rows, with first row having
1element, second row having 2 elements and so on. Store numbers in these cells by
taking input from user and find the sum of the numbers of each row.
Source Code:-
import java.util.Scanner;

public class SumOfRowElements {


public static void main(String[]
args) {
int[][] array = new int[5][]; // Initialize the 2D array

// Populate the array with elements based on the


patternfor (int i = 0; i < 5; i++) {
array[i] = new int[i + 1];
}

Scanner scanner = new Scanner(System.in);

// Take input from the user to fill the


arrayfor (int row = 0; row < 5;

row++) {
for (int col = 0; col < array[row].length; col++) {
");
System.out.print("Enter value for row " + (row + 1) + ", column " + (col + 1) + ":

array[row][col] = scanner.nextInt();

RSR rungta College of Engineering & Technology, Bhilai pg. 6


CSE Department
JAVA LAB
MCA-II

}
}

// Calculate and print the sum of each


rowfor (int row = 0; row < 5; row++)
{
int rowSum = 0;
for (int col = 0; col < array[row].length;
col++) {rowSum += array[row][col];
}
System.out.println("Sum of row " + (row + 1) + ": " + rowSum);
}

scanner.close();
}
}

RSR rungta College of Engineering & Technology, Bhilai pg. 7


CSE Department
JAVA LAB
MCA-II

Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 8


CSE Department
JAVA LAB
MCA-II

Experiment-04

Aim:- 4 Write a program that creates an abstract class called Shape. Create two
subclasses rectangle and triangle. Includeappropriate methods for both the subclasses
that calculate and display the area of the rectangle and triangle.
Source Code:-
abstract class Shape {
abstract double calculateArea();

abstract void displayArea();


}

class Rectangle extends

Shape {private double


length;
private double width;

public Rectangle(double length, double


width) {this.length = length;
this.width = width;
}

double calculateArea() {
return length * width;
}

void displayArea() {
System.out.println("Rectangle Area: " + calculateArea());

RSR rungta College of Engineering & Technology, Bhilai pg. 9


CSE Department
JAVA LAB
MCA-II

}
}

class Triangle extends Shape {


private double base;

private double height;

public Triangle(double base, double


height) {this.base = base;
this.height = height;
}

double calculateArea() {

return 0.5 * base *


height;
}

void displayArea() {
System.out.println("Triangle Area: " + calculateArea());
}
}

class ShapeDemo {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5,
10);rectangle.displayArea();

RSR rungta College of Engineering & Technology, Bhilai pg. 10


CSE Department
JAVA LAB
MCA-II

Triangle triangle = new Triangle(4, 7);


triangle.displayArea();
}
}
Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 11


CSE Department
JAVA LAB
MCA-II

Experiment-05

Aim:- 5 Write a java source code to accept elements of an integer array fromcommand
line and sort the array.
Source Code:-
import java.util.Arrays;

public class ArraySorting {


public static void main(String[]

args) {if (args.length == 0) {


System.out.println("Please provide integer elements as command line
arguments.");return;
}

int[] array = new


int[args.length]; for (int i = 0; i
< args.length; i++) {
try {
array[i] = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {
System.out.println("Invalid input: " +
args[i]);return;
}
}

Arrays.sort(array);
System.out.print("Sorted Array:
");for (int num : array) {

RSR rungta College of Engineering & Technology, Bhilai pg. 12


CSE Department
JAVA LAB
MCA-II

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


}
}
}

RSR rungta College of Engineering & Technology, Bhilai pg. 13


CSE Department
JAVA LAB
MCA-II

Experiment-06

Aim:- 6 Define an exception NegArgException that is thrown if the


argument is negative. Write a program to find the factorial of a number that
uses this exception when the number is negative.

Source Code:-
class NegArgException extends Exception {

public NegArgException(String message) {


super(message);
}
}

public class FactorialWithException {


public static int factorial(int n) throws

NegArgException {if (n < 0) {


throw new NegArgException("Negative argument: " + n);

if (n == 0 || n == 1)

{return 1;
}

return n * factorial(n - 1);


}

public static void main(String[]

args) {try {

RSR rungta College of Engineering & Technology, Bhilai pg. 14


CSE Department
JAVA LAB
MCA-II

int number = -9; // Change this to the desired

numberint result = factorial(number);


System.out.println("Factorial of " + number + " is " + result);
} catch (NegArgException e) {

System.out.println("Error: " + e.getMessage());

}
}

Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 15


CSE Department
JAVA LAB
MCA-II

Experiment-07

Aim:- 7 Create an exception called “NoMatchException” that is thrown if thestring is


note equal to “India”. Handle the exception in your java program.
Source Code:-
class NegArgException extends Exception {
public NegArgException(String message) {
super(message);
}
}

public class FactorialWithException {


public static int factorial(int n) throws
NegArgException {if (n < 0) {
throw new NegArgException("Negative argument: " + n);
}

if (n == 0 || n == 1)
{return 1;
}

return n * factorial(n - 1);


}

public static void main(String[]


args) {try {
int number = -5; // Change this to the desired

RSR rungta College of Engineering & Technology, Bhilai pg. 16


CSE Department
JAVA LAB
MCA-II

numberint result = factorial(number);


System.out.println("Factorial of " + number + " is " + result);
} catch (NegArgException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 17


CSE Department
JAVA LAB
MCA-II

Experiment-8

Aim:- 8 Write Java code to see the all the IP addresses of “www.google.com”using
InetAddressclass.
Source Code:-
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPAddressLookup {


public static void main(String[]
args) {try {
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");

System.out.println("IP Addresses of www.google.com:");

for (InetAddress address : addresses) {


System.out.println(address.getHostAddress());
}
} catch (UnknownHostException e) {

System.out.println("Error: " + e.getMessage());


}
}
}
Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 18


CSE Department
JAVA LAB
MCA-II

Experiment-9

Aim:- 9 Write a java program to read a character file line by line and display itscontents
with line numbers.
Source Code:-
import
java.io.BufferedReader;
import java.io.FileReader;

import java.io.IOException;

public class FileReadWithLineNumbers {


public static void main(String[] args) {
String filePath = "path_to_your_file.txt"; // Replace with the actual file path

try (BufferedReader reader = new BufferedReader(new FileReader(filePath)))


{String line;
int lineNumber = 1;
while ((line = reader.readLine()) != null) {
System.out.println("Line " + lineNumber + ": " +
line);lineNumber++;
}
} catch (IOException e) {
System.out.println("Error: " +
e.getMessage());
}
}
}

RSR rungta College of Engineering & Technology, Bhilai pg. 19


CSE Department
JAVA LAB
MCA-II

Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 20


CSE Department
JAVA LAB
MCA-II

Experiment-10

Aim:- 10 Write a java program that display the contents of a directory passedthrough
command line argument.

Source Code:-
import java.io.File;

public class DirectoryContents {


public static void main(String[]
args) {if (args.length != 1) {

System.out.println("Usage: java DirectoryContents


<directory_path>");return;
}

String directoryPath = args[0];


File directory = new File(directoryPath);

if (!directory.exists() ||
!directory.isDirectory()) {
System.out.println("Invalid directory
path."); return;
}

System.out.println("Contents of " + directoryPath +


":");File[] files = directory.listFiles();

RSR rungta College of Engineering & Technology, Bhilai pg. 21


CSE Department
JAVA LAB
MCA-II

if (files != null) {
for (File file : files) {
System.out.println(file.getName());
}
} else {
System.out.println("No files or directories found.");
}
}
}

Output:-

RSR rungta College of Engineering & Technology, Bhilai pg. 22

You might also like