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

Java Assignment

Uploaded by

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

Java Assignment

Uploaded by

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

A D Patel Institute Of Technology

(A Constituent College of CVM University)


New V. V. Nagar

COMPUTER SCIENCE AND DESIGN DEPARTMENT

Submitted By
Harsh Jha

Name of Student: Jha HarshKumar R.R


Enrollment No: 12302130603006

SEMINAR (102040404)
A.Y. 2022-23 EVEN TERM
1 Inner class

In Java, inner class refers to the class that is declared inside class or interface
which were mainly introduced, to sum up, same logically relatable classes as Java
is purely object-oriented so bringing it closer to the real world. Now geeks you
must be wondering why they were introduced?
There are certain advantages associated with inner classes are as follows:
• Making code clean and readable.
• Private methods of the outer class can be accessed, so bringing a new
dimension and making it closer to the real world.
• Optimizing the code module.

Types of Inner Classes


There are basically four types of inner classes in java.
1. Nested Inner Class
2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes
Let us discuss each of the above following types sequentially in-depth alongside
a clean java program which is very crucial at every step as it becomes quite
tricky as we adhere forwards.

Type 1: Nested Inner Class


It can access any private instance variable of the outer class. Like any other
instance variable, we can have access modifier private, protected, public, and
default modifier. Like class, an interface can also be nested and can have access
specifiers.

Example
• Java

// Java Program to Demonstrate Nested class


// Class 1
// Helper classes
class Outer {

// Class 2
// Simple nested inner class
class Inner {

// show() method of inner class


public void show()
{

// Print statement
System.out.println("In a nested class method");
}
}
}

// Class 2
// Main class
class Main {

// Main driver method


public static void main(String[] args)
{

// Note how inner class object is created inside


// main()
Outer.Inner in = new Outer().new Inner();

// Calling show() method over above object created


in.show();
}
}

Output
In a nested class method
Type 2: Method Local Inner Classes
Inner class can be declared within a method of an outer class which we will be
illustrating in the below example where Inner is an inner class in outerMethod().
Example
• Java

// Java Program to Illustrate Inner class can be


// declared within a method of outer class

// Class 1
// Outer class
class Outer {

// Method inside outer class


void outerMethod()
{

// Print statement
System.out.println("inside outerMethod");

// Class 2
// Inner class
// It is local to outerMethod()
class Inner {

// Method defined inside inner class


void innerMethod()
{

// Print statement whenever inner class is


// called
System.out.println("inside innerMethod");
}
}

// Creating object of inner class


Inner y = new Inner();

// Calling over method defined inside it


y.innerMethod();
}
}
// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of outer class inside main()


// method
Outer x = new Outer();

// Calling over the same method


// as we did for inner class above
x.outerMethod();
}
}

Output
inside outerMethod
inside innerMethod
Type 3: Static Nested Classes
Static nested classes are not technically inner classes. They are like a static
member of outer class.
Example
• Java

// Java Program to Illustrate Static Nested Classes

// Importing required classes


import java.util.*;

// Class 1
// Outer class
class Outer {

// Method
private static void outerMethod()
{

// Print statement
System.out.println("inside outerMethod");
}

// Class 2
// Static inner class
static class Inner {

public static void display()


{

// Print statement
System.out.println("inside inner class Method");

// Calling method inside main() method


outerMethod();
}
}
}

// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Calling method static display method rather than an instance of that class
Outer.Inner.display();
}
}

Output
inside inner class Method
inside outerMethod
Type 4: Anonymous Inner Classes
Anonymous inner classes are declared without any name at all. They are created
in two ways.
As a subclass of the specified type

• As an implementer of the specified interface
Way 1: As a subclass of the specified type
Example:
• Java

// Java Program to Illustrate Anonymous Inner classes


// Declaration Without any Name
// As a subclass of the specified type

// Importing required classes


import java.util.*;

// Class 1
// Helper class
class Demo {

// Method of helper class


void show()
{
// Print statement
System.out.println(
"i am in show method of super class");
}
}

// Class 2
// Main class
class Flavor1Demo {

// An anonymous class with Demo as base class


static Demo d = new Demo() {
// Method 1
// show() method
void show()
{
// Calling method show() via super keyword
// which refers to parent class
super.show();

// Print statement
System.out.println("i am in Flavor1Demo class");
}
};

// Method 2
// Main driver method
public static void main(String[] args)
{
// Calling show() method inside main() method
d.show();

}
}

Output
i am in show method of super class
i am in Flavor1Demo class

In Java, an inner class is a class that is defined inside another class. An inner class
can access the members of the outer class, including private members, and it
can be used to implement callbacks and event handlers. There are four types of
inner classes in Java:
Member Inner Class: It is a non-static class that is defined at the member level of
a class. It has access to all the members of the outer class, including private
members.
Local Inner Class: It is a class that is defined inside a method or a block of code.
It has access to the final variables of the method or block in which it is defined.
Anonymous Inner Class: It is a class that is defined inline and has no name. It is
used to implement interfaces or extend classes without creating a separate
class.
Static Nested Class: It is a static class that is defined inside another class. It does
not have access to the non-static members of the outer class.
Inner classes have several advantages:
Encapsulation: Inner classes can be used to encapsulate implementation details
of a class, making the code more modular and maintainable.
Access Control: Inner classes can access private members of the outer class,
allowing for more precise control over the visibility of members.
Callbacks and Event Handlers: Inner classes can be used to implement callbacks
and event handlers, making it easier to handle events in graphical user
interfaces.
Code Organization: Inner classes can be used to organize code by grouping
related classes together.

Program

• Java

public class OuterClass {


private int outerVar;

public OuterClass(int var) {


outerVar = var;
}

public void outerMethod() {


System.out.println("This is an outer method");
}

// Inner class
public class InnerClass {
private int innerVar;

public InnerClass(int var) {


innerVar = var;
}

public void innerMethod() {


System.out.println("This is an inner method");
}

public void accessOuterVar() {


System.out.println("Outer variable from inner class: " + outerVar);
}
}

public static void main(String[] args) {


// Create an instance of the outer class
OuterClass outer = new OuterClass(10);

// Create an instance of the inner class


OuterClass.InnerClass inner = outer.new InnerClass(20);
// Access the inner class methods
inner.innerMethod();
inner.accessOuterVar();
}
}

Output
This is an inner method
Outer variable from inner class: 10

The benefits of using inner classes in Java are:

Encapsulation: Inner classes can access private variables and methods of the
outer class. This helps to achieve encapsulation and improves code readability.
Code Organization: Inner classes allow you to group related code together in
one place. This makes your code easier to understand and maintain.
Better Access Control: Inner classes can be declared as private, which means
that they can only be accessed within the outer class. This provides better
access control and improves code security.
Callbacks: Inner classes are often used for implementing callbacks in event-
driven programming. They provide a convenient way to define and implement a
callback function within the context of the outer class.
Polymorphism: Inner classes can be used to implement polymorphism. You can
define a class hierarchy within the outer class and then create objects of the
inner classes that implement the different subclasses.
Reduced Code Complexity: Inner classes can reduce the complexity of your code
by encapsulating complex logic and data structures within the context of the
outer class.
Overall, the use of inner classes can lead to more modular, maintainable, and
flexible code.
2 Socket programming

This article describes a very basic one-way Client and Server setup where a Client
connects, sends messages to the server and the server shows them using a socket
connection. There’s a lot of low-level stuff that needs to happen for these things
to work but the Java API networking package (java.net) takes care of all of that,
making network programming very easy for programmers.
Client-Side Programming
Establish a Socket Connection
To connect to another machine we need a socket connection. A socket
connection means the two machines have information about each other’s
network location (IP Address) and TCP port. The java.net.Socket class represents
a Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
• The first argument – IP address of Server. ( 127.0.0.1 is the IP address
of localhost, where code will run on the single stand-alone machine).
• The second argument – TCP Port. (Just a number representing which
application to run on a server. For example, HTTP runs on port 80. Port
number can be from 0 to 65535)
Communication
To communicate over a socket connection, streams are used to both input and
output the data.
Closing the connection
The socket connection is closed explicitly once the message to the server is sent.
In the program, the Client keeps reading input from a user and sends it to the
server until “Over” is typed.
Java Implementation
• Java

// A Java program for a Client


import java.io.*;
import java.net.*;

public class Client {


// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");

// takes input from terminal


input = new DataInputStream(System.in);

// sends output to the socket


out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}

// string to read message from input


String line = "";

// keep reading until "Over" is input


while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}

// close the connection


try {
input.close();
out.close();
socket.close();
}
catch (IOException i) {
System.out.println(i);
}
}

public static void main(String args[])


{
Client client = new Client("127.0.0.1", 5000);
}
}

Server Programming
Establish a Socket Connection
To write a server application two sockets are needed.
• A ServerSocket which waits for the client requests (when a client
makes a new Socket())
• A plain old Socket to use for communication with the client.
Communication
getOutputStream() method is used to send the output through the socket.
Close the Connection
After finishing, it is important to close the connection by closing the socket as
well as input/output streams.
• Java

// A Java program for a Server


import java.net.*;
import java.io.*;

public class Server


{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

// constructor with port


public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");

System.out.println("Waiting for a client ...");


socket = server.accept();
System.out.println("Client accepted");

// takes input from the client socket


in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

String line = "";

// reads message from client until "Over" is sent


while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);

}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");

// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}

public static void main(String args[])


{
Server server = new Server(5000);
}
}

Important Points
• Server application makes a ServerSocket on a specific port which is
5000. This starts our Server listening for client requests coming in for
port 5000.
• Then Server makes a new Socket to communicate with the client.
socket = server.accept()
•The accept() method blocks(just sits there) until a client connects to the
server.
• Then we take input from the socket using getInputStream() method.
Our Server keeps receiving messages until the Client sends “Over”.
• After we’re done we close the connection by closing the socket and the
input stream.
• To run the Client and Server application on your machine, compile both
of them. Then first run the server application and then run the Client
application.
To run on Terminal or Command Prompt
Open two windows one for Server and another for Client
1. First run the Server application as,
$ java Server
Server started
Waiting for a client …
2. Then run the Client application on another terminal as,
$ java Client
It will show – Connected and the server accepts the client and shows,
Client accepted
3. Then you can start typing messages in the Client window. Here is a sample
input to the Client
Hello
I made my first socket connection
Over
Which the Server simultaneously receives and shows,
Hello
I made my first socket connection
Over
Closing connection
Notice that sending “Over” closes the connection between the Client and the
Server just like said before.
3 File handling
In Java, with the help of File Class, we can work with files. This File Class is inside
the java.io package. The File class can be used by creating an object of the class
and then specifying the name of the file.
Why File Handling is Required?
• File Handling is an integral part of any programming language as file
handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
• In simple words, file handling means reading and writing data to a file.

• Java

// Importing File Class


import java.io.File;

class GFG {
public static void main(String[] args)
{

// File name specified


File obj = new File("myfile.txt");
System.out.println("File Created!");
}
}

Output
File Created!
In Java, the concept Stream is used in order to perform I/O operations on a file.
So at first, let us get acquainted with a concept known as Stream in Java.
Streams in Java
• In Java, a sequence of data is known as a stream.
• This concept is used to perform I/O operations on a file.
• There are two types of streams :
1. Input Stream:
The Java InputStream class is the superclass of all input streams. The input
stream is used to read data from numerous input devices like the keyboard,
network, etc. InputStream is an abstract class, and because of this, it is not
useful by itself. However, its subclasses are used to read data.
There are several subclasses of the InputStream class, which are as follows:
1. AudioInputStream
2. ByteArrayInputStream
3. FileInputStream
4. FilterInputStream
5. StringBufferInputStream
6. ObjectInputStream
Creating an InputStream
// Creating an InputStream
InputStream obj = new FileInputStream();
Here, an input stream is created using FileInputStream.

2. Output Stream:
The output stream is used to write data to numerous output devices like the
monitor, file, etc. OutputStream is an abstract superclass that represents an
output stream. OutputStream is an abstract class and because of this, it is not
useful by itself. However, its subclasses are used to write data.
There are several subclasses of the OutputStream class which are as follows:
1. ByteArrayOutputStream
2. FileOutputStream
3. StringBufferOutputStream
4. ObjectOutputStream
5. DataOutputStream
6. PrintStream
Creating an OutputStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Here, an output stream is created using FileOutputStream
Based on the data type, there are two types of streams :
1. Byte Stream:
This stream is used to read or write byte data. The byte stream is again
subdivided into two types which are as follows:
• Byte Input Stream: Used toread byte data from different devices.
• Byte Output Stream: Used to write byte data to different devices.
2. Character Stream:
This stream is used to read or write character data. Character stream is again
subdivided into 2 types which are as follows:
• Character Input Stream: Used to read character data from different
devices.
• Character Output Stream: Used to
write character data to different devices.
Owing to the fact that you know what a stream is, let’s polish up File Handling in
Java by further understanding the various methods that are useful for
performing operations on the files like creating, reading, and writing files.
File operations in Java
The following are the several operations that can be performed on a file in Java :
• Create a File
• Read from a File
• Write to a File
• Delete a File
Now let us study each of the above operations in detail.
1. Create a File
• In order to create a file in Java, you can use the createNewFile()
method.
• If the file is successfully created, it will return a Boolean value true and
false if the file already exists.
Following is a demonstration of how to create a file in Java :

• Java

// Import the File class


import java.io.File;

// Import the IOException class to handle errors


import java.io.IOException;

public class GFG {


public static void main(String[] args)
{

try {
File Obj = new File("myfile.txt");
if (Obj.createNewFile()) {
System.out.println("File created: "
+ Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}

Output
An error has occurred.

2. Read from a File: We will use the Scanner class in order to read contents from
a file. Following is a demonstration of how to read contents from a file in Java :
• Java

// Import the File class


import java.io.File;

// Import this class for handling errors


import java.io.FileNotFoundException;

// Import the Scanner class to read content from text files


import java.util.Scanner;

public class GFG {


public static void main(String[] args)
{
try {
File Obj = new File("myfile.txt");
Scanner Reader = new Scanner(Obj);
while (Reader.hasNextLine()) {
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}

Output
An error has occurred.
3. Write to a File: We use the FileWriter class along with its write() method in
order to write some text to the file. Following is a demonstration of how to
write text to a file in Java :
• Java

// Import the FileWriter class


import java.io.FileWriter;

// Import the IOException class for handling errors


import java.io.IOException;

public class GFG {


public static void main(String[] args)
{
try {
FileWriter Writer
= new FileWriter("myfile.txt");
Writer.write(
"Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}

Output
An error has occurred.
4. Delete a File: We use the delete() method in order to delete a file. Following
is a demonstration of how to delete a file in Java :
• Java

// Import the File class


import java.io.File;

public class GFG {


public static void main(String[] args)
{
File Obj = new File("myfile.txt");
if (Obj.delete()) {
System.out.println("The deleted file is : "
+ Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}

Output
Failed in deleting the file.
4 Generics
Generics means parameterized types. The idea is to allow type (Integer, String, …
etc., and user-defined types) to be a parameter to methods, classes, and
interfaces. Using Generics, it is possible to create classes that work with
different data types. An entity such as class, interface, or method that operates
on a parameterized type is a generic entity.

Why Generics?

The Object is the superclass of all other classes, and Object reference can refer to
any object. These features lack type safety. Generics add that type of safety
feature. We will discuss that type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example, classes like
HashSet, ArrayList, HashMap, etc., use generics very well. There are some
fundamental differences between the two approaches to generic types.

Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns some value
after performing a task. It is exactly like a normal function, however, a generic
method has type parameters that are cited by actual type. This allows the
generic method to be used in a more general way. The compiler takes care of
the type of safety which enables programmers to code easily since they do not
have to perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class.
The only difference is that it contains a type parameter section. There can be
more than one type of parameter, separated by a comma. The classes, which
accept one or more parameters, ?are known as parameterized classes or
parameterized types.

Generic Class

Like C++, we use <> to specify parameter types in generic class creation. To
create objects of a generic class, we use the following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()

// Java program to show working of user defined


// Generic classes

// We use < > to specify Parameter type


class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}

Output
15
GeeksForGeeks

Generic Functions:

We can also write generic functions that can be called with different types of
arguments based on the type of arguments passed to the generic method. The
compiler handles each method.

• Java
// Java program to show working of user defined
// Generic functions

class Test {
// A Generic method example
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getName()
+ " = " + element);
}

// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);

// Calling generic method with String argument


genericDisplay("GeeksForGeeks");

// Calling generic method with double argument


genericDisplay(1.0);
}
}

Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0

Generics Work Only with Reference Types:

When we declare an instance of a generic type, the type argument passed to the
type parameter must be a reference type. We cannot use primitive data types
like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type
wrappers to encapsulate a primitive type.
But primitive type arrays can be passed to the type parameter because arrays
are reference types.
ArrayList<int[]> a = new ArrayList<>();

Generic Types Differ Based on Their Type Arguments:

Consider the following Java code.

• Java

// Java program to show working


// of user-defined Generic classes

// We use < > to specify Parameter type


class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
iObj = sObj; // This results an error
}
}

Output:
error:
incompatible types:
Test cannot be converted to Test
Even though iObj and sObj are of type Test, they are the references to different
types because their type parameters differ. Generics add type safety through
this and prevent errors.

Type Parameters in Java Generics

The type parameters naming conventions are important to learn generics


thoroughly. The common type parameters are as follows:
• T – Type
• E – Element
• K – Key
• N – Number
• V – Value

Advantages of Generics:

Programs that use Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use it for any
type we want.
2. Type Safety: Generics make errors to appear compile time than at run time
(It’s always better to know problems in your code at compile time rather than
making your code fail at run time). Suppose you want to create an ArrayList that
store name of students, and if by mistake the programmer adds an integer
object instead of a string, the compiler allows it. But, when we retrieve this data
from ArrayList, it causes problems at runtime.
3. Individual Type Casting is not needed: If we do not use generics, then, in the
above example, every time we retrieve data from ArrayList, we have to typecast
it. Typecasting at every retrieval operation is a big headache. If we already know
that our list only holds string data, we need not typecast it every time.
4. Generics Promotes Code Reusability: With the help of generics in Java, we can
write code that will work with different types of data. For example,
Let’s say we want to Sort the array elements of various data types like int, char,
String etc.
Basically we will be needing different functions for different data types.
For simplicity, we will be using Bubble sort.
But by using Generics, we can achieve the code reusability feature.
5. Implementing Generic Algorithms: By using generics, we can implement
algorithms that work on different types of objects, and at the same, they are
type-safe too.

You might also like