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

Core Java Practicals

The document contains multiple Java programming tasks including matrix addition, string sorting, interface implementation, inheritance demonstration, method overloading and overriding, custom exception handling, list operations, AWT GUI applications, file copying, and a TCP client-server program for calculating factorials. Each task is accompanied by sample code demonstrating the required functionality. The tasks cover a range of Java concepts suitable for learning and practice.

Uploaded by

tejasnimbale3
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)
2 views

Core Java Practicals

The document contains multiple Java programming tasks including matrix addition, string sorting, interface implementation, inheritance demonstration, method overloading and overriding, custom exception handling, list operations, AWT GUI applications, file copying, and a TCP client-server program for calculating factorials. Each task is accompanied by sample code demonstrating the required functionality. The tasks cover a range of Java concepts suitable for learning and practice.

Uploaded by

tejasnimbale3
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/ 10

1.Accept two n x n matrices. Write a Java program to find addition of these matrices.

Code:

import java.util.Scanner;
public class Practs1 {
public static void main(String[] args) {
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows of matrix");
m = in.nextInt();
System.out.println("Enter the number of columns of matrix");
n = in.nextInt();int first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
first[c][d] = in.nextInt();
}
}
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
second[c][d] = in.nextInt();
}
}
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices
}
}
System.out.println("Sum of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
System.out.print(sum[c][d]+"\t");
}
System.out.println();
}
}
}

2 Accept n strings. Sort names in ascending order.


Code:
import java.util.Scanner;
public class Practs2 {
public static void main(String[] args) {
int i, j;
String temp;
Scanner scan = new Scanner(System.in);
String names[] = new String[5];
System.out.println("Enter 5 Names/Words : ");
for(i=0; i<5; i++)
{
names[i] = scan.nextLine();
}
for(i=0; i<5; i++)
{
for(j=1; j<5; j++)
{
if(names[j-1].compareTo(names[j])>0)
{
temp=names[j-1];
names[j-1]=names[j];
names[j]=temp;
}
}
}
System.out.println("Words/Names Sorted in Alphabetical Order Successfully..!!");
for(i=0;i<5;i++)
{
System.out.println(names[i]);
}
}
}

3 Create a package: animals. In the package animals create interface Animal with
suitable behaviours. Implement the interface Animal in the same package animals.
Code:
Interface:
package animals;
public interface Animal {
public void name(String nm);
public void color(String cl);
}
Class:
package animals;
public class Animals implements Animal {
public static void main(String[] args) {
Animals an=new Animals();
an.name("Cat");
an.color("Black");
}

public void name(String nm) {


System.out.println("Species :"+nm);
}

public void color(String cl) {


System.out.println("Color:"+cl);
}
}
Execute:
javac animals/Animal.java animals/Animals.java
Java

4 Demonstrate Java inheritance using extends keyword


Code:

5 Demonstrate method overloading and method overriding in Java.


Code:
Method Overloading Program:
package practs6;
public class Practs6 {
void add(int a,int b)
{
int c=a+b;
System.out.println("Addition of 2 nos="+c);
}
void add(int a,int b,int c)
{
int d=a+b+c;
System.out.println("Addition of 3 nos ="+d);
}
public static void main(String[] args) {
Practs6 p=new Practs6();
p.add(4,5);
p.add(7,8,4);
}
}

Method OverRiding:
package methodoverriding;
public class MethodOverriding {
public static void main(String[] args) {
Base b1=new Base();
b1.add(4, 5);
Base b2=new Derived();
b2.add(6,7);
}
}
class Base
{
void add(int a,int b)
{
int c=a+b;
System.out.println("addition of base class="+ c);
}
}
class Derived extends Base
{
void add(int a,int b)
{
int c=a+b;
System.out.println("addition of derived class="+ c);
}
}

6 Demonstrate creating your own exception in Java.

Code:
package practs7;
class MyException extends Exception
{ String str;
MyException(String s)
{
str=s;
}

public String toString()


{
return("Exception Occured="+str);
}
}
public class Practs7 {

public static void main(String[] args) {


try
{
float x=5;
float y=1000;
float z=x/y;
if(z<0.5)
{
throw new MyException("No is to small");
}
else
{
System.out.println("No is greater");
}
}
catch(MyException e)
{
System.out.println(e);
}
}
}
7 Write a Java List example and demonstrate methods of Java List interface.
import java.util.ArrayList;
import java.util.List;

public class ListExample {


public static void main(String[] args) {
// Create an ArrayList instance
List<String> fruits = new ArrayList<>();

// Add elements to the list


fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Print the list


System.out.println("List after adding elements: " + fruits);

// Add an element at a specific position


fruits.add(1, "Blueberry");
System.out.println("List after adding an element at index 1: " + fruits);

// Access an element
String firstFruit = fruits.get(0);
System.out.println("First fruit: " + firstFruit);

// Modify an element
fruits.set(2, "Strawberry");
System.out.println("List after modifying element at index 2: " + fruits);

// Remove an element by index


fruits.remove(3);
System.out.println("List after removing element at index 3: " + fruits);

// Remove an element by value


fruits.remove("Banana");
System.out.println("List after removing 'Banana': " + fruits);

// Check if the list contains a specific element


boolean hasApple = fruits.contains("Apple");
System.out.println("List contains 'Apple': " + hasApple);

// Get the size of the list


int size = fruits.size();
System.out.println("Size of the list: " + size);

// Iterate over the list


System.out.print("Iterating over the list: ");
for (String fruit : fruits) {
System.out.print(fruit + " ");
}
System.out.println();

// Clear the list


fruits.clear();
System.out.println("List after clearing: " + fruits);

// Check if the list is empty


boolean isEmpty = fruits.isEmpty();
System.out.println("Is the list empty: " + isEmpty);
}
}

8 Using various AWT components,


a. Design Java applications to accept a student's resume. (Design form)
import java.awt.Frame;
import java.awt.*;
public class Practs9 extends Frame {
Label nm, age,pno,addr,gender,qual;
TextField tnm, tage,tpno;
Checkbox m,fm,q1,q2,q3,q4;
CheckboxGroup cbg;
TextArea tr;
Button b;
public Practs9() {
setLayout(new FlowLayout());
nm=new Label("Name");
age=new Label("Age");
pno=new Label("PhoneNo");
gender=new Label("Gender");
qual=new Label("Qualification");
addr=new Label("Address");
tnm=new TextField(20);
tage=new TextField(20);
tpno=new TextField(20);
cbg=new CheckboxGroup();
m=new Checkbox("Male", false,cbg);
fm=new Checkbox("FeMale" ,false,cbg);
q1=new Checkbox("Msc Cs");
q2=new Checkbox("Msc It");
q3=new Checkbox("MCom");
q4=new Checkbox("MA");
tr=new TextArea(5,26);
b=new Button("submit");
add(nm);
add(tnm);
add(age);
add(tage);
add(pno);
add(tpno);
add(gender);
add(m);
add(fm);
add(qual);
add(q1);
add(q2);
add(q3);
add(q4);
add(addr);
add(tr);
add(b);
setSize(200,500);
setVisible(true);
}

public static void main(String[] args) {


Practs9 i=new Practs9();
}
}

b. Design simple calculator GUI application using AWT components.

Code:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Practical10 extends Frame implements ActionListener{
Label no1,no2,result;
TextField tno1,tno2,tresult;
Button badd,bsub,bmul,bdiv,bclr;
public Practical10() {
setLayout(new FlowLayout());
no1=new Label("Enter 1 st no");
no2=new Label("Enter 2 nd no");
result=new Label("Result");
tno1=new TextField(10);
tno2=new TextField(10);
tresult=new TextField(10);
badd= new Button("Add");
bsub= new Button("Sub");
bmul= new Button("Mul");
bdiv= new Button("Div");
bclr= new Button("Clear");
add(no1);
add(tno1);
add(no2);
add(tno2);
add(result);
add(tresult);
add(badd);
add(bsub);
add(bmul);
add(bdiv);
add(bclr);
badd.addActionListener(this);
bsub.addActionListener(this);
bmul.addActionListener(this);
bdiv.addActionListener(this);
bclr.addActionListener(this);
setSize(120,300);
setVisible(true);
}
public static void main(String[] args) {
Practical10 p=new Practical10();
}

public void actionPerformed(ActionEvent e) {


String a=e.getActionCommand();
int n1=Integer.parseInt(tno1.getText());
int n2=Integer.parseInt(tno2.getText());
if(a.equals("Add"))
{
int r=n1+n2;
String rs=String.valueOf(r);
tresult.setText(rs);
}
if(a.equals("Sub"))
{
int r=n1-n2;
String rs=String.valueOf(r);
tresult.setText(rs);
}
if(a.equals("Mul"))
{
int r=n1*n2;
String rs=String.valueOf(r);
tresult.setText(rs);
}
if(a.equals("Div"))
{
float n3=Float.parseFloat(tno1.getText());
float n4=Float.parseFloat(tno2.getText());
float r=n3/n4;
String rs=String.valueOf(r);
tresult.setText(rs);
}
if(a.equals("Clear"))
{
tresult.setText("");
tno1.setText("");
tno2.setText("");
tno1.requestFocus();
}
}
}
9 Write a java program to copy the content of abc.txt file to pqr.txt file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class FileCopy {


public static void main(String[] args) {
// Define the source and destination file paths
Path sourcePath = Path.of("abc.txt");
Path destinationPath = Path.of("pqr.txt");

try {
// Copy the file content from source to destination
Files.copy(sourcePath, destinationPath,
StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully!");
} catch (IOException e) {
// Handle potential I/O errors
System.err.println("Error occurred while copying the file: " + e.getMessage());
}
}
}

10 Write a TCP client-server program; the client accepts a number from the user &
sends it to the server, the server returns the factorial of that number to the client.
Server code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FactorialServer {


public static void main(String[] args) {
final int PORT = 12345;

try (ServerSocket serverSocket = new ServerSocket(PORT)) {


System.out.println("Server is listening on port " + PORT);

while (true) {
try (Socket socket = serverSocket.accept();
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true)) {

System.out.println("Client connected");

// Read number from client


String numberStr = input.readLine();
int number = Integer.parseInt(numberStr);

// Calculate factorial
long factorial = calculateFactorial(number);

// Send the result back to client


output.println(factorial);

} catch (IOException e) {
System.err.println("Client communication error: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Server error: " + e.getMessage());
}
}

private static long calculateFactorial(int number) {


long result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
}
Client:
import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class FactorialClient {


public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost";
final int PORT = 12345;

try (Socket socket = new Socket(SERVER_ADDRESS, PORT);


PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
Scanner scanner = new Scanner(System.in)) {

System.out.println("Connected to server");

// Get number from user


System.out.print("Enter a number: ");
int number = scanner.nextInt();

// Send the number to server


output.println(number);

// Read the factorial result from server


String result = input.readLine();
System.out.println("Factorial is: " + result);

} catch (IOException e) {
System.err.println("Client error: " + e.getMessage());
}
}
}

You might also like