Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Java Notes

The document provides an overview of Java programming concepts, including classes, objects, inheritance, polymorphism, error types, exception handling, stream classes, file handling, and networking protocols like TCP and UDP. It explains the fundamental principles of object-oriented programming and how Java handles errors and exceptions. Additionally, it covers socket programming for communication between applications over networks.

Uploaded by

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

Java Notes

The document provides an overview of Java programming concepts, including classes, objects, inheritance, polymorphism, error types, exception handling, stream classes, file handling, and networking protocols like TCP and UDP. It explains the fundamental principles of object-oriented programming and how Java handles errors and exceptions. Additionally, it covers socket programming for communication between applications over networks.

Uploaded by

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

Java

Java Classes
• A class in Java is a set of objects which shares common characteristics/
behavior and common properties/ attributes. It is a user-defined blueprint or
prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.
• Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
4. Data member
5. Method
6. Constructor
7. Nested Class
8. Interface
Java Objects
• An object in Java is a basic unit of Object-Oriented
Programming and represents real-life entities. Objects are the
instances of a class that are created to use the attributes and
methods of a class. A typical Java program creates many
objects, which as you know, interact by invoking methods. An
object consists of :
1.State: It is represented by attributes of an object. It also reflects
the properties of an object.
2.Behavior: It is represented by the methods of an object. It also
reflects the response of an object with other objects.
3.Identity: It gives a unique name to an object and enables one
object to interact with other objects.
Example Dog: Identity- Name of Dog; States/Attributes: Breed,
color; Behavior: Bark, eat.
Inheritance
• Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviours 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.

Need of Inheritance

• Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.

• Method Overriding: Method Overriding is achievable only through Inheritance. It is one


of the ways by which Java achieves Run Time Polymorphism.

• Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.
Terminologies Used in Java Inheritance
• Class: Class is a set of objects which shares common characteristics/ behavior
and common properties/ attributes. Class is not a real-world entity. It is just a
template or blueprint or prototype from which objects are created.

• Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).

• Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can add
its own fields and methods in addition to the superclass fields and methods.

• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to


create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.
Polymorphism
• Polymorphism is considered one of the important features of Object-

Oriented Programming. Polymorphism allows us to perform a single

action in different ways. In other words, polymorphism allows you to

define one interface and have multiple implementations. The word “poly”

means many and “morphs” means forms, So it means many forms.

• Real-life Illustration of Polymorphism in Java: A person at the same time

can have different characteristics. Like a man at the same time is a

father, a husband, and an employee. So the same person possesses

different behaviors in different situations. This is called polymorphism.


Errors in Java
• Error is an illegal operation performed by the user which results in
the abnormal working of the program. Programming errors often
remain undetected until the program is compiled or executed. Some
of the errors inhibit the program from getting compiled or executed.
Thus errors should be removed before compiling and executing.

Types of error-

• Runtime error

• Compile-time error

• Logical error

• Syntax error
Run-time Error
• Run Time errors occur during the execution of the program. Sometimes
these are discovered when the user enters an invalid data or data which
is not relevant.

For example: if the user inputs a data of string format when the computer is
expecting an integer, there will be a runtime error.

• Runtime errors occur when a program does not contain any syntax
errors but asks the computer to do something that the computer is
unable to reliably do.

For example: Runtime Error caused by dividing by zero

• To handle the error during the run time we can put our error code inside
the try block and catch the error inside the catch block.
Compile time Error
• Compile Time Errors are those errors which prevent the code from running
because of an incorrect syntax such as a missing semicolon at the end of a
statement or a missing bracket, class not found, etc.

• Type errors, for example, occur when there is a mismatch between the expected
data type and the actual data type used in the code. These errors are detected by
the java compiler and an error message is displayed on the screen while
compiling.

• These kind of errors are easy to spot and rectify because the java compiler finds
them for you. The compiler will tell you which piece of code in the program got in
trouble and its best guess as to what you did wrong.

• Usually, the compiler indicates the exact line where the error is, or sometimes the
line just before it. Compile-time errors prevent the program from being
successfully compiled into an executable form.

• Example 1: Misspelled variable name or method names


Logical Error
• A logic error is when your program compiles and executes, but does the
wrong thing or returns an incorrect result or no output when it should be
returning an output.

• These errors are detected neither by the compiler nor by JVM. The Java
system has no idea what your program is supposed to do, so it provides
no additional information to help you find the error.

• Logical errors are also called Semantic Errors. These errors are caused
due to an incorrect idea or concept used by a programmer while coding.

For example, if a programmer accidentally adds two variables when he or


she meant to divide them, the program will give no error and will execute
successfully but with an incorrect result.
Syntax Error
• A syntax error in programming refers to a mistake in the structure of the
code that violates the rules and grammar of the programming language.

• These errors occur during the compilation phase when the compiler
attempts to translate the human-readable code into machine-executable
instructions.

• Common syntax errors include missing semicolons, mismatched


parentheses, or incorrect usage of keywords.

• int x, y;

• x = 10 // missing semicolon (;)

• z = x + y; // z is undefined, y in uninitialized.
Exception Handling
• Exception Handling in Java is one of the effective means to handle runtime
errors so that the regular flow of the application can be preserved.

• Java Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

• The Object Orientation mechanism has provided the following techniques to


work with exception:
I. try
II. catch
III. throw
IV. throws
V. finally
try & catch

Try block

• The try block contains a set of statements where an exception can occur.

• Whenever we write a statement and if the statement is error suspection


statement or risky code then put that code inside the try block.

Catch block

• The catch block is used to handle the uncertain condition of a try block.

• A try block is always followed by a catch block, which handles the


exception that occurs in the associated try block.
Throw & throws
Throw
• Java throw keyword is used to throw an exception explicitly in the code,
inside the function or the block of code.
• The throw keyword is followed by an instance of Exception to be thrown.
throw is used within the method.
• We are allowed to throw only one exception at a time i.e. we cannot
throw multiple exceptions.
Throws
• Java throws keyword is used in the method signature to declare an
exception which might be thrown by the function while the execution of
the code.
• The throws keyword is followed by class names of Exceptions to be
thrown. throws is used with the method signature.
• We can declare multiple exceptions using throws keyword that can be
thrown by the method. For example, main() throws IOException,
SQLException.
Stream classes
• In Java, stream classes are used for input and output operations. They
provide a way to read from or write to a data source or destination.

• Stream classes are broadly categorized into two types: byte stream
classes and character stream classes.

Byte Stream Classes:

•Byte stream classes deal with raw binary data, making them suitable for

handling all kinds of files, including images, videos, and non-text files.

•InputStream and OutputStream are the base classes for byte streams.

Example: FileInputStream and FileOutputStream are byte stream classes

that read and write bytes to and from files.


Stream classes

Character Stream Classes:

•Character stream classes are designed for handling character data,

making them suitable for text files.

•Reader and Writer are the base classes for character streams.

Example: FileReader and FileWriter are character stream classes that read

and write characters to and from files.


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.

• 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.

// Importing File Class


import java.io.File;

class CreateFile {
public static void main(String[] args)
{
// File name specified
File f = new File(“path\\myfile.txt");
System.out.println("File Created!");
}
}
TCP (Transmission Control Protocol)
1. Connection-Oriented Protocol:
TCP is a connection-oriented protocol, establishing a reliable and
ordered connection between two devices before data transfer.
2. Reliability and Flow Control:
TCP ensures reliable, error-checked delivery of data and implements
flow control mechanisms to manage data transmission speed.
3. Acknowledgment Mechanism:
It uses acknowledgment and retransmission mechanisms to guarantee
the delivery of data and handle lost or corrupted packets.
4. Ordered Data Transmission:
TCP maintains the order of data packets, ensuring that they are
received in the same order they were sent.
5. Byte Stream Communication:
TCP operates on a byte stream, treating data as a continuous stream
without explicit message boundaries.
UDP (User Datagram Protocol)
1. Connectionless:
UDP is connectionless, offering a simple and lightweight communication
model.
2. Unreliable:
UDP does not guarantee delivery or order of packets. It is considered an
unreliable protocol.
3. Packet-Oriented:
Data is sent in separate packets without a continuous stream. Each packet is
independent.
4. No Flow Control:
UDP lacks built-in flow control mechanisms, allowing data to be transmitted at
the maximum possible rate.
5. No Connection Setup:
There is no explicit connection setup phase in UDP, making it faster for certain
applications.
6. Broadcast and Multicast:
UDP supports broadcast and multicast communication.
Socket Programming
• Java Socket programming is used for communication between the applications
running on different JRE.
• Java Socket programming can be connection-oriented or connection-less.
• Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
• in socket programming, programs can send and receive data over the internet or
a local network. A "socket" acts like a telephone, enabling communication
between different applications.
• One program creates a socket (like making a call), and another program accepts
the connection (like answering the call). Once connected, they can exchange
messages.

The client in socket programming must know two information:


1. IP Address of Server, and
2. Port number.

You might also like