Java Assignment
Java Assignment
Submitted By
Harsh Jha
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.
Example
• Java
// Class 2
// Simple nested inner class
class Inner {
// Print statement
System.out.println("In a nested class method");
}
}
}
// Class 2
// Main class
class Main {
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
// Class 1
// Outer class
class Outer {
// Print statement
System.out.println("inside outerMethod");
// Class 2
// Inner class
// It is local to outerMethod()
class Inner {
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
// 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 {
// Print statement
System.out.println("inside inner class Method");
// Class 3
// Main class
class GFG {
// 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
// Class 1
// Helper class
class Demo {
// Class 2
// Main class
class Flavor1Demo {
// 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
// Inner class
public class InnerClass {
private int innerVar;
Output
This is an inner method
Outer variable from inner class: 10
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
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
}
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);
}
}
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
class GFG {
public static void main(String[] args)
{
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
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
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
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
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.
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>()
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);
Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0
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<>();
• Java
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.
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.