0% found this document useful (0 votes)
7 views40 pages

Java Programming Notes

This document provides an overview of the Internet and Java programming, covering key concepts such as Internet protocols, the history and benefits of the Internet, as well as the features and principles of Java as an object-oriented programming language. It discusses various types of Internet connections, addresses, and applications, along with the basic concepts of object-oriented programming (OOP) including classes, objects, encapsulation, inheritance, and polymorphism. Additionally, it outlines the future of the Internet, emphasizing advancements like decentralization, smart devices, and AI integration.

Uploaded by

M. Roshini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views40 pages

Java Programming Notes

This document provides an overview of the Internet and Java programming, covering key concepts such as Internet protocols, the history and benefits of the Internet, as well as the features and principles of Java as an object-oriented programming language. It discusses various types of Internet connections, addresses, and applications, along with the basic concepts of object-oriented programming (OOP) including classes, objects, encapsulation, inheritance, and polymorphism. Additionally, it outlines the future of the Internet, emphasizing advancements like decentralization, smart devices, and AI integration.

Uploaded by

M. Roshini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

JAVA PROGRAMMING -

UNIT -I

An overview of Internet

The Internet is two or more computers / devices connected through online.

Internet – Overview –Internet Protocols – Internet address – Internet access


– Applications – Future of Internet and intranet related Applications. –
Basic concepts of OOP – benefits of OOP– Object Oriented applications of
OOP – Data types, variables and arrays – Programs with input, numeric
input – type conversion and casting.

What is Java?

● Java is a popular object-oriented programming language that can run on many


different platforms and devices.
● Java is a high-level programming language that's used to write code for web
applications, Smartphone operating systems, and more.
● Java was developed by James Gosling at Sun Microsystems in 1990.
● In May 1995 and later Oracle Corporation and is widely used for developing
applications for desktop, web, and mobile devices.

Feature of java:
Java has many features,
Simplicity: Java's syntax is clean and straightforward, making it easy to learn and
understand.

Object-oriented: Java treats everything as an object, which helps organize and design
software. The four pillars of Java's object-oriented programming (OOP) are encapsulation,
inheritance, polymorphism, and abstraction.

Platform independent: Java code can be written once and run on different platforms, such
as Windows, Linux, and Mac, without modification.

Security: Java is known for its security features, such as avoiding explicit pointers and
running programs in a secure environment.

Robust: Java is strong and reliable, with features like automatic garbage collection and
efficient memory management.

Architecture neutral: Java is not dependent on a specific architecture, and the size of
primitive data types is fixed.

Portable: Java code can be carried to any platform without modification.

High performance: Java's bytecode is close to native code.

Distributed: Java supports the creation of distributed applications.

Multithreaded: Java supports multithreading.

An overview of Internet:

● The Internet is two or more computers / devices connected through online.


● The internet is a global network of interconnected computers and devices that allows
people to communicate and share information.
● The Internet is a group of computer systems connected from all around the world.
History of Internet:

● The ARPANET (Advanced Research Projects Agency Network, later renamed the
internet) established a successful link between the University of California October 29,
1969.
● TCP/IP (Transmission Control Protocol and Internet Protocol) was established in the
1970s, allowing internet technology to mature.
● In the year 1991, a user-friendly internet interface was developed.
● Delhi was the first national commercial online service to offer internet connectivity in
July 1992.
● Wi-Fi was first introduced in 1997.
● Smartphone use was widespread in 2007.
● The 4G network was launched in 2009.
● The internet is used by 3 billion people nowadays.
● By 2030, there are expected to be 7.5 billion internet users and 500 billion devices linked
to the internet.

Benefits of Internet:
The internet has many benefits, including:

● Access to information: The internet provides a vast amount of information on almost


any topic, including financial matters, government legislation, educational issues, and
more.
● Communication: The internet allows people to communicate with each other across long
distances.
● Distance education: The internet allows people to pursue higher studies without leaving
home or resigning from their jobs.
● Personalized education: Online classes can benefit students who have trouble focusing
in the classroom or who aren't as assertive.
● Cost savings: The internet of things can help reduce utility costs by connecting sensors
to automated systems.
● Entertainment: The internet offers a wide range of entertainment options.
● Cultural sharing: The internet allows for the sharing of culture and diversity.
● Improved medical care: The internet can improve medical care.
● Economic growth: The internet can contribute to economic growth.
● More efficient government services: The internet can make government services more
efficient.
Drawbacks of Internet:
The internet has many drawbacks, including:

● Privacy: Hackers can steal sensitive information from devices and post it on social
media.
● Cybercrime: The internet can be used for cyberbullying, identity theft, fraud, and other
cybercrimes.
● Addiction: People can become addicted to the internet, spending more time online than
on real-life activities.
● Health: Spending too much time on the internet can negatively impact your health,
including eye strain, obesity, and improper posture.
● Distraction: Using social media during work or study hours can reduce productivity.
● Isolation: Online education can lead to feelings of isolation, as students may not have
the same opportunities to interact with other students.
● Academic performance: Excessive internet use can negatively impact academic
performance.
● Misinformation: The internet can be exposed to misinformation.
● Self-esteem: Excessive internet use can lead to comparison and self-esteem issues

Internet Protocol (IP):

● Internet Protocol (IP) is a set of protocols that enables data to be sent between computers
on the internet.
● The Internet Protocol (IP) is a set of rules that allows computers and other devices to
communicate over the Internet.
● It ensures that information sent from one device reaches the correct destination by using
a unique set of numbers known as IP addresses.
● IP has the task of delivering packets from the source host to the destination host solely
based on the IP addresses.

History of Internet Protocol:


● The development of the protocol was started in 1974 by Bob Kahn and Vint Cerf.
● It is used in conjunction with the Transmission Control Protocol (TCP), so they together
named the TCP/IP.
● The first major version of the internet protocol was IPv4 in 1981.
● The second major version of the internet protocol was IPv6 in 1998.
● The main reason behind the development of IPv6 is the big difference between
addressing.
● IPv4 uses 32 bits for addressing, while IPv6 uses 128 bits for addressing.

What is an IP Packet?

● An IP packets is the basic unit of data transmission in an IP network. It consists of a


header and a payload.
● Header: The header contains essential control information, such as the source and
destination IP addresses, that helps routers determine where to send the packet.
● Payload: The payload contains the actual data being transmitted. Once the packet
reaches its destination, the data in the payload is delivered to the appropriate
application or protocol.

Working of Internet Protocol:


● Dividing Data into Packets: When you send information over the internet, IP split it
into small parts called packets. Each packet contains a piece of the data and the
address of where it needs to go.
● Addressing: Every device connected to the internet has its own IP address. This
address helps identify where the data is being sent from and where it should be
delivered.
● Routing the Packets: As the packets travel across the internet, they pass through
several devices called routers. These routers help direct the packets toward the
correct destination, like how mail is sorted at different post offices.
● Reassemble the Data: Once all the packets arrive at the destination, they are put
back together to recreate the original message or file.
● Handling Missing Packets: If some packets don’t arrive, the system can request that
they be sent again, making sure the complete data is received.

Commonly Used Network Protocols:


There are several commonly used network protocols that run on top of IP, including:

1. TCP: Transmission Control Protocol enables the flow of data across IP address
connections.
2. UDP: User Datagram Protocol provides a way to transfer low-latency process
communication that is widely used on the internet for DNSlookup and voice over
Internet Protocol.
3. FTP: File Transfer Protocol is a specification that is purpose-built for accessing,
managing, loading, copying and deleting files across connected IP hosts.
4. HTTP: Hypertext Transfer Protocol is the specification that enables the modern
web. HTTP enables websites and web browsers to view content. It typically runs over
port 80.

5. HTTPS: Hypertext Transfer Protocol Secure is HTTP that runs with encryption via
Secure Sockets Layer or Transport Layer Security. HTTPS typically is served over
port 443.

What is IP Address:

● IP provides mechanisms that enable different systems to connect to each other to transfer
data.

● It identifies each machine in an IP network as enabled with an IP address.


● Similar to the way a street address identifies the location of a home or business, an IP
address provides an address that identifies a specific system so data can be sent to it or
received from it.
● An IP address is a unique identifier assigned to the computer which is connected to the
internet.
● Each IP address consists of a series of characters like 192.168.1.2.
● Users can access the domain name of each website with the help of these characters and
convert the human-readable domain names into a series of characters.
● Each IP packet contains two addresses, i.e., the IP address of the device, which is sending
the packet, and the IP address of the device which is receiving the packet.

Categories of IP Addresses:
IPv4 addresses are divided into two categories:

● Public address
● Private address

Public address:
● The public address is also known as an external address as they are grouped under the
WAN addresses.
● We can also define the public address as a way to communicate outside the network.
● This address is used to access the internet. The public address available on our computer
provides remote access to our computer.
● With the help of a public address, we can set up the home server to access the internet.
This address is generally assigned by the ISP (Internet Service Provider).

Private address:

● A private address is also known as an internal address, as it is grouped under the LAN
addresses.
● It is used to communicate within the network.
● These addresses are not routed on the internet so that no traffic can come from the
internet to this private address.
● The address space for the private address is allocated using to create our own network.
● The private addresses are assigned to mainly those computers, printers, smartphones,
which are kept inside the home or the computers that are kept within the organization.

Internet Access:

● Internet access refers to users or organizations connecting to the internet via laptops,
mobile devices, or personal computers.

Types of internet connections:

Knowing the differences between the connections is essential when choosing the type and

speed that meets your needs. There are numerous ways to connect your e-reader, tablet, gaming

console, desktop, smartphone, or laptop to the internet in this day and age. Below is a deep dive

into common connections.

1. WiFi hotspots:

● These sites offer internet access over WLAN, a Wireless Local Area Network, through a

router that connects to an internet provider.

● Hotspots use WiFi technology that uses radio waves to connect electronic devices to the

internet or for wireless data exchanges.

● A hotspot can either be free-standing or phone-based, free or commercial.


2. Broadband:

● This is a high-speed connection provided via telephone or cable companies.

● It is among the fastest options currently, and it uses several multiple channels to transfer

massive volumes of information.

● Broadband is short for broad bandwidth.

3. Dial-up:

● In dial-up connections, users have to link their phone line to a computer to access the

internet.

● This type of connection, also known as analogue, restricts users from making or receiving

phone calls via their phone service when using the internet.

● Although dial-up connections were commonly used before, they are currently outdated.

4. Satellite:

● A satellite internet connection could be available in areas where a broad bandwidth

connection is unavailable.

● Similar to wireless access, a satellite connection uses a modem.

5. Cable:

● Cable internet connections fall under broadband connections.

● Users can access the internet over cable TV lines using a cable modem.

● These modems typically offer fast access to the internet, making this type of connection

desirable to many internet users.


6. DSL:

● DSL is the acronym for Digital Subscriber Line, and it utilizes existing 2-wire copper

phone lines connected to a user's home.

● Internet service is delivered simultaneously with landline phone services.

● Unlike dial-up connections, users can make calls while still browsing the internet.

7. ISDN:

● Integrated Service Digital Network, commonly ISDN, enables users to send video, voice

content, and data over standard or digital telephone lines.

● The user and the internet access provider must install an ISDN adapter at both ends of

this transmission.

Future of internet:

● Decentralization

The internet will be powered by decentralized technologies like blockchain and peer-to-

peer networks. This will lead to greater privacy and security.

● Virtual and augmented reality

Users will be able to browse the web using virtual reality (VR) and augmented reality

(AR).

● Smart devices

More devices will be connected to the internet, including smart earbuds, VR glasses, and

holographic projectors.
● Body augmentation

Users will be able to enhance their bodies with technology, such as AR contact lenses or

brain-computer interfaces (BCIs).

● Internet of Things (IoT)

More objects will be connected to the internet, including household appliances,

buildings, and utility grids.

● AI and machine learning

Artificial intelligence (AI) and machine learning will be used to generate content,

automate tasks, and improve the user experience.

● Internet Application:

An internet application is a program that uses the internet to connect a client to a server.

Internet applications can be used to provide services like online shopping, banking, and

social networking.

Internet applications:

● Online shopping: Users can shop from virtual stores that are available 24/7.

● Email: A widely used application that allows users to send and receive electronic

messages.

● Web browsing: Users can view websites and access information.

● Social networking: Users can connect with friends and family through social media

sites.

● Online banking: Users can access their bank accounts and perform transactions online.

● Education: Users can access educational resources and take online courses.
● Gaming: Users can play games online.

● Trading: Users can buy and sell securities online.

● Dating: Users can meet potential partners online.

Basic Concept OOPS:

● Object-oriented programming is based on the concept of objects.

● OOPs Provides a clear structure for the program.

● Object-oriented programming (OOP) is a programming model that uses classes and

objects to create software programs.

There are 8 basic concepts in OOPs.

❖ Class

❖ Objects

❖ Encapsulation

❖ Abstraction

❖ Polymorphism

❖ Inheritance

❖ Dynamic Binding

❖ Message Passing

Object:

● Object is a real time entity.

● It have some characteristics and behavior.


● An Object is an instance of a Class.

● When an object is created, memory is allocated.

Class:

● Collection of object that is called known as class.

● Class is like as blueprint for an object.

● [Ex]: Car is consider as class. That properties wheel, accelarator and break are objects.

Abstraction:

● Abstraction is displaying only essential information and hiding background information.

● [Ex]: The man only knows pressing the accelerator and increase speed. Don’t have knows

accelerator internal process.

Encapsulation:

● Encapsulation is wrapping up data under a single unit.

● Encapsulation is binding together properties and the functions that manipulate them.

[Ex]: accelerator – Speed, Break – Slow.

Inheritance:

● One class properties and characteristics derived to another class is called Inheritance.

● First class is the base class. Second class is the Derived class.
There are 5 types:

1. Single Inheritance - One subclass is derived from one base class

2. Multiple Inheritance - One subclass is derived from more than base class.

3. Multilevel Inheritance - One sub class is derived from another sub class (Base).

4. Hierarchical Inheritance - More than subclass is derived from a single base class.

5. Hybrid Inheritance - Combining Hierarchical inheritance and Multiple Inheritance.


Polymorphism:

Single entity taking more than one form.

[Ex]: ‘+’ symbol use as Arithmetic operator; Some time used Unary operator.

Dynamic Binding:

● Dynamic binding with a single function name to handle multiple objects.

● Dynamic binding is the connection between the function declaration and the function

call.

● Dynamic binding is reducing the code build time.

[Ex]: Debugging the code and errors is reducing the complexity.

Message Passing:

● The exchange of information between two or more objects.

● It communicates by sending messages.

● There are 2 types: Sending Objects & Receiving Objects.

Benefits of OOPs:
A programming paradigm known as object-oriented programming (OOP). It employs objects

and classes to structure and arrange code.

1. Modularity:

● Breaks down large systems into smaller, manageable objects.

● Enhances code readability and simplifies understanding.


● Makes testing individual modules easier and more efficient.

● This modularity encourages debugging easier.

2. Reusability:

● Objects and classes can be reused across projects or application modules.

● Reduces the need to write repetitive code, saving time and effort.

● Encourages creating libraries of reusable components for common functionality.

● Enhances productivity with quicker development cycles.

3. Syntax:

● This is the set of rules that define how words and punctuation are organized in a

programming language.

4. Better Code Organization:

● OOPs promote a clearer and more structured code structure.

● It is simpler to relate software components of code.

● It improves the readability of the code.

5. Maintenance:

● With OOPs, updating or changing a system is frequently simpler and less error.

● It is possible to localize changes to particular classes or objects.

● which lowers the possibility of unexpected side effects of the code.


6. Collaborative Development:

● OOP allows team members to work independently on various classes or objects.

● These parts may eventually be included in the entire system.

7. Scalability:

● OOP ideas like polymorphism and inheritance can help a system scale more easily.

● It allows for the addition of new classes or modifications without affecting the system's

whole codebase.

8. Real-World Modeling

● OOP helps in the modeling of real-world entities and relationships in software.

● This makes the code more aligned with human understanding of the problem domain.

9. Extensibility

● OOPs principles make it easier to extend and scale software systems.

● New features and functionalities can be added with minimal disruption to existing

code.

● The structured approach provided by OOPs ensures a clearer and sustainable

development process.
10. Ease of Troubleshooting

● OOP simplifies the process of debugging and troubleshooting by isolating


functionality into separate classes.
● Problems can be localized and resolved more efficiently.

Applications of OOPS:

Object-Oriented Programming (OOP) has found widespread applications across various domains
due to its modular, reusable, and scalable nature. Here are some key applications of OOP:

● Software Development:

OOP is extensively used to build large-scale and complex systems. The modular structure
of OOP allows developers to organise code efficiently, making it more manageable and
maintainable.

● Game Development:

OOP is a fundamental paradigm in the gaming industry. Games involve numerous


entities with specific attributes and behaviours, making OOP’s object modelling a natural
fit. Game developers use OOP to create structured and interactive gaming environments.

● Client Server System:

The client-server systems are those that involve a relationship between cooperating
programs in an application. In general, the clients will initiate requests for services and
the servers will provide that functionality. The client and server either reside in the same
system or communicate with each other through a computer network or the internet.

● Web Development:

Many web development languages, including Java, Python, and PHP, incorporate OOP
principles. OOP allows developers to create modular and scalable web applications. Each
component, such as user interfaces and data structures, can be encapsulated in objects for
better organisation and maintenance.

● Simulation and Modeling: OOP is employed in simulation and modelling applications,


where real-world systems are replicated digitally. OOP offers a suitable method for
streamlining these complex structures.
● Database Systems:

Object-relational mapping (ORM) frameworks, which bridge the gap between object-
oriented programming languages and relational databases, are built on OOP concepts.
This integration simplifies data manipulation and enhances database interactions in
software applications.

● Artificial Intelligence (AI) and Machine Learning (ML):

OOP is utilised in AI and ML applications to model and represent intelligent agents,


algorithms, and data structures. The flexibility and abstraction provided by OOP make it
easier to implement and maintain complex AI systems.

● Graphical User Interface (GUI) Development:

OOP is well-suited for GUI development, where user interfaces are represented as
objects with specific properties and behaviours. This allows for the creation of interactive
and user-friendly applications.

● Network Programming:

OOP is employed to model network components and their interactions in network


programming. Objects can represent network devices, protocols, and communication
channels, making designing and implementing networked applications easier.
● Office Automation System:
Nowadays companies use automated systems to share information and communication to
and from the people inside and outside the organization. There are various works in the
office for which the employees can be replaced by automated robots and these works are
generally time-consuming and hard work.
● Hypertext and Hypermedia:
Hypertext is a cross-referencing tool that connects to other texts in a non-linear, multi-
sequential manner. Contrarily, hypermedia is a superset of hypertext. OOP also
contributes to the development of the hypertext and hypermedia framework.

Data Types in Java?

● Data types in Java specify how memory stores the values of the variable. Each variable
has a data type that decides the value the variable will hold.
● Data types specify the different sizes and values that can be stored in the variable.

There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

Java Primitive data types:

1. boolean data type


2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
Non-Primitive Data Types:

In Java, non-primitive data types, also known as reference data types, are used to store complex
objects rather than simple values.

1. Arrays

Arrays have a fixed size, which is specified when the array is created, and can be accessed
using an index. Arrays are commonly used to store lists of values or to represent matrices and
other multi-dimensional data structures.

Array Declaration:

To declare an array in Java, use the following syntax:

type[] arrayName;

Create an Array:

To create an array, you need to allocate memory for it using the new keyword:

// Creating an array of 5 integers


numbers = new int[5];

2. 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";


Output:

public class Main {

public static void main(String[] args) {

String greeting = "Hello";

System.out.println(greeting);

Java Variables:

Variables are containers for storing data values.

In Java, there are different types of variables for example:

● Int - stores integers (whole numbers), without decimals, such as 123 or -123
● Float - stores floating point numbers, with decimals, such as 19.99 or -19.99
● Char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
● String - stores text, such as "Hello". String values are surrounded by double quotes
● Boolean - stores values with two states: true or false

Declaring (Creating) Variables:

To create a variable, you must specify the type and assign it a value:

Syntax:

type variableName = value;

Int sno = 101;


Program with output:

● You learned from the previous chapter that you can use the println() method to output
values or print text in Java.
● Text must be wrapped inside double quotations marks "".
● If you forget the double quotes, an error occurs:

Example:

System.out.println("Hello World!");

public class Main {

public static void main(String[] args) {

System.out.println("Hello World!");

Output:

Java Input:

● This statement accepts an integer from the user using Stream class and parses it into int
data type using Integer.
● parseInt() method. readLine() means it'll take users input
Example:

public static void main(String args[])throws IOException


{
int i=2,n,a,b=0;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the n value");
n=Integer.parseInt(in.readLine());

Java Type Casting and Conversion:

The two terms type casting and the type conversion are used in a program to convert one data
type to another data type.

What is type casting?

● In typing casting, a data type is converted into another data type by the programmer using
the casting operator during the program design.
● In typing casting, the destination data type may be smaller than the source data type when

converting the data type to another data type.


Syntax:

Destination_datatype = (target_datatype) variable;


(data_type) it is known as casting operator

Example:
float b = 3.0;
int a = (int) b; // converting a float value into integer

2. Type conversion :

● In type conversion, a data type is automatically converted into another data type by a
compiler at the compiler time.
● In type conversion, the destination data type cannot be smaller than the source data type,
that’s why it is also called widening conversion.
● One more important thing is that it can only be applied to compatible data types.

Syntax:

Destination_datatype = (target_datatype) variable;


(data_type) it is known as casting operator

Example:
int x=30;

float y;

y=x; // y==30.000000.

====================================================================

UNIT - II

Operators

An operator is a symbol that tells a compiler to perform specific mathematical or logical


operations on data and variables in a programming language.

Operators – Arithmetic operators – Bitwise operators – Relational operators– Boolean operators


– Logical operators – Assignment operators – Control statement– Selection statements – if,
switch, iteration statements – while, do while, for, nested loops –jump statements, break,
continue, return statements

Operators:

● 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. Bitwise Operators
3. Relational Operators
4. Boolean Operators
5. Logical Operators
6. Assignment Operator

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:
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 % b = " + (a % b));
Output:
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1

2. Bitwise Operators

Bitwise Operators are used to perform the manipulation of individual bits of a number and with
any of the integer types. They are used when performing update and query operations of the
Binary indexed trees.
● & (Bitwise AND) – returns bit-by-bit AND of input values.
● | (Bitwise OR) – returns bit-by-bit OR of input values.
● ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
● ~ (Bitwise Complement) – inverts all bits (one’s complement).

Example:
System.out.println("d & e : " + (d & e));
System.out.println("d | e : " + (d | e));
System.out.println("d ^ e : " + (d ^ e));
System.out.println("~d : " + (~d));
Output:
d&e:8
d | e : 14
d^e:6
~d : -11

3. Relational Operators

Relational Operators are used to check for relations like equality, greater than, and less than.
They return boolean results after the comparison and are extensively used in looping statements
as well as conditional if-else statements. The general format is

variable relation_operator value

Relational operators compare values and return boolean results:

● == , Equal to.
● != , Not equal to.
● < , Less than.
● <= , Less than or equal to.
● > , Greater than.
● >= , Greater than or equal to.
Example:

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));

Output:
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

4. Logical Operators

Logical Operators are used to perform “logical AND” and “logical OR” operations, similar to
AND gate and OR gate in digital electronics. They have a short-circuiting effect, meaning the
second condition is not evaluated if the first is false.

Conditional operators are:

● &&, 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

Example:
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
Output:
x && y: false
x || y: true
!x: false

5. Assignment Operator

‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left
associativity, i.e. value given on the right-hand side of the operator is assigned to the variable on
the left, and therefore right-hand side value must be declared before using it or should be a
constant.

The general format of the assignment operator is:

variable = value;

In many cases, the assignment operator can be combined with others to create shorthand
compound statements. For example, a += 5 replaces a = a + 5. Common compound operators
include:

● += , Add and assign.


● -= , Subtract and assign.
● *= , Multiply and assign.
● /= , Divide and assign.
● %= , Modulo and assign.

Example:
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));
Output:

f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0

6. Boolean Operators:
Boolean operators in Java are logical operators that perform logical operations and return a
boolean value. Boolean values can only be true or false.
● Boolean expressions are expressions that evaluate to true or false
● Boolean expressions are often used with comparison operators
● Boolean expressions are used in conditional statements
Boolean data type
● The boolean keyword is used to declare a variable that can only have the values true or
false
● For example, boolean user = true
Example:
int age = 25;
boolean is EligibleToVote = (age >= 18) && (age <= 65); // This will be true because 25 is
within the range

Difference between while and do-while loop in Java:


while loop:

● While loop is an entry-controlled loop. In an entry-controlled loop, the loop condition is


evaluated before the loop body is executed.
● A while loop is a control flow statement that allows code to be executed repeatedly based
on a given Boolean condition.

Syntax :
while (boolean condition)
{
loop statements...
}

Example:
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
while (i < 10)
{
i++;
System.out.println("GfG");
}
}
}
Output:
GFG
GFG
GFG
GFG
GFG
Do-while loop:

● Do-while loop is an exit-controlled loop, not an entry-controlled loop.


● The condition is checked after the loop body executes.
● In an entry-controlled loop, the condition is checked before the loop body executes.

Syntax:

do
{
statements..
}
while (condition);

Example:
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 5;
do {
i++;
System.out.println("GfG");
} while (i < 10);
}
}

Output

GFG
GFG
GFG
GFG
GFG
Jump Statements:

● Jumping statements are control statements that move program execution


from one location to another.
● Jump statement in Java helps transfer the control of a program from one line
of the code to another and skip the ones in between.
● Jump statements are used to shift program control unconditionally from one
location to another within the program.

Java provides three main jump statements:

1. break
2. continue
3. Return

Break Statement:

● The break statement is used to exit from a loop prematurely.


● It is commonly used in loops (such as for, while, and do-while) and
switch statements.
Example:

Class break_statement
{
public static void main(String[] args)
{
int i=1;
for (;;i++) //infinite loop
{
if (i==5)
{
break;
}
else
{
System.out.println(i);
}
}
}
}
2. Continue statement in Java

● The continue statement in Java never terminates the execution of any loops.
● It can only work inside the "loop statement".
● The primary job of the "Continue statement" is the iteration of that specific loop.
● The nature of the Continue statement is to skip the current iteration and force for the next
one.

Example:

class continue statement


{
public static void main(String[] args)
{
for(int i=0; i<=10;i++)
{
if (i<3)
{
Continue; //continues and goes to next iteration
}
System.out.println(i);
}
}
}
3. Return statement in Java

● Return statement is used to exit a method and, if needed, return a value to the called
● The return statement in Java is a type of jump statement which is primarily used only
inside the functions or methods.
● The purpose of using a Return statement is to terminate the current method of execution
and transfer the control to the next "calling method".
● There are two types of Return statements, which are "Return with a value" and "Return
without a value".

Return with a value: Where expression is the value or result that the function is returning.

Return without a value: It is without an accompanying expression.

Example:

public class Main


{
public static int add(int a, int b){
int sum = a+b;
return sum;
}
public static void main(String[] args) {
int x = 5, y = 10;
int sum = add(x, y);
System.out.println("Sum of a and b: " + sum);
}
}
Output:

Sum of a and b: 15

You might also like