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

Java notes

This document provides an overview of Java programming, covering its history, data types, operators, control statements, and object-oriented programming concepts. It explains the structure of a Java program, the role of the Java Virtual Machine (JVM), and details various operators and control flow statements like loops and branching. Additionally, it discusses classes, objects, constructors, inheritance, and string manipulation in Java.

Uploaded by

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

Java notes

This document provides an overview of Java programming, covering its history, data types, operators, control statements, and object-oriented programming concepts. It explains the structure of a Java program, the role of the Java Virtual Machine (JVM), and details various operators and control flow statements like loops and branching. Additionally, it discusses classes, objects, constructors, inheritance, and string manipulation in Java.

Uploaded by

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

Java notes

Introduction to Java

History of java

Data types

Comments

Variables

Keywords in notes book

C++ vs Java
Explain jvm
JVM(Java Virtual Machine) runs Java applications as a run-time
engine.

Java applications are called WORA (Write Once Run Anywhere).


This means a programmer can develop Java code on one system
and expect it to run on any other Java-enabled system without
any adjustment. This is all possible because of JVM.

These steps together describe the whole JVM.


Q. Structure of java program
Let's see which elements are included in the structure of a Java program. A typical structure
of a Java program contains the following elements:

1.Documentation Section

Package Declaration

Import Statements

Interface Section

Class Definition

Class Variables and Variables

Main Method Class

Methods and Behaviors

Operator in java
Java operators are special symbols that perform operations on variables or values. They can
be classified into several categories based on their functionality. These operators play a
crucial role in performing arithmetic, logical, relational, and bitwise operations etc.

Types of Operators in Java

1. Arithmetic Operators

2. Unary Operators

3. Assignment Operator

4. Relational Operators

5. Logical Operators

6. Ternary Operator

7. Bitwise Operators

8. Shift Operators

1. Arithmetic Operators

Arithmetic Operators are used to perform simple arithmetic operations on primitive and
non-primitive data types.
 * : Multiplication

 / : Division

 % : Modulo

 + : Addition

 – : Subtraction

Example:

// Java Program to show the use of

// Arithmetic Operators

import java.io.*;

class Geeks

public static void main(String[] args)

// Arithmetic operators on integers

int a = 10;

int b = 3;

System.out.println("a + b = " + (a + b));

System.out.println("a - b = " + (a - b));24

System.out.println("a * b = " + (a * b));

System.out.println("a / b = " + (a / b));

System.out.println("a % b = " + (a % b));

System.out.println("a1 + b1 = " + (a1 + b1));

2. Unary Operators

Unary Operators need only one operand. They are used to increment, decrement, or negate
a value.

 - , Negates the value.


 + , Indicates a positive value (automatically converts byte, char, or short to int).

 ++ , Increments by 1.

o Post-Increment: Uses value first, then increments.

o Pre-Increment: Increments first, then uses value.

 -- , Decrements by 1.

o Post-Decrement: Uses value first, then decrements.

o Pre-Decrement: Decrements first, then uses value.

Example:

// Java Program to show the use of

// Unary Operators

import java.io.*;

// Driver Class

class Geeks {

// main function

public static void main(String[] args)

// Interger declared

int a = 1-0;

int b = 10;

// Using unary operators

System.out.println("Postincrement : " + (a++));

System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));

System.out.println("Predecrement : " + (--b));

. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable
 += , Add and assign.
 -= , Subtract and assign.
 *= , Multiply and assign.
 /= , Divide and assign.
 %= , Modulo and assign

EXAMPLE
// Java Program to show the use of
// Assignment Operators
import java.io.*;

// Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{

// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}

4. Relational Operators

Relational Operators are used to check for relations like equality, greater than, and less than

 == , Equal to.

 != , Not equal to.

 < , Less than.

 <= , Less than or equal to.

 > , Greater than.


 >= , Greater than or equal to.
import java.io.*;

// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;

System.out.println("a > b: " + (a > b));


System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
5. Logical Operators
Logical Operators are used to perform “logical AND” and “logical OR” operations, similar to
AND gate and OR gate in digital electronics
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-versa
 import java.io.*;

 class Geeks {

 // Main Function
 public static void main (String[] args) {

 // Logical operators
 boolean x = true;
 boolean y = false;

 System.out.println("x && y: " + (x && y));
 System.out.println("x || y: " + (x || y));
 System.out.println("!x: " + (!x));
 }
 }

6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary. The general format is ,
condition ? if true : if false
Control Statements in Java

What is a Statement?
 Definition:

A statement is a fundamental building block of a program, instructing the computer


to execute a specific task.

Java provides three types of control flow statements.

1. Decision Making statements

o if statements

o switch statement

2. Loop statements

o do while loop

o while loop

o for loop

3. Jump statements

o break statement

o continue statement

LOOP STATEMENT
Java Loops

Looping in programming languages is a feature that facilitates the execution of a set of


instructions/functions repeatedly while some condition evaluates to true. Java provides
three ways for executing the loops. While all the ways provide similar basic functionality,
they differ in their syntax and condition-checking time.

In Java, there are three types of Loops which are listed below:

 for loop

 while loop
 do-while loop

1. for loop
The for loop is used when we know the number of iterations (we
know how many times we want to repeat a task). The for
statement consumes the initialization, condition, and
increment/decrement in one line thereby providing a shorter,
easy-to-debug structure of looping.

import java.io.*;

class Geeks {

public static void main(String[] args)

for (int i = 0; i <= 10; i++) {

System.out.print(i + " ");

2. while Loop

A while loop is used when we want to check the condition before running the code.

import java.io.*;

class Geeks {

public static void main(String[] args)

int i = 0;

while (i <= 10) {

System.out.print(i + " ");

i++;

}
}

do-while Loop

The do-while loop in Java ensures that the code block executes at least once before the
condition is checked.

import java.io.*;

class Geeks {

public static void main(String[] args)

int i = 0;

do {

System.out.print(i + " ");

i++;

} while (i <= 10);

JUMPP/BRANCHING STATEMENT
Branching statements are used to change the flow of execution from one section of a
program to another. Branching statements are typically utilized within control statements.
Java includes three types of branching statements: continue, break, and return.

The break Statement

The break statement is used to abruptly exit a loop or switch statement.

public class BranchingStatements {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int num : numbers) {

if (num == 5) {

break; // Exit the loop when num is 5

System.out.println(num);
}

The continue Statement

The continue statement is used to skip the current loop iteration and go to the next.

1. public class BranchingStatements {

2. public static void main(String[] args) {

3. int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

4. for (int num : numbers) {

5. if (num == 5) {

6. CONTINUE; // Exit the loop when num is 5

7. }

8. System.out.println(num);

9. }

10. }

11. }

Java - What is OOP?


OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations
on the data, while object-oriented programming is about creating objects that contain both
data and methods.
Object-oriented programming has several advantages over procedural programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time
Java - What are Classes and
Objects?
Classes and objects are the two main aspects of object-oriented
programming.

Look at the following illustration to see the difference between class and
objects:

class
Fruit

objects
Apple

Banana

Mang

Java Classes/Objects
Java is an object-oriented programming language.
. For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:
Create a class named "Main" with a variable x:
Ex.
public class Main {
int x = 5;
}

Create an Object

Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}

Java Class Methods


create a method named myMethod() in Main:
Example
Inside main, call myMethod():

public class Main {


static void myMethod() {
System.out.println("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "Hello World!"

Java Constructors
A 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:

Example

Create a constructor:
// Create a Main class
public class Main {
int x; // Create a class attribute

// Create a class constructor for the Main class


public Main() {
x = 5; // Set the initial value for the class attribute x
}

public static void main(String[] args) {


Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}

// Outputs 5

Types of constructor
Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so primarily there are three
types of constructors in Java are mentioned below:

 Default Constructor

 Parameterized Constructor

 Copy Constructor

Example
public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println(myObj.x);

// Outputs 5

java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:
Example
Create a variable of type String and assign it a value:
String greeting = "Hello";
Try it Yourself »

String Length
A String in Java is actually an object, which contain methods that can perform certain
operations on strings. For example, the length of a string can be found with
the length() method:
Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
Try it Yourself »

More String Methods


There are many string methods available, for example toUpperCase() and toLowerCase():
Example
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"
Try it Yourself »

Finding a Character in a String


The indexOf() method returns the index (the position) of the first occurrence of a specified
text in a string (including whitespace):
Example
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
Try it Yourself »

INHERITANCE IN JAVA
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and methods)
of another class. In Java, Inheritance means creating new classes based on existing ones
Important Terminologies Used in Java Inheritance

 Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. 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)

How to Use Inheritance in Java?


The extends keyword is used for inheritance in Java. Using the extends keyword indicates
you are derived from an existing class. In other words, “extends” refers to increased
functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}

Java Inheritance Types


Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’
inherits all the properties of the class ‘A’.

3. Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
subclass. In the below image, class A serves as a base class for the derived classes B, C, and
D.
3. Multiple Inheritance (Through Interfaces)

In Multiple inheritances

Please note that Java does not support multiple inheritances with classes. In Java, we can
achieve multiple inheritances only through Interfaces. In the image below, Class C is derived
from interfaces A and B.
Method overloading
Method overloading allows you to define multiple methods within the same class that share
the same name but have different parameter lists (number, type, or order of parameters)
Example;
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add two doubles (overloaded)


double add(double a, double b) {
return a + b;
}

// Method to add three integers (overloaded)


int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Abstract Class in Java


 Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).

An abstract class is declared using the “abstract” keyword in its class definition.

// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}

// Subclass (inherit from Animal)


class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:

To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends).

Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}

Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface

/ Creating a thread by extending the Thread class


class MyThread extends Thread {
@Override
public void run() {
// Code to be executed by the thread
System.out.println("Thread is running");
}
}

// Creating a thread by implementing the Runnable interface


class MyRunnable implements Runnable {
@Override
public void run() {
// Code to be executed by the thread
System.out.println("Runnable is running");
}
}

public class Main {


public static void main(String[] args) {
// Create and start a thread using Thread class
MyThread thread1 = new MyThread();
thread1.start();

// Create and start a thread using Runnable interface


MyRunnable runnable = new MyRunnable();
Thread thread2 = new Thread(runnable);
thread2.start();
}
}
Life cycle of thread
A thread in Java can exist in any one of the following states at any given time. A thread lies
only in one of the shown states at any instant:

1. New State

2. Runnable State

3. Blocked State

4. Waiting State

5. Timed Waiting State

6. Terminated State

The diagram below represents various states of a thread at any instant.

Java Exception Handling

Try or catch use only

Java Applets
A Java Applet is a Java program that runs inside a web browser. An Applet is embedded in an
HTML file using <applet> or <objects> tags. Applets are used to make the website more
dynamic and entertaining. Applets are executed in a sandbox for security, restricting access
to local system resources.
Java Applet Life Cycle

The below diagram demonstrates the life cycle of Java Applet:

Creating Hello World Applet


Let’s begin with the HelloWorld applet :
import java.applet.Applet;
import java.awt.Graphics;

// HelloWorld class extends Applet


public class HelloWorld extends Applet {

// Overriding paint() method


@Override public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}
}

Local Applet
Local Applet is written on our own, and then we will embed it into web pages. Local Applet
is developed locally and stored in the local system.

Specifying Local applet

<applet
codebase = "tictactoe"
code = "FaceApplet.class"
width = 120
height = 120>
</applet>
FaceApplet.java
//Import packages and classes
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
//Creating FaceApplet class that extends Applet
public class FaceApplet extends Applet
{
//paint() method starts
public void paint(Graphics g){
//Creating graphical object
g.setColor(Color.red);
g.drawString("Welcome", 50, 50);
g.drawLine(20, 30, 20, 300);
g.drawRect(70, 100, 30, 30);
g.fillRect(170, 100, 30, 30);
g.drawOval(70, 200, 30, 30);
g.setColor(Color.pink);
g.fillOval(170, 200, 30, 30);
g.drawArc(90, 150, 30, 30, 30, 270);
g.fillArc(270, 150, 30, 30, 0, 180);
}
}

Remote Applet
A remote applet is designed and developed by another developer. It is located or available
on a remote computer that is connected to the internet.
we must know the applet's address on the web that is referred to as Uniform Recourse
Locator(URL).

Specifying Remote applet

<applet
codebase = "http://www.myconnect.com/applets/"
code = "FaceApplet.class"
width = 120
height =120>
</applet>

Java Application is just like a Java program that runs on an underlying operating
system with the support of a virtual machine. It is also known as an application program.
The graphical user interface is not necessary to execute the java applications, it can be run
with or without it.
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter().

Example of using parameter in Applet:

import java.applet.Applet;
import java.awt.Graphics;

public class UseParam extends Applet{

public void paint(Graphics g){


String str=getParameter("msg");
g.drawString(str,50, 50);
}

myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

Java AWT Basics


Java AWT (Abstract Window Toolkit) is an API used to create Graphical User Interface (GUI)
or Windows-based Java programs and Java AWT components are platform-dependent,
which means they are shown in accordance with the operating system’s view

The java.awt package contains AWT API classes such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List, and so on.
Java AWT Hierarchy

 Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.

Containers: AWT provides containers like panels, frames, and dialogues to organize
and group components in the Application.
1. Java AWT Label

Syntax of AWT Label

public class Label extends Component implements Accessible

2. Java AWT Button

AWT Button is a control component with a label that generates an event when clicked on.
Button Class is used for creating a labeled button that is platform-independent.

Syntax of AWT Button

public class Button extends Component implements Accessible

3. Java AWT TextField

Syntax of AWT TextField:

public class TextField extends TextComponent

4. Java AWT Checkbox

Syntax of AWT Checkbox:

public class Checkbox extends Component implements ItemSelectable, Accessible


5. Java AWT List

The object of the AWT List class represents a list of text items.

Syntax of Java AWT List:

public class List extends Component implements ItemSelectable, Accessible

Event Handling in Java


An event is a change in the state of an object triggered by some action such as Clicking a
button, Moving the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java,
the java.awt.event package provides various event classes to handle these actions.

Classification of Events

1. Foreground Events: Foreground events are the events that require user interaction
to generate. Examples of these events include Button clicks, Scrolling the scrollbar,
Moving the cursor, etc.

2. Background Events: Events that don’t require interactions of users to generate are
known as background events.

Event Classes and Listener Interfaces

Java provides a variety of event classes and corresponding listener interfaces.


Below table demonstrates the most commonly used event classes and their
associated listener interfaces:
Event Class Listener Interface

ActionEvent ActionListener

AdjustmentEvent AdjustmentListener
Event Class Listener Interface

ContainerEvent ContainerListener

ComponentEvent ComponentListener

FocusEvent FocusListener

ItemEvent ItemListener

KeyEvent KeyListener

MouseEvent MouseListener & MouseMotionListener

MouseWheelEvent MouseWheelListener

TextEvent TextListener

WindowEvent WindowListener

image below shows the flow chart of the


event
delegationmodel.
Java Networking
When computing devices such as laptops, desktops, servers, smartphones, and tablets and
an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells,
refrigerators, audio/visual systems, thermostats, and various sensors are sharing information
and data with each other is known as networking.
Java Networking classes
The java.net package of the Java programming language includes various classes that
provide an easy-to-use means to access network resources. The classes covered in
the java.net package are given as follows –

1. CacheRequest – The CacheRequest class is used in java whenever there is a need to


store resources in ResponseCache. The objects of this class provide an edge for the
OutputStream object to store resource data into the cache.

2. CookieHandler – The CookieHandler class is used in Java to implement a callback


mechanism for securing up an HTTP state management policy implementation inside
the HTTP protocol handler. The HTTP state management mechanism specifies the
mechanism of how to make HTTP requests and responses.

3. CookieManager – The CookieManager class is used to provide a precise


implementation of CookieHandler. This class separates the storage of cookies from
the policy surrounding accepting and rejecting cookies. A CookieManager comprises
a CookieStore and a CookiePolicy.

4. DatagramPacket – The DatagramPacket class is used to provide a facility for the


connectionless transfer of messages from one system to another. This class provides
tools for the production of datagram packets for connectionless transmission by
applying the datagram socket class.

5. InetAddress – The InetAddress class is used to provide methods to get the IP address
of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.

6. Server Socket – The ServerSocket class is used for implementing system-independent


implementation of the server-side of a client/server Socket Connection. The
constructor for ServerSocket class throws an exception if it can’t listen on the
specified port. For example – it will throw an exception if the port is already being
used.

7. Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations. The users can implement various
networking actions such as sending, reading data, and closing connections. Each
Socket object built using java.net.Socket class has been connected exactly with 1
remote host; for connecting to another host, a user must create a new socket object.

8. DatagramSocket – The DatagramSocket class is a network socket that provides a


connection-less point for sending and receiving packets. Every packet sent from a
datagram socket is individually routed and delivered. It can further be practiced for
transmitting and accepting broadcast information. Datagram Sockets is Java’s
mechanism for providing network communication via UDP instead of TCP.

9. Proxy – A proxy is a changeless object and a kind of tool or method or program or


system, which serves to preserve the data of its users and computers. It behaves like
a wall between computers and internet users. A Proxy Object represents the Proxy
settings to be applied with a connection.

10. URL – The URL class in Java is the entry point to any available sources on the internet.
A Class URL describes a Uniform Resource Locator, which is a signal to a “resource”
on the World Wide Web. A source can denote a simple file or directory, or it can
indicate a more difficult object, such as a query to a database or a search engine.

Java Networking Interfaces


The java.net package of the Java programming language includes various interfaces also that
provide an easy-to-use means to access network resources. The interfaces included in
the java.net package are as follows:
1. CookiePolicy – The CookiePolicy interface in the java.net package provides the
classes for implementing various networking applications. It decides which cookies
should be accepted and which should be rejected. In CookiePolicy, there are three
pre-defined policy implementations, namely ACCEPT_ALL, ACCEPT_NONE, and
ACCEPT_ORIGINAL_SERVER.

2. CookieStore – A CookieStore is an interface that describes a storage space for


cookies. CookieManager combines the cookies to the CookieStore for each HTTP
response and recovers cookies from the CookieStore for each HTTP request.

3. FileNameMap – The FileNameMap interface is an uncomplicated interface that


implements a tool to outline a file name and a MIME type string. FileNameMap
charges a filename map ( known as a mimetable) from a data file.

4. SocketOption – The SocketOption interface helps the users to control the behavior of
sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions
allows the user to set various standard options.

5. SocketImplFactory – The SocketImplFactory interface defines a factory for


SocketImpl instances. It is used by the socket class to create socket implementations
that implement various policies.

6. ProtocolFamily – This interface represents a family of communication protocols. The


ProtocolFamily interface contains a method known as name(), which returns the
name of the protocol family.
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to perform all the input-
output operations. These streams support all the types of objects, data-types, characters,
files etc. to fully execute the I/O operations.

Example:
// Java code to illustrate print()
import java.io.*;

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

// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}

Use of Stream in Java:


The uses of Stream in Java are mentioned below:
1. Stream API is a way to express and process collections of objects.
2. Enable us to perform operations like filtering, mapping, reducing, and sorting.
How to Create Java Stream?
Java Stream Creation is one of the most basic steps before considering the functionalities of
the Java Stream. Below is the syntax given for declaring Java Stream.
Syntax:
Stream<T> stream;
Byte Streams in Java
These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits.
Using these you can store characters, videos, audios, images etc.

The InputStream and OutputStream classes (abstract) are the super classes of all the
input/output stream classes: classes that are used to read/write a stream of bytes. Following
are the byte array stream classes provided by Java −

InputStream OutputStream

FIleInputStream FileOutputStream

ByteArrayInputStream ByteArrayOutputStream

ObjectInputStream ObjectOutputStream

PipedInputStream PipedOutputStream

FilteredInputStream FilteredOutputStream

BufferedInputStream BufferedOutputStream

DataInputStream DataOutputStream

JDBC Drivers
Java Database Connectivity (JDBC) is an application programming interface (API) for
the Java programming language that defines how a client can access and interact with any
kind of tabular data, especially a relational database. JDBC Drivers uses JDBC APIs which was
developed by Sun Microsystem, but now this is a part of Oracle.

The JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query

Structure of JDBC Driver


There are 4 types of JDBC drivers.
1. Type-1 driver or JDBC-ODBC bridge driver

2. Type-2 driver or Native-API driver

3. Type-3 driver or Network Protocol driver

4. Type-4 driver or Thin driver

connectivity model
In Java, the connectivity model for interacting with databases is achieved through the Java
Database Connectivity (JDBC) API, which provides a standard interface for Java applications
to connect to and interact with various relational databases.

You might also like