0% found this document useful (0 votes)
2 views62 pages

JavaRecrdupdated 1

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 views62 pages

JavaRecrdupdated 1

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

Introduction to Java

Java is a programming language and a platform. Java is a high level, robust, object-oriented and
secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the name from Oak to
Java.

Features of Java:-

Simple

Object-Oriented

Portable

Platform independent

Secured

Robust

Architecture neutral

Interpreted

High Performance

Multithreaded

Distributed

Dynamic

Application

According to Sun, 3 billion devices run Java. There are many devices where Java is currently used.
Some of them are as follows:

Desktop Applications such as acrobat reader, media player, antivirus, etc.

Web Applications such as [Link], [Link], etc.

Enterprise Applications such as banking applications.

Mobile

Embedded System

Smart Card

Robotics

Games, etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications.
These are traditional software that we need to install on every machine. Examples of standalone
application are Media player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In
Java, EJB is used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently, Android
and Java ME are used for creating mobile applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as [Link], [Link],
[Link], [Link], [Link], [Link] etc. It includes core topics like OOPs, String, Regex,
Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection,
Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built
on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface API

Java OOPs Concepts

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm
that provides many concepts, such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as a truly object-oriented programming
language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for example,
object, classes, abstraction, inheritance, polymorphism, etc.
OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies software development and maintenance by providing some concepts:

Object

Class

Inheritance

Polymorphism

Abstraction

Encapsulation

Write a java program to find the addition of two numbers.

class Add {

public static void main(String[] args) {

// Declare and initialize two integer variables

int number1 = 15;

int number2 = 25;

// Perform the addition

int sum = number1 + number2;

// Print the result

[Link]("The sum of " + number1 + " and " + number2 + " is: " + sum);

o/p:

The sum of 15 and 25 is: 40

Write java program to find factorial of a number

class Fact

public static void main(String[] args)

int n=6;

int fact=1;

for(int i=1;i<=n; i++)

{
fact=fact*i;

[Link]("factorial of a number is:" +fact);

O/P:

factorial of a number is:720

Write a java program to find a reverse of number.

import [Link];

public class Reverse

public static void main(String[] args)

int rev=0,num,num1,rem;

Scanner in =new Scanner([Link]);

[Link]("enter a number");

num=[Link]();

num1=num;

while(num>0)

rem=num%10;

rev=rev*10+rem;

num=num/10;

[Link]("the reverse of number :" +num1+ " is " +rev);

O/P

enter a number

689

the reverse of number :689 is 986

Write a java program to generate a Fibonacci series

class Fibo
{

public static void main(String args[])

int f=0,f1=1,f2,count=10;

[Link](f);

[Link](f1);

for(int i=2;i<count;i++)

f2=f+f1;

[Link](f2);

f=f1;

f1=f2; } } }

O/P:

0 1 1 2 3 5 8 13 21 34

Write a java program to print multiplication table.

class Multi

public static void main(String args[])

{ int n=4;

for(int i=1;i<=10;i++)

[Link](n + "x" +i+"=" +(n*i));

O/P:

4x1=4

4x2=8

4x3=12

4x4=16

4x5=20

4x6=24

4x7=28

4x8=32
4x9=36

4x10=40

Implement the concept of classes and objects.

Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.

Syntax to declare a class:

class <class_name>

field;

method;

Object: An entity that has state and behaviour is known as an object. It can be physical or logical
entity. An object can be defined as an instance of a class. An object contains an address and take
up some space to memory.

Syntax:

Class name object name =new class name();

Keyword

Object and Class Example: main within the class

Java Program to illustrate how to define a class and fields

//Defining a Student class.

class Student{

//defining fields

int id;//field or data member or instance variable

String name;

//creating main method inside the Student class

public static void main(String args[]){

//Creating an object or instance

Student s1=new Student();//creating an object of Student

//Printing values of the object

[Link]([Link]);//accessing member through reference variable

[Link]([Link]);

Output:
0

null

//main method outside the class

class Student

int id;

String name;

public class Student1

public static void main(String args[])

Student S1=new Student();

[Link]([Link]);

[Link]([Link]);

O/P

Null

class Student2

int id;

String name;

class Stud1

public static void main(String args[])

Student2 S1=new Student2();

[Link]=100;

[Link]="Sandhya";

Student2 S2=new Student2();


[Link]=101;

[Link]="Vanditha";

[Link]([Link]+ " " +[Link]);

[Link]([Link]+ " " +[Link]);

O/P

C:\Users\Student\Desktop\CSE-C>java Stud1

100 Sandhya

101 Vanditha

Data types in Java

Data types specify the different sizes and values that can be stored in the variable or constants.
These are two types of datatypes in java. Each data type is predefined.

Primitive Datatype

Non-primitive Datatype

Primitive Datatype: In Java, primitive data types are the building blocks of data manipulation. These
are the basic data types.

In Java, there are mainly eight primitive data types which are as follows.

boolean data type

char data type

byte data type

short data type

int data type

long data type

float data type

double data type

Non-Primitive Data Types in Java

In Java, non-primitive data types are also known as reference data types. It is used to store
complex objects rather than simple values. Non-Primitive data types in java are user defined data
types & they can be easily created or modified by the user.

There are four types of Non-Primitive Data Types.

Class

String

Array
Interfaces

Ex: write a program on datatypes

public class Prdatatype

public static void main(String args[])

boolean bool = true;

char ch = 'z';

int num = 1234;

byte size = 2;

short srt = 78;

double value = 2.4546778;

float temp = 3.8f;

long val = 1888889;

[Link]("boolean: " + bool);

[Link]("char: " + ch);

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

[Link]("byte: " + size);

[Link]("short: " + srt);

[Link]("float: " + value);

[Link]("double: " + temp);

[Link]("long: " + val);

O/P

C:\Users\Student\Desktop\CSE-C>javac [Link]

C:\Users\Student\Desktop\CSE-C>java Prdatatype

boolean: true

char: z

integer: 1234

byte: 2

short: 78

float: 2.4546778
double: 3.8

long: 1888889

Variables:

Variable are container used to store data values. They are fundamental elements for manipulating
and referencing information within a program.

int data=50;

A variable is assigned with a data type. Which determines the kind of data it can hold.

Types of Variables

There are three types of variables in Java:

local variable

instance variable

static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.

A local variable cannot be defined with "static" keyword.

//defining a Local Variable

int num = 10;

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

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among
instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.

Example program on variables:

public class A

static int statvar=30;

int insvar=25;

void someMethod()
{

int a=10; //local variable

public static void main(String args[])

A obj1=new A();

[Link]([Link]);

[Link]([Link]);

//[Link]();

O/P :

C:\Users\Student\Desktop\java programs>javac [Link]

C:\Users\Student\Desktop\java programs>java A

30

25

Type Casting

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

Widening Casting (automatically) - converting a smaller type to a larger type size is also called
Implicit conversion. byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) - converting a larger type to a smaller size type is also called Explicit
conversion. double -> float -> long -> int -> char -> short -> byte

Write a java program to convert integer to data type to double.

class ITD

public static void main(String args[])

int num=12;

[Link]("the integer value is :"+num);

double data=num;

[Link]("the double value is :"+data);

}
}

O/P:

C:\Users\Student\Desktop>java ITD

the integer value is :12

the double value is :12.0

Write a java program to convert double data type to integer.

class DTI

public static void main(String args[])

double num=12.25;

[Link]("the double value is :"+num);

int data=(int)num;

[Link]("the double value is :"+data);

O/P:

C:\Users\Student\Desktop>java DTI

the double value is :12.25

the double value is :12

Write a java program to convert integer data type to String.

import [Link];

class Str

public static void main(String args[])

int num=13;

[Link]("the integer value is:" +num);

String data=[Link](num);

[Link]("The string value is:"+data);

O/P:
C:\Users\Student\Desktop>java Str

the integer value is:13

The string value is:13

Write a java program to convert string data type to integer

import [Link];

class Str1

public static void main(String args[])

String data="13";

[Link]("the string value is:" +data);

int num=[Link](data);

[Link]("The integer value is:"+num);

O/P:

C:\Users\Student\Desktop>java Str1

the string value is:13

The integer value is:13

Arrays

Java array is an object which contains elements of a similar data type. Additionally, The elements of
an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.

Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

Random access: We can get any data located at an index position.

Disadvantages

Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.

Types of Array in java

There are two types of array.

Single Dimensional Array


Multidimensional Array

Write a java program on single Dimensional Array

class TestArray

public static void main(String args[])

int a[]= new int[5];

a[0]=10;

a[1]=20;

a[2]=25;

a[3]=30;

a[4]=40;

for (int i=0;i<[Link];i++)

[Link](a[i]);

O/P :

C:\Users\Student\Desktop\java programs>javac [Link]

C:\Users\Student\Desktop\java programs>java TestArray

10

20

25

30

40

Write a java program on Multi Dimensional Array

class Testarray3{

public static void main(String args[])

//declaring and initialising 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

for(int i=0;i<3;i++)

{
for(int j=0;j<3;j++)

[Link](arr[i][j]+" ");

[Link]();

}}

C:\Users\Student\Desktop\java programs>java Testarray3

123

245

445

Expierment-3

Use string and String Tokenizer classes and develop java programs

Java String: In Java, string is basically an object that represents sequence of char values.
An array of characters works as a string in Java.

Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

String Tokenizer in Java

The [Link] class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to
the tokens.

The six useful methods of the StringTokenizer class are as follows:

Aim: To write a java program to create a string

import [Link];

public class StringExample

public static void main(String args[])

String s1="java"; //creating string by Java string literal

char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch); //converting char array to string


String s3=new String("example"); /creating Java string by new keyword

[Link](s1);

[Link](s2);

[Link](s3);

o/p:

D:\>javac [Link]

D:\>java StringExample

java

strings

example

Write a java program to implement the methods of string class

import [Link];

public class Strm

public static void main(String args[])

String S1="Hello";

String S2="world";

[Link]([Link](S2));

String S3=[Link](S2);

[Link](S3);

[Link]([Link](S2));

String S4="Java,programming,Language";

String[] parts=[Link](",",3);

[Link]("\n parts with limit 2:");

for (String part:parts)

[Link](part);

[Link]([Link]());

String strrepl=[Link]("o","a");
[Link](strrepl);

String S6=[Link]();

[Link](S6);

String S7="Hello world";

//String c=[Link](S7);

[Link]([Link](3));

O/P

-47

Helloworld

false

parts with limit 2:

Java

programming

Language

warld

Hello

lo world

Write a java program to illustrate the concept of String Tokenizer

import [Link];

public class Simple

public static void main(String args[])

StringTokenizer st = new StringTokenizer("my name is Sandhya"," ");

while ([Link]())

[Link]([Link]());

}
}

o/p:

D:\>javac [Link]

D:\>java Simple

my

name

is

Sandhya

Experiment:4: Develop Java Programs using inheritance.

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.

Syntax: class <parent-class>

//methods;

Fields;

Class <child-class>extends <parent-class>

//methods;

Fields;

The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.

Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

Single Inheritance: When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single inheritance.

Example:

import [Link];

class Animal

void eat()

[Link]("eating...");

class Dog extends Animal

void bark()

[Link]("barking..");

public class SingleInheritance1

public static void main(String args[])

Dog D=new Dog();

[Link]();

[Link]();

}
Output:

barking...

eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance.

import [Link];

class Animal

void eat()

[Link]("eating...");

class Dog extends Animal

void bark()

[Link]("barking..");

}}

class BabyDog extends Dog

void weep()

[Link]("weeping...");

public class MultilevelInheritance

public static void main(String args[])

BabyDog D=new BabyDog();


[Link]();

[Link]();

[Link]();

Output:

weeping...

barking...

eating…

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance

//Hierarchical Inheritance

import [Link];

class Animal

void eat()

[Link]("eating...");

class Dog extends Animal

void bark()

[Link]("Barking..");

class cat extends Animal

void meow()

{
[Link]("mewoing..");

class TestHier

public static void main(String args[])

cat c=new cat();

[Link]();

[Link]();

//[Link]();// compilation error

Output:

meowing...

eating...

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

class A{

void msg(){[Link]("Hello");}

class B{

void msg(){[Link]("Welcome");}

class C extends A, B{//suppose if it were

public static void main(String args[]){

C obj=new C();

[Link]();//Now which msg() method would be invoked?

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be ambiguity
to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error.
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Write a java program to demonstrate abstract class

Abstraction : Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

An abstract class must be declared with an abstract keyword.

It can have abstract and non-abstract methods.

It cannot be instantiated.

It can have constructors and static methods also.

It can have final methods which will force the subclass not to change the body of the method.

Example:

import [Link];

abstract class Vehicle

int s; // normal variable

abstract void speed(); // Abstract method where implementation must be empty

void display() // normal method

[Link]("this program will demonstrate abstract classes/methods on vehicle\n");

class Bike extends Vehicle

void speed() // Abstract method implementation must be given in child class

[Link]("Average Bike speed is \t "+s+"\n");

void Brand(String C)

[Link](" Bike company is \t "+C+"\n");

class TestAbs

{
public static void main(String args[])

//Vehicle V=new Vehicle(); Abstract method will never instantiate the objects

Bike B= new Bike();

B.s=65;

[Link]();

[Link]("Hero Honda");

Output:

Average Bike speed is 65

Bike company is Hero Honda

Experiment :5

Aim: Develop a java programs using interfaces and Packages.

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in
Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have
a method body.

Java Interface also represents the IS-A relationship.

There are mainly three reasons to use interface. They are given below.

It is used to achieve abstraction.

By interface, we can support the functionality of multiple inheritance.

It can be used to achieve loose coupling.

Syntax:

interface <interface_name>

// declare constant fields

// declare methods that abstract

// by default.

Example :
import [Link];

interface printable

void print();

class A6 implements printable

public void print()

[Link]("Hello");

public static void main(String args[])

A6 obj=new A6();

[Link]();

Output:

Hello

Write a java program to demonstrate interfaces.

import [Link];

interface Vehicle

public void speed(int S);

public void Brand(String C);

public void milage(double m);

class Bike implements Vehicle

public void speed(int S)

[Link]("Average Bike speed is \t "+S+"\n");

}
public void Brand(String C)

[Link](" Bike company is \t "+C+"\n");

public void milage(double m)

[Link](" Average Bike milage is \t "+m+"\n");

class TestInterfa

public static void main(String args[])

//Vehicle V=new Vehicle(); Abstract method will never instantiate the objects

Bike B= new Bike();

[Link](70);

[Link]("Pulsur");

[Link](45.25);

Output:

Average Bike speed is 70

Bike company is Pulsur

Average Bike milage is 45.25

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form

built-in package

user-defined package

Built-in package: java,lang,awt,javax,swing,net,io,util,sql, etc..,

User defined package: These are designed by the developer to categorize classes and packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Example of java package:

The package keyword is used to create a package in java.

// save as [Link]

package mypack;

public class Simple

public static void main(string args[])

[Link](:welcome to package”);

How to compile java package

javac -d . java filename

ex: javac -d [Link]

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. [Link] etc to run the class.

Output:Welcome to package

How to access package from another package?

There are three ways to access the package from outside the package.

import package.*;

import [Link];

fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to the
current package.

Example of package that import the packagename.*


//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

[Link]();

Output:Hello

Example of package by import [Link]

//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.A;

class B{

public static void main(String args[]){

A obj = new A();

[Link]();

Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.

Example of package by import fully qualified name

//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

[Link]();

Output:Hello

Exp: [Link]: Develop Java programs using Method overloading and method overriding.

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading

If we have to perform only one operation, having same name of the methods increases the
readability of the program

Different ways to overload the method

There are two ways to overload the method in java

By changing number of arguments

By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments

class Adder

static int add(int a,int b)


{

return a+b;

static int add(int a,int b,int c)

return a+b+c;

class TestOverloading1

public static void main(String[] args)

[Link]([Link](11,11));

[Link]([Link](11,11,11));

Output

22

33

2) Method Overloading: changing data type of arguments

class Adder{

static int add(int a, int b)

return a+b;}

static double add(double a, double b)

return a+b;}

class TestOverloading2

public static void main(String[] args)

[Link]([Link](11,11));
[Link]([Link](12.3,12.6));

Output:

22

24.9

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.

Method overriding is used for runtime polymorphism

//Java Program to illustrate the use of Java Method Overriding

//Creating a parent class.

class Vehicle{

//defining a method

void run()

[Link]("Vehicle is running");

//Creating a child class

class Bike2 extends Vehicle

//defining the same method as in the parent class

void run()

[Link]("Bike is running safely");

public static void main(String args[])


{

Bike2 obj = new Bike2();//creating object

[Link]();//calling method

Output:

Bike is running safely

Exp: 7. Develop a java program using Exception handling.

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

Checked Exception

Unchecked Exception

Error

Java Exception Keywords

Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.

// Demonstrate try block

import [Link];

public class ExceptionEx

public static void main(String args[])

try

int d=0;

int data=100/d;

[Link]("This will not be printed");

catch(ArithmeticException e)

[Link]("Division by Zero");

}
[Link]("Rest of the code...");

Output :

Exception in thread main [Link]:/ by zero

rest of the code...

Exception Handling

[Link]: Develop java programs using Exception handling (using try, catch, throw, throws and finally).

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions.

Hierarchy of Java Exception classes

The [Link] class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

Checked Exception

Unchecked Exception

Error

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known
as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords

Write a program to demonstrate Try-Catch block statements


public class ExceptionEx

public static void main(String args[])

try

int d=0;

int data=15/d;

[Link]("this will not be printed");

catch(ArithmeticException e)

[Link]("Division by Zero");

[Link]("rest of the code..");

O/P:

D:\SW>javac [Link]

D:\SW>java ExceptionEx

Division by Zero

rest of the code..

2. write a program to demonstrate multiple catch statements.

class MultiCatch

public static void main(String args[])

try

int a=[Link];

[Link]("a=" +a);

int b=42/a;

int c[]={1};
c[42]=99;

catch(ArithmeticException e)

[Link]("Divide by Zero" +e);

catch(ArrayIndexOutOfBoundsException e)

[Link]("ArrayIndexOutOfBoundsException:" +e);

[Link]("After try catch blocks");

O/P

D:\SW>javac [Link]

D:\SW>java MultiCatch

a=0

Divide by [Link]: / by zero

After try catch blocks

Java throw Exception

Java throw keyword

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message with it
that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used
to throw a custom exception. The syntax of the Java throw keyword is given below.

throw Instance i.e.,

throw new exception_class("error message");

Let's see the example of throw IOException.

throw new IOException("sorry device error");

public class TestThrow1 {

//function to check if person is eligible to vote or not

public static void validate(int age) {


if(age<18) {

//throw Arithmetic exception if not eligible to vote

throw new ArithmeticException("Person is not eligible to vote");

else {

[Link]("Person is eligible to vote!!");

//main method

public static void main(String args[]){

//calling the function

validate(13);

[Link]("rest of the code...");

Output:

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide the
exception handling code so that the normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions

Syntax of Java throws

return_type method_name() throws exception_class_name{

//method code

import [Link];

class Testthrows1

void m()throws IOException

throw new IOException("device error");//checked exception

void n()throws IOException


{

m();

void p(){

try

n();

catch(Exception e)

[Link]("exception handled");

public static void main(String args[]){

Testthrows1 obj=new Testthrows1();

obj.p();

[Link]("normal flow...");

Output:

exception handled

normal flow...

Java finally block

Java finally block is a block used to execute important code such as closing the connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it contains
all the necessary statements that need to be printed regardless of the exception occurs or not.

The finally block follows the try-catch block.

[Link]

class TestFinallyBlock {

public static void main(String args[]){

try{

//below code do not throw any exception

int data=25/5;
[Link](data);

//catch won't be executed

catch(NullPointerException e){

[Link](e);

//executed regardless of exception occurred or not

finally {

[Link]("finally block is always executed");

[Link]("rest of phe code...");

Output:

Case 2: When an exception occur but not handled by the catch block

Let's see the the fillowing example. Here, the code throws an exception however the catch block
cannot handle it. Despite this, the finally block is executed after the try block and then the program
terminates abnormally.

[Link]

public class TestFinallyBlock1{

public static void main(String args[]){

try

[Link]("Inside the try block");

//below code throws divide by zero exception

int data=25/0;

[Link](data);

//cannot handle Arithmetic type exception

//can only accept Null Pointer type exception

catch(NullPointerException e){

[Link](e);

}
//executes regardless of exception occured or not

finally {

[Link]("finally block is always executed");

[Link]("rest of the code...");

Exp: [Link]: Develop java programs using Multithreading (using Thread class and Runnable
interface, synchronization).

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

How to create a thread in Java

There are two ways to create a thread:

By extending Thread class

By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

Thread()

Thread(String name)

Thread(Runnable r)

Thread(Runnable r,String name)

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

1. Write a java program for implementation of Thread by extending Thread class

//Extending by thread class

class Multi1 extends Thread

public void run()

{
[Link]("Thread is running....");

public static void main(String args[])

Multi1 t1=new Multi1();

[Link]();

[Link]("hello");

for(int i=0;i<=5;i++)

[Link](i);

Output:

D:\java>javac [Link]

D:\java>java Multi1

hello

Thread is running....

2) Java Thread Example by implementing Runnable interface

class TestThread1 implements Runnable

public void run()

[Link]("Thread");

public static void main(String[] args)

{
Runnable r1=new TestThread1();

Thread t1=new Thread(r1,"my new thread");

[Link]();

String str=[Link]();

[Link](str);

Output:

D:\java>javac [Link]

D:\java>java TestThread1

my new thread

Thread

3) Using the Thread Synchronization

Thread synchronization in Java is a mechanism to control the access of multiple threads to shared
resources, ensuring that only one thread can access a resource at a time. This prevents race
conditions, where unpredictable outcomes occur because multiple threads try to update shared
data simultaneously, and data inconsistency, where threads read outdated or corrupted values.

import [Link].*;

class Example

void display()

Thread g=[Link]();

synchronized(this)

for(int i=0;i<=5;i++)

try

[Link](2000);

[Link]([Link]()+" "+i);

catch(InterruptedException e)
{

[Link](e);

class T extends Thread

Example e;

T(Example e)

this.e=e;

public void run()

[Link]();

class Tsynch

public static void main(String args[])

Example ex=new Example();

T t1=new T(ex);

T t2=new T(ex);

T t3=new T(ex);

[Link]();

[Link]();

[Link]();

Output:
javac [Link]

D:\java>java Tsynch

Thread-0 0

Thread-0 1

Thread-0 2

Thread-0 3

Thread-0 4

Thread-0 5

Thread-2 0

Thread-2 1

Thread-2 2

Thread-2 3

Thread-2 4

Thread-2 5

Thread-1 0

Thread-1 1

Thread-1 2

Thread-1 3

Thread-1 4

Thread-1 5

Exp:9 Aim: Develop java programs using collections (using list, set, Map and generics).

Collections in Java

The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet)

Java Generics: The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects. It makes the code stable by detecting the bugs at compile time.

Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics
force the java programmer to store a specific type of objects.

Example of Generics in Java

Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

What is Collection framework


The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It has:

Interfaces and its implementations, i.e., classes

Algorithm

java List

List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements also.
We can also store the null elements in the list.

The List interface is found in the [Link] package and inherits the Collection interface. It is a factory
of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward
directions. The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector.
The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated
since Java 5.

Write a java program to illustrate collection class with Arraylist

import [Link].*;

public class ListExample1{

public static void main(String args[]){

//Creating a List

List<String> list=new ArrayList<String>();

//Adding elements in the List

[Link]("Mango");

[Link]("Apple");

[Link]("Banana");

[Link]("Grapes");

//Iterating the List element using for-each loop

for(String fruit:list)

[Link](fruit);

Output:

Mango

Apple

Banana

Grapes

Set in Java
The set is an interface available in the [Link] package. The set interface extends the Collection
interface. An unordered collection or list in which duplicates are not allowed is referred to as
a collection interface. The set interface is used to create the mathematical set. The set interface use
collection interface's methods to avoid the insertion of the same
elements. SortedSet and NavigableSet are two interfaces that extend the set implementation.

[Link]

import [Link].*;

public class setExample{

public static void main(String[] args)

// creating LinkedHashSet using the Set

Set<String> data = new LinkedHashSet<String>();

[Link]("JavaTpoint");

[Link]("Set");

[Link]("Example");

[Link]("Set");

[Link](data);

Output:

Java Map Interface

A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:

A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

Java Map Example: Non-Generic (Old Style)

//Non-generic

import [Link].*;

public class MapExample1 {

public static void main(String[] args) {

Map<Integer, String> map = new LinkedHashMap<>();

//Adding elements to map


[Link](1,"Amit");

[Link](5,"Rahul");

[Link](2,"Jai");

[Link](6,"Amit");

//Traversing Map

Set set=[Link]();//Converting to Set so that we can traverse

Iterator itr=[Link]();

while([Link]()){

//Converting to [Link] so that we can get key and value separately

[Link] entry=([Link])[Link]();

[Link]([Link]()+" "+[Link]());

} } }

Output:

1 Amit

2 Jai

5 Rahul

6 Amit

Example of Generics in Java

Here, we are using the ArrayList class, but you can use any collection class such as ArrayList,
LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

import [Link].*;

class TestGenerics1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();

[Link]("rahul");

[Link]("jai");

//[Link](32);//compile time error

String s=[Link](1);//type casting is not required

[Link]("element is: "+s);

Iterator<String> itr=[Link]();

while([Link]()){

[Link]([Link]());

} }}
Output:

element is: jai

rahul

jai

Exp:10 write a java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired,[Use adapter classes.]

import [Link].*;

import [Link].*;

import [Link];

import [Link];

public class MouseEventDisplay extends JFrame {

private JLabel eventLabel;

public MouseEventDisplay() {

setTitle("Mouse Event Handler");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout()); // Use BorderLayout for centering

eventLabel = new JLabel("No Mouse Event", [Link]); // Center text within


JLabel

[Link](new Font("Serif", [Link], 24));

[Link]([Link]);

// Add the label to the center of the frame

add(eventLabel, [Link]);

// Add a MouseAdapter to the frame to handle mouse events

addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

[Link]("Mouse Clicked");

@Override

public void mousePressed(MouseEvent e) {

[Link]("Mouse Pressed");

}
@Override

public void mouseReleased(MouseEvent e) {

[Link]("Mouse Released");

@Override

public void mouseEntered(MouseEvent e) {

[Link]("Mouse Entered");

@Override

public void mouseExited(MouseEvent e) {

[Link]("Mouse Exited");

});

setVisible(true);

public static void main(String[] args) {

[Link](MouseEventDisplay::new);

Output:

// Create JDBC connection to MySQL Database server

import [Link].*;

public class Connect {

public static void main (String[] args)

Connection conn = null;

try{

String userName = "root";

String password = "Sandhya@20";

String url = "jdbc:mysql://localhost:3306/test";

[Link] ("[Link]").newInstance (); // This is depricated

//[Link] ("[Link]").newInstance ();// This is the newest driver

conn = [Link] (url, userName, password);


[Link] ("Database connection established");

catch (Exception e)

[Link] ("Cannot connect to database server:"+e);

finally

if (conn != null) {

try {

[Link] ();

[Link] ("Database connection terminated:");

} catch (Exception e) { /* ignore close errors */ }

Output:

//Create Table Using JDBC

import [Link];

import [Link];

import [Link];

import [Link];

public class CreateTableExample {

// Database credentials and URL

static final String DB_URL = "jdbc:mysql://localhost:3306/test";

static final String USER = "root";

static final String PASS = "Sandhya@20";

public static void main(String[] args) {

// SQL command to create a table

String sql = "CREATE TABLE EMPLOYEES " +

"(id INTEGER not NULL, " +


" first VARCHAR(255), " +

" last VARCHAR(255), " +

" age INTEGER, " +

" PRIMARY KEY ( id ))";

// Open a connection and create a statement using try-with-resources

try (Connection conn = [Link](DB_URL, USER, PASS);

Statement stmt = [Link]()) {

// Execute the DDL command

[Link](sql);

[Link]("Created table in given database successfully...");

} catch (SQLException e) {

[Link]();

Output:

//Insert Records using JDBC into a created table

import [Link];

import [Link];

import [Link];

public class InsertData {

static final String DB_URL = "jdbc:mysql://localhost/test";

static final String USER = "root";

static final String PASS = "Sandhya@20";

public static void main(String[] args) {

try(Connection conn = [Link](DB_URL, USER, PASS);

Statement stmt = [Link]();) {

// SQL for inserting a single record

//[Link]("Inserting records into the table...");

//stmt =[Link]();

String sql ="INSERT INTO Employees VALUES (10, 'Kriss', 'Kurian', 18)";

[Link](sql);

sql = "INSERT INTO Employees VALUES (11, 'Enrique', 'John', 25)";


[Link](sql);

sql= "INSERT INTO Employees values (12, 'Taylor', 'Swift', 30)";

[Link](sql);

sql= "INSERT INTO Employees VALUES(13, 'Linkin', 'Park', 28)";

[Link](sql);

[Link]("Inserted records into the table...");

/*String sql = "INSERT INTO EMPLOYEES (id, first, last, age) " +

"VALUES (100, 'John', 'Doe', 30)";

[Link](sql);

[Link]("Inserted record into the table...");*/

} catch (Exception e) {

[Link]();

Output:

//Updating a Record using JDBC in the given table

import [Link];

import [Link];

import [Link];

public class UpdateData {

static final String DB_URL = "jdbc:mysql://localhost/test";

static final String USER = "root";

static final String PASS = "Sandhya@20";

public static void main(String[] args) {

try(Connection conn = [Link](DB_URL, USER, PASS);

Statement stmt = [Link]();) {

// SQL for inserting a single record

String sql ="UPDATE EMPLOYEES SET age = 26, first ='Sireesha', last = 'paga' WHERE id =11";

[Link](sql);

[Link]("updated record into the table...");

} catch (Exception e) {
[Link]();

Output:

import [Link].*;

public class ReadRecords {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "Sandhya@20";

String query = "SELECT id, first, last,age FROM employees";

// Try-with-resources ensures objects are closed automatically

try (Connection con = [Link](url, user, password);

Statement stmt = [Link]();

ResultSet rs = [Link](query)) {

while ([Link]()) {

int id = [Link]("id");

String first = [Link]("first");

String last = [Link]("last");

String age = [Link]("age");

[Link](id + " | " + first + " | " + last + "|" + age);

} catch (SQLException e) {

[Link]();

Output:

import [Link];

import [Link];

import [Link];

import [Link];
public class DeleteRecord {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/test";

String user = "root";

String password = "Sandhya@20";

String sql = "DELETE FROM employees WHERE id = 101";

// Try-with-resources automatically closes resources

try (Connection conn = [Link](url, user, password);

PreparedStatement pstmt = [Link](sql)) {

// Bind value to the placeholder (?)

// [Link](1, 13);

int rowsDeleted = [Link]();

if (rowsDeleted > 0) {

[Link]("Successful deletion of " + rowsDeleted + " record(s).");

} else {

[Link]("No records found with the specified ID.");

} catch (SQLException e) {

[Link]();

Additional programs

this keyword

In Java, the this keyword is a reference variable that refers to the current object. It is primarily used
within instance methods or constructors to access members of the object that is currently being
executed.

Write a program using this keyword

public class ThisEx

int x;

public ThisEx(int x)

{
this.x=x;

public static void main(String args[])

ThisEx obj=new ThisEx(4);

[Link]("value of x =" +obj.x);

Output:

D:\java>javac [Link]

D:\java>java ThisEx

value of x =4

super keywod

In Java, the super keyword is a reference variable used by a subclass to refer to its immediate
parent class. It serves as a bridge to access members (fields, methods, and constructors) of the
superclass that might be hidden or overridden

write a java program to access super class variable (Members)

class Bike

String name="TVS Jupiter";

void display()

[Link]("\n it is a two wheeler");

[Link]("\n my vechile name is:" +name);

class Car extends Bike

String name="Creta 2022";

void display()

[Link]("\n it is a four wheeler");

[Link]("\n my vechile name is:" +name);


[Link]("\n my vechile name is:" +[Link]);

class TestSuper

public static void main(String args[])

Car C =new Car();

[Link]();

Output:

D:\java>javac [Link]

D:\java>java TestSuper

it is a four wheeler

my vechile name is:Creta 2022

my vechile name is:TVS Jupiter

write a java program to access super class Method

class Bike

String name="Harley Davidson";

void display()

[Link]("\n it is a two wheeler");

[Link]("\n my vechile name is:" +name);

class Car extends Bike

String name="KIA";

void display()

[Link]();
[Link]("\n it is a four wheeler");

[Link]("\n my vechile name is:" +name);

class TestSuper1

public static void main(String args[])

Car C =new Car();

[Link]();

Output:

D:\java>javac [Link]

D:\java>java TestSuper1

it is a two wheeler

my vechile name is:Harley Davidson

it is a four wheeler

my vechile name is:KIA

write a java program to access super class constructor

//super is used to invoke parent class constructor

class Bike

Bike()

[Link]("\n Bike is a two wheeler");

class Car extends Bike

Car(String n, String B)

{
super(); //it is called super class constructor

[Link]("\n my vehicle name is\t"+n+"\n and its brand is\t"+B);

void display()

[Link]("\n This program is to understand super keyword in constructors\t");

class TestSuper2

public static void main(String args[])

Car C=new Car("Innova crysta", "Toyata");

[Link]();

D:\java>javac [Link]

D:\java>java TestSuper2

Bike is a two wheeler

my vehicle name is Innova crysta

and its brand is Toyata

This program is to understand super keyword in constructors

/*constructor

constructor in Java is a special method that is used to initialize objects.

The constructor is called when an object of a class is created.

It can be used to set initial values for object attributes:

rules for defining a constructor:

class name and constructor name must be same.

constructors do not have a return type , not even void is needed

if there are no constructors by default constructor is called by JVM .

cannot be inherited by subclass , but they cannot be accessed using the super key word

they can use acess modifiers (public, private, protection or default )but cannot be abstract,final
static or synchronized.
Type of constructors

Default constructor(Implicit):- if we do not define any constructors in our class the java compiler
automatically provides a public no-argument constructor. this implicit constructor initializes instance
variales with default values(ex: 0 for int, null for objects, false for boolean)

no argument constructor(Explicit):-

Parameterized constructor

the variable are declared inside a class instance variabless*/

//default constructor

class Rectangle

double length;

double breadth;

Rectangle() //no argument constructor

length=20;

breadth=35;

double area()

return length*breadth;

public static void main(String args[])

Rectangle obj1=new Rectangle();

Rectangle obj2=new Rectangle();

[Link]("Area of object1 is:" +[Link]());

[Link]("Area of object2 is:" +[Link]());

Output:

D:\java>javac [Link]

D:\java>java Rectangle

Area of object1 is:700.0


Area of object2 is:700.0

//Parameterized constructor

class Rectangle1

double length;

double breadth;

Rectangle1(double l , double b) //parameterized constructor

length=l;

breadth=b;

double area()

return length*breadth;

public static void main(String args[])

Rectangle1 obj1=new Rectangle1(2.3,4.5);

Rectangle1 obj2=new Rectangle1(5.2,9.5);

[Link]("Area of object1 is:" +[Link]());

[Link]("Area of object2 is:" +[Link]());

//No constructor

class Rectangle2

double length;

double breadth;

double area()

return length*breadth;

public static void main(String args[])


{

Rectangle2 obj1=new Rectangle2();

[Link]("Area of object2 is:" +[Link]());

Output:

Client server Program

import [Link].*;

import [Link].*;

public class Server {

public static void main(String[] args) {

int port = 12345; // Port for communication

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

[Link]("Server started. Waiting for a client on port " + port + "...");

Socket clientSocket = [Link](); // Accept client connection

[Link]("Client connected: " + [Link]());

// Prepare to receive the file

DataInputStream dis = new DataInputStream([Link]());

String fileName = [Link](); // Read filename sent by client

[Link]("Receiving file: " + fileName);

FileOutputStream fos = new FileOutputStream("received_" + fileName); // Output stream to save


file

byte[] buffer = new byte[4096];

int bytesRead;

while ((bytesRead = [Link](buffer)) != -1) {

[Link](buffer, 0, bytesRead);

[Link]("File received successfully.");

[Link]();

[Link]();

[Link]();

} catch (IOException e) {

[Link]();
}

Client program

import [Link].*;

import [Link].*;

public class Client {

public static void main(String[] args) {

String serverAddress = "localhost"; // Server IP address or hostname

int port = 12345; // Port for communication

String filePath = "send_this_file.txt"; // Path to the file to send

try (Socket socket = new Socket(serverAddress, port)) {

[Link]("Connected to server: " + serverAddress + ":" + port);

File fileToSend = new File(filePath);

if (![Link]()) {

[Link]("Error: File not found at " + filePath);

return;

// Prepare to send the file

DataOutputStream dos = new DataOutputStream([Link]());

[Link]([Link]()); // Send filename to server

FileInputStream fis = new FileInputStream(fileToSend);

byte[] buffer = new byte[4096];

int bytesRead;

while ((bytesRead = [Link](buffer)) != -1) {

[Link](buffer, 0, bytesRead);

[Link]("File sent successfully.");

[Link]();

[Link]();

} catch (IOException e) {

[Link]();
}

You might also like