0% found this document useful (0 votes)
12 views10 pages

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)
12 views10 pages

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

[Link] two n x n matrices. Write a Java program to find addition of these matrices.

Code:

import [Link];
public class Practs1 {
public static void main(String[] args) {
int m, n, c, d;
Scanner in = new Scanner([Link]);
[Link]("Enter the number of rows of matrix");
m = [Link]();
[Link]("Enter the number of columns of matrix");
n = [Link]();int first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = new int[m][n];
[Link]("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
first[c][d] = [Link]();
}
}
[Link]("Enter the elements of second matrix");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
second[c][d] = [Link]();
}
}
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
}
}
[Link]("Sum of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
[Link](sum[c][d]+"\t");
}
[Link]();
}
}
}

2 Accept n strings. Sort names in ascending order.


Code:
import [Link];
public class Practs2 {
public static void main(String[] args) {
int i, j;
String temp;
Scanner scan = new Scanner([Link]);
String names[] = new String[5];
[Link]("Enter 5 Names/Words : ");
for(i=0; i<5; i++)
{
names[i] = [Link]();
}
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;
}
}
}
[Link]("Words/Names Sorted in Alphabetical Order Successfully..!!");
for(i=0;i<5;i++)
{
[Link](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();
[Link]("Cat");
[Link]("Black");
}

public void name(String nm) {


[Link]("Species :"+nm);
}

public void color(String cl) {


[Link]("Color:"+cl);
}
}
Execute:
javac animals/[Link] animals/[Link]
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;
[Link]("Addition of 2 nos="+c);
}
void add(int a,int b,int c)
{
int d=a+b+c;
[Link]("Addition of 3 nos ="+d);
}
public static void main(String[] args) {
Practs6 p=new Practs6();
[Link](4,5);
[Link](7,8,4);
}
}

Method OverRiding:
package methodoverriding;
public class MethodOverriding {
public static void main(String[] args) {
Base b1=new Base();
[Link](4, 5);
Base b2=new Derived();
[Link](6,7);
}
}
class Base
{
void add(int a,int b)
{
int c=a+b;
[Link]("addition of base class="+ c);
}
}
class Derived extends Base
{
void add(int a,int b)
{
int c=a+b;
[Link]("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
{
[Link]("No is greater");
}
}
catch(MyException e)
{
[Link](e);
}
}
}
7 Write a Java List example and demonstrate methods of Java List interface.
import [Link];
import [Link];

public class ListExample {


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

// Add elements to the list


[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

// Print the list


[Link]("List after adding elements: " + fruits);

// Add an element at a specific position


[Link](1, "Blueberry");
[Link]("List after adding an element at index 1: " + fruits);

// Access an element
String firstFruit = [Link](0);
[Link]("First fruit: " + firstFruit);

// Modify an element
[Link](2, "Strawberry");
[Link]("List after modifying element at index 2: " + fruits);

// Remove an element by index


[Link](3);
[Link]("List after removing element at index 3: " + fruits);

// Remove an element by value


[Link]("Banana");
[Link]("List after removing 'Banana': " + fruits);

// Check if the list contains a specific element


boolean hasApple = [Link]("Apple");
[Link]("List contains 'Apple': " + hasApple);

// Get the size of the list


int size = [Link]();
[Link]("Size of the list: " + size);

// Iterate over the list


[Link]("Iterating over the list: ");
for (String fruit : fruits) {
[Link](fruit + " ");
}
[Link]();

// Clear the list


[Link]();
[Link]("List after clearing: " + fruits);

// Check if the list is empty


boolean isEmpty = [Link]();
[Link]("Is the list empty: " + isEmpty);
}
}

8 Using various AWT components,


a. Design Java applications to accept a student's resume. (Design form)
import [Link];
import [Link].*;
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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
setSize(120,300);
setVisible(true);
}
public static void main(String[] args) {
Practical10 p=new Practical10();
}

public void actionPerformed(ActionEvent e) {


String a=[Link]();
int n1=[Link]([Link]());
int n2=[Link]([Link]());
if([Link]("Add"))
{
int r=n1+n2;
String rs=[Link](r);
[Link](rs);
}
if([Link]("Sub"))
{
int r=n1-n2;
String rs=[Link](r);
[Link](rs);
}
if([Link]("Mul"))
{
int r=n1*n2;
String rs=[Link](r);
[Link](rs);
}
if([Link]("Div"))
{
float n3=[Link]([Link]());
float n4=[Link]([Link]());
float r=n3/n4;
String rs=[Link](r);
[Link](rs);
}
if([Link]("Clear"))
{
[Link]("");
[Link]("");
[Link]("");
[Link]();
}
}
}
9 Write a java program to copy the content of [Link] file to [Link] file.
import [Link];
import [Link];
import [Link];
import [Link];

public class FileCopy {


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

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

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 [Link].*;
import [Link];
import [Link];

public class FactorialServer {


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

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


[Link]("Server is listening on port " + PORT);

while (true) {
try (Socket socket = [Link]();
BufferedReader input = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](), true)) {

[Link]("Client connected");

// Read number from client


String numberStr = [Link]();
int number = [Link](numberStr);

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

// Send the result back to client


[Link](factorial);

} catch (IOException e) {
[Link]("Client communication error: " + [Link]());
}
}
} catch (IOException e) {
[Link]("Server error: " + [Link]());
}
}

private static long calculateFactorial(int number) {


long result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
}
Client:
import [Link].*;
import [Link];
import [Link];

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([Link](), true);
BufferedReader input = new BufferedReader(new
InputStreamReader([Link]()));
Scanner scanner = new Scanner([Link])) {

[Link]("Connected to server");

// Get number from user


[Link]("Enter a number: ");
int number = [Link]();

// Send the number to server


[Link](number);

// Read the factorial result from server


String result = [Link]();
[Link]("Factorial is: " + result);

} catch (IOException e) {
[Link]("Client error: " + [Link]());
}
}
}

You might also like