0% found this document useful (0 votes)
14 views34 pages

Unit 1

The document outlines the curriculum for the CS-20 Network Technology and Administration course for the academic year 2024-25, covering key concepts in computer networking, including network models, services, access methods, and topologies. It explains the differences between peer-to-peer and client-server architectures, detailing their advantages and disadvantages, as well as various applications of computer networks in communication, resource sharing, and collaboration. Additionally, it introduces Java programming concepts such as tokens, keywords, identifiers, and literals.

Uploaded by

amitbhatt
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)
14 views34 pages

Unit 1

The document outlines the curriculum for the CS-20 Network Technology and Administration course for the academic year 2024-25, covering key concepts in computer networking, including network models, services, access methods, and topologies. It explains the differences between peer-to-peer and client-server architectures, detailing their advantages and disadvantages, as well as various applications of computer networks in communication, resource sharing, and collaboration. Additionally, it introduces Java programming concepts such as tokens, keywords, identifiers, and literals.

Uploaded by

amitbhatt
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/ 34

2024 - 25

CS -20 Network Technology and Administration

Bhavesh K. Hadiyal
HOD of Computer science
Department OMVVIM College
2024 - 25
Index
• Network concepts
o What is network?
o Use of network
• Network model: peer – to – peer, client – server
• Network Services
o File service,
o Print service,
o Comm. service,
o Data base service,
o Security service,
o Application service
• Network Access Methods
o CSMA / CD,
o CSMA / CA,
o Token passing,
o Polling
• Network Topologies: Bus, Ring, Star, Mesh, Tree, Hybrid
• Advanced Network Topologies Ethernet, CDDI, FDDI
• Communication Methods
o Unicasting,
o Multicasting,
o Broadcasting
• OSI reference model with 7 layers
• TCP/IP network model with 4 layers
Network concepts
● Computer networking is often an essential skill for many IT professionals, like network
engineers, systems administrators and network technicians.
● There are many industry terms, aspects and elements of computer networking, and your
depth of technical knowledge might help you secure an interview or offer during a job
search.
● According to Merriam-Webster, Network is usually an informally interconnected group
or association of different entities like a person, computers, radio stations, etc.

What is network?
 Computer networking refers to interconnected computing devices that can exchange
data and share resources with each other.
 A computer network is a system that connects two or more computing devices to
transmit and share information.
 "A Computer Network is defined as a set of two or more computing devices that are
linked together either via wired cables or wireless networks i.e., Wi-Fi with the purpose
of communicating, exchanging, sharing or distributing data, files and resources."

Each of the devices on the network can be thought of as a node. Computing devices include
everything from a mobile phone to a server.
Computer Networks are built using a collection of hardware (such as routers, switches, hubs,
and so forth) and networking software (such as operating systems, firewalls, or corporate
applications).
Computer networking is like having a group of friends who all have phones and can call or text
each other. In computer networking, instead of phones, we have computers and instead of
phone lines, we use cables, Wi-Fi, or other methods to connect them.
When computers are connected to a network, they can share information and resources, like
files, printers, and internet connections. This allows them to communicate with each other
quickly and easily, just like friends talking on their phones.
In simple words, a computer network is a group of computers and other devices that are
connected together so they can communicate and share resources like files and printers. It
allows devices to work together, share information, and access the internet.

Use of network?
Computer networks are used in various ways to facilitate communication, resource sharing,
and collaboration. Here are some common uses:
Communication: Computer networks enable individuals and organizations to communicate
with each other using various methods such as email, messaging, and video conferencing
GO to index page
Resource sharing: Networks allow users to share resources such as printers, scanners, and
files, which can improve efficiency and reduce costs.
Remote access: Networks enable users to access information and resources from anywhere in
the world, providing greater flexibility and convenience.
Collaboration: Networks facilitate collaboration by enabling users to work together on
projects, share ideas, and provide feedback in real time.
E-commerce: Computer networks are used extensively in e-commerce, enabling businesses to
sell products and services online and process payments securely.
Education: Networks are used in educational institutions to facilitate distance learning,
provide access to educational resources, and enable collaboration among students and
teachers.
Entertainment: Networks are used for entertainment purposes such as online gaming,
streaming movies and music, and social media.

There are multiple applications of computer networks including:


Business applications, Educational applications, Healthcare applications, Entertainment
applications, Military applications, scientific applications, Transportation applications, Banking
and finance applications.

Advantages of Uses of Computer Networks


 Improved communication and collaboration.
 Cost savings through resource sharing.
 Better data management and security.
 Increased flexibility with remote access.
 Enhanced productivity and efficiency
 Centralized Data Storage

Network model: peer – to – peer, client – server


In computer networks, there are two main types called "client-server" and "peer-to-peer."
Both let computers connect to share things like files and programs. However, they work
differently from each other.

What Is Peer-To-Peer?
Peer-to-peer (P2P) is a decentralized network architecture in which participants, called peers,
interact directly with each other without needing a central authority or server.
In a P2P network, each participant acts as both a client and a server, enabling them to share
resources and services directly with other peers. Here, all computers are equal.

GO to index page
History of P2P Networks
 In the 1980s the first use of P2P networks occurred after personal computers were
introduced.
 In August 1988, the internet relay chat was the first P2P network built to share text and
chat.
 In June 1999, Napster was developed which was a file-sharing P2P software. It could be
used to share audio files as well. This software was shut down due to the illegal sharing of
files. But the concept of network sharing i.e P2P became popular.
 In June 2000, Gnutella was the first decentralized P2P file sharing network. This allowed
users to access files on other users’ computers via a designated folder.

Types of P2P Networks


Unstructured P2P networks: In this type of P2P network, each device is able to make an equal
contribution. This network is easy to build as devices can be connected randomly in the
network. But being unstructured, it becomes difficult to find content. For example, Napster,
Gnutella, etc.
Structured P2P networks: It is designed using software that creates a virtual layer in order to
put the nodes in a specific structure. These are not easy to set up but can give easy access to
users to the content. For example, P-Grid, Kademlia, etc.
Hybrid P2P networks: It combines the features of both P2P networks and client-server
architecture. An example of such a network is to find a node using the central server.

P2P Network Architecture


In the P2P network architecture, the
computers connect with each other in a
workgroup to share files, and access to
internet and printers.
Each computer in the network has the
same set of responsibilities and
capabilities.
Each device in the network serves as both
a client and server.
The architecture is useful in residential
areas, small offices, or small companies
where each computer act as an
independent workstation and stores the
data on its hard drive.
Each computer in the network has the
ability to share data with other computers in the network.
The architecture is usually composed of workgroups of 12 or more computers.
GO to index page
Advantages of P2P Network
Easy to maintain: The network is easy to maintain because each node is independent of the
other.
Less costly: Since each node acts as a server, therefore the cost of the central server is saved.
Thus, there is no need to buy an expensive server.
No network manager: In a P2P network since each node manages his or her own computer,
thus there is no need for a network manager.
Adding nodes is easy: Adding, deleting, and repairing nodes in this network is easy.
Less network traffic: In a P2P network, there is less network traffic than in a client/ server
network.

Disadvantages of P2P Network


Data is vulnerable: Because of no central server, data is always vulnerable to getting lost
because of no backup.
Less secure: It becomes difficult to secure the complete network because each node is
independent.
Slow performance: In a P2P network, each computer is accessed by other computers in the
network which slows down the performance of the user.
Files hard to locate: In a P2P network, the files are not centrally stored, rather they are stored
on individual computers which makes it difficult to locate the files.

What is Client-Server?
In a client–server network, there is at least one dedicated central server that controls the
network, and a number of clients connect to the server to carry out specific tasks.
This is like a boss and employees setup. There's a main computer (server) that stores
information and manages resources.
Other computers (clients) connect to the server to access these resources, like files or
software.
It's structured and organized, like a company where everyone has a specific role.

History of Client-Server Networks


The client-server model emerged in the 1960s alongside the development of computer
networking. Initially, it involved mainframe computers serving multiple terminals.
By the 1980s, with the rise of LANs and PCs, it became decentralized, allowing PCs to act as
clients accessing resources from dedicated servers.
The standardization of protocols like TCP/IP in the 1980s and 1990s facilitated its widespread
adoption, especially with the growth of the internet and web servers.
Today, it continues to evolve with distributed computing technologies, enabling efficient
resource sharing and management across various networked environments.

GO to index page
How does Client-Server Architecture work?
The basic steps of how Client-Server Architecture works are:
1) In the first step, client sends a request to the server using the network medium. The request
can be a query, a command, or a
message.
2) In the second step, the server
receives the request and processes
it according to its logic and data. The
server may access its own resources
or other servers to fulfil the request.
3) In the third step, server sends a
response back to the client using the
network medium. The response can
be data, an acknowledgement, or an
error message.
4) Lastly, client receives the response and displays it to the user or performs further actions
based on it.

Types of Client-Server Networks


One-Tier architecture: consists of a simple program running on a single computer without
requiring access to the network.
Two-Tier architecture: consists of the client, the server, and the protocol that links the two
tiers.
Three-Tier architecture: consists of a presentation tier.
N-Tier architecture: divides an application into logical layers, which run on separate machines,
improve scalability, and add latency from the additional network communication.
N-Tier architecture can be closed-layer, in which a layer can only communicate with the next
layer down, or open-layer, in which a layer can communicate with any layers below it.

Advantages of Client-Server Model


Centralized: Centralized back-up is possible in client-server networks, i.e., all the data is stored
in a server.
Security: These networks are more secure as all the shared resources are centrally
administered. Data recovery is possible.
Performance: The use of the dedicated server increases the speed of sharing resources. This
increases the performance of the overall system.
Scalability: We can increase the number of clients and servers separately, i.e., the new
element can be added, or we can add a new node in a network at any time.
Capacity: The capacity of the Client and Servers can be changed separately.
Cost: Requires less maintenance cost.
GO to index page
Disadvantages of Client-Server Model
Risk of viruses: Trojans, and worms if present in the Server or uploaded into the Server.
Attack: Servers are prone to Denial of Service (DOS) attacks. Phishing or capturing login
credentials or other useful information of the user are common and MITM (Man in the
Middle) attacks are common.
Cheat: Data packets may be spoofed or modified during transmission.

Network Services
A network service is a capability that facilitates a network operation. It typically is provided by
a server (which can be running one or more services), based on protocols running at the
application layer in the Open Systems Interconnection (OSI) model of the network.
Network application layer provides data storage, manipulation, presentation, communication
or other capability which is often implemented using a client–server or peer-to-peer
architecture based on application layer network protocols.
Each service is usually provided by a server component running on one or more computers
(often a dedicated server computer offering multiple services) and accessed via a network by
client components running on other devices. However, the client and server components can
both be run on the same machine.

GO to index page

Characters
This group represents char, which represent symbols in a character set, like letters and
numbers.
char : It is 16 bit unsigned Unicode character. Range 0 to 65,535. example: char c='a';

Boolean
This group represent boolean, which is a special type for representing true/false values. They
are defined constant of the language. example: boolean b=true;
Java Tokens
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation.
These statements and expressions are made up of tokens.
In other words, we can say that the expression and statement is a set of tokens. The tokens
are the small building blocks of a Java program that are meaningful to the Java compiler.
The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program. The Java compiler identified these words as tokens.
These tokens are separated by the delimiters. It is useful for compilers to detect errors.
Remember that the delimiters are not part of the Java tokens.
GO to index page

Types of Tokens
o Keywords o Separators
o Identifiers o Comments
o Literals o Whitespace
o Operators

Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
GO to index page
Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. The label is also known as a special kind of identifier that is used
in the goto statement. There are some rules to declare identifiers are:
o Identifiers are case sensitive.
o Identifiers must begin with a letter, dollar sign or underscore.
o Apart from the first character, an identifier can have any combination of characters.
o Identifiers in Java are case sensitive.
o Java Identifiers can be of any length.
o Identifier name cannot contain white spaces.
o Any identifier name must not begin with a digit but can contain digits within.
o Most importantly, keywords can’t be used as identifiers in Java.

Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:
Operator Symbols
Literal Type
o Integer
Arithmetic 23 + , - , / , * , % int
o Floating Point
Unary 9.86++ , - - , ! double
o Character
Assignment false,
= ,true
+= , -= , *= , /=boolean
, %= , ^=
Relational 'K', '7',
==, '-' char
!= , < , >, <= , >=
o String
Logical "javatpoint"
&& , || String
o Boolean
Ternary null(Condition)? (Stat1) any: reference
(Stat2); type
Operators: In programming, Bitwise &,|,^,~
operators are the special Shift << , >> , >>>
symbol that tells the compiler to perform a special operation. Java provides different types of
operators that can be classified according to the functionality they provide. There are eight
types of operators in Java, are as follows:

o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Separators: The separators in Java is also known as punctuators. There are nine separators
in Java, are as follows:
separator <= ; | , | . | ( | ) | { | } | [ | ]
Note that the first three separators (; , and .) are tokens that separate other tokens, and the
last six (3 pairs of braces) separators are also known as delimiters.
For example, Math.pow(9, 3); GO to index page
o Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional
array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the
two statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates
a variable or method from a reference variable.

Comments: Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the following
two types of comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.

The JDK offers developers a choice of three Java comment types:


1. Inline Java comments, which begin with two slashes //
2. Block Java comments, which follow the structure /* */
3. JavaDoc comments on methods and classes /** */

Whitespace: White space is defined as the ASCII space character, horizontal tab character,
form feed character, and line terminator characters.
● Blank space, New line, Carriage return, Horizontal tab

Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For
example, a + b
Here, the + operator is used to add two variables a and b. Similarly, there are various other
arithmetic operators in Java.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
GO to index page
Assignment Operators Operator Example Equivalent to
Assignment operators are used in Java to assign = a = b; a = b;
values to variables. For example, int age; age = 5; += a += b; a = a + b;
Here, = is the assignment operator. It assigns the -= a -= b; a = a - b;
value on its right to the variable on its left. That is, 5 is *= a *= b; a = a * b;
assigned to the variable age. Let's see some more /= a /= b; a = a / b;
short hand assignment operators available in Java. %= a %= b; a = a % b;

Relational Operators
Relational operators are used to check the relationship between two operands. For example,
a < b; /*check if a is less than b*/  Here,< is the relational operator. It checks if a is less
than s or not. It returns either true or false.
Operator Description Example
== Is Equal To 3 == 5 returns false
!= Not Equal To 3 != 5 returns true
> Greater Than 3 > 5 returns false
< Less Than 3 < 5 returns true
>= Greater Than or Equal To 3 >= 5 returns false
<= Less Than or Equal To 3 <= 5 returns true
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary operator that
increases the value of a variable by 1. That is, ++5 will return 6.
Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without using it
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- Decrement operator: decrements value by 1
! Logical complement operator: inverts the value of a boolean

Logical Operators
Logical operators are used to check whether an expression is true or false. They are used in
decision making.
Operator Example Meaning
&& (Logical AND) expression1 && expression2 true only if both expression are true
|| (Logical OR) expression1 || expression2 true if any one expression is true
! (Logical NOT) !expression true if expression is false and vice versa
GO to index page
Bitwise Operators
Bitwise operators in Java are used to perform operations Operator Description
on individual bits. For example, Bitwise complement ~ Bitwise Complement
Operation of 35 & Bitwise AND
35 = 00100011 (In Binary) | Bitwise OR
~ 00100011 ^ Bitwise exclusive OR
________________
>> Right Shift
11011100 = 220 (In decimal)
<< Left Shift
Here, ~ is a bitwise operator. It inverts the value of each >>> Unsigned Right Shift
bit (0 to 1 and 1 to 0).

Ternary Operator
The ternary operator (conditional operator) is shorthand for the if-then-else statement.
For example, variable = Expression ? expression1 : expression2
Here's how it works.
If the Expression is true, expression1 is assigned to the variable.
If the Expression is false, expression2 is assigned to the variable.

Java Type Casting


Java supports two types of castings –
1. primitive data type casting and
2. reference type casting.
 primitive data type casting is when you assign a value of one primitive data type to another
type.
 Reference type casting is nothing but assigning one Java object to another object. It comes
with very strict rules and is explained clearly in Object Casting.
Java data type casting comes with 2 flavours. 1. Implicit casting 2. Explicit casting

In Java, there are also known as:


● Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
Note: This is also known as Implicit Type Casting.
● Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Note: This is also known as Explicit Type Casting.

Decision making statement


Selection statements are also known as branching statements or conditional or decision-
making statements.
Here are two types of decision making statements in Java. They are:
1. IF statements
2. switch statements GO to index page
(1) IF Statement:
(a) if...Statement:
IF statement consists of a Boolean expression followed by one or more statements.
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will
be executed. If not the first set of code after the end of the if statement (after the closing curly
brace) will be executed.
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
if( x < 20 )
{ System.out.print("This is if statement"); }
}
}
This would produce the following result:
This is if statement

(b) if...else Statement:


A if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax:
if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
else
{
//Executes when the Boolean expression is false
}
Example:
public class Test {
public static void main(String args[]) {
int x = 30;
if( x < 20 )
{ System.out.print("This is if statement"); }
else
{ System.out.print("This is else statement"); }
}
}
GO to index page
This would produce the following result:
This is else statement

(c) The if...else if...else Statement: (Multiple IF)


if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
● if can have zero or one else's and it must come after any else if's.
● if can have zero to many else if's and they must come before the else.
● Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
//Executes when the Boolean expression 3 is true
}
.
.
.
.
else
{
//Executes when the none of the above condition is true.
}

(d) Nested if...else Statement:


It is always legal to nest if-else statements which means you can use one if or else if statement
inside another if or else if statement.
Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
GO to index page
You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test {
public static void main(String args[]) {
int x = 30, y = 10;
if( x == 30 )
{ if ( y == 10 ) { System.out.print("X = 30 and Y = 10"); } }
}
}
This would produce the following result:
X = 30 and Y = 10

(2) The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.
Syntax:
switch(expression)
{
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
.
.
.
.
//You can have any number of case statements.
default : //Optional
//Statements
}
The following rules apply to a switch statement:
● The variable used in a switch statement can only be a byte, short, int, or char.
● You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
● The value for a case must be the same data type as the variable in the switch and it must
be a constant or a literal.
● When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
● When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
● Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
● A switch statement can have an optional default case. The default case can be used for
performing a task when none of the cases is true. GO to index page
Example:
public class Test {
public static void main(String args[]) {
char grade = 'C';
switch(grade)
{
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
case 'A' :
System.out.println("Excellent!");
break;
case 'C' :
case 'B' :
System.out.println("Well done");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
This would produce the following result:
Well done
Your grade is a C
Loops in Java
There may be a situation when we need to execute a block of code several number of times,
and is often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
(1) while Loop
(2) do...while Loop
(3) for Loop ( As of Java 5, the enhanced for loop (for each) was introduced. This is
mainly used for Arrays.)

(1) while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
while(Boolean expression)
{
//Statements
}
GO to index page
When executing, if the boolean_expression result is true, then the actions inside the loop will
be executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 12 )
{ System.out.print("\n value of x : " + x++ ); }
}
}
This would produce the following result:
value of x : 10
value of x : 11

(2) do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
do
{
//Statements
} while(Boolean expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the
loop execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements
in the loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test {
public static void main(String args[]) {
int x = 10;
do
{ System.out.print("\n value of x : " + x++ ); }while( x <= 12 );
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12

(3) for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times. A for loop is useful when you know how many times a
task is to be repeated. GO to index page
Syntax:
for(initialization; Boolean_expression; increment/decrement)
{
//Statements
}
Here is the flow of control in a for loop:
● The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
● Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop does not execute and flow of control jumps to the next
statement past the for loop.
● After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the Boolean
expression.
● The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After
the Boolean expression is false, the for loop terminates.
Example:
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+3)
{ System.out.print("\n value of x : " + x ); }
}
}
This would produce the following result:
value of x : 10
value of x : 13
value of x : 16
value of x : 19

(4) Enhanced for loop in Java:


As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
for(declaration : expression)
{
//Statements
}
● Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
● Expression: This evaluates to the array you need to loop through. The expression can
be an array variable or method call that returns an array.
GO to index page
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{ System.out.print( x + ”, ” ); }
System.out.print("\n");
String [] names ={"OM", "Jay", "Vijay", "Ajay"};
for( String name : names )
{ System.out.print( name + “, ” ); }
}
}
This would produce the following result:
10, 20, 30, 40, 50,
OM, Jay, Vijay, Ajay,

Jumping Statements
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside
any loop or a switch statement. The break keyword will stop the execution of the innermost
loop and start executing the next line of code after the block.
Syntax: The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
{
if( x == 30 ) { break; }
System.out.print(“\n” + x );
}
}
}
This would produce the following result:
10
20

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes
flow of control to immediately jump to the update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
GO to index page
Syntax: The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40};
for(int x : numbers )
{ if( x == 30 ) { continue; }
System.out.print(“\n” + x );
}
}
}

This would produce the following result:


10
20
40

The return Keyword:


In Java, the return keyword returns a value from a method. The method will return the value
immediately when the keyword is encountered. This means that the method will not execute
any more statements beyond the return keyword, and any local variables created in the
method will be discarded.
This is similar to how a break statement immediately exits a for loop and transfers control back
to the enclosing code block. To understand how this works, consider the following example:
public String fun(int a)
{
if(a<10)
return "Number less than 10";
if(a<100)
return "Number greater than 10 but less than 100";
if(a>=100)
return "Number greater than or equal to 100";
}
In the code above, if you pass the number 8 to the function, it will return the string “Number
less than 10” and move on to the function’s caller.
Similarly, if parameter a is less than 100, the function returns “Number greater than 10 but
less than 100.” If the parameter is greater than or equal to 100, the program returns “Number
greater than or equal to 100.”
Every Java method must include a return type in its declaration. If there’s nothing to return,
use void as the return type.
There are several return types classified in one of two ways.
Primitive types like int, float, and double represent raw values, whereas non-primitive types
can represent things like classes, arrays, or interfaces.
GO to index page

Non-Primitive (Reference) Data type


A reference data type is used to refer to an object. A reference variable is declared to
be of specific and that type can never be change. Classes, Arrays, Interface are an example of
Non Primitive types.

Java Array
Normally, array is a collection of similar type of
elements that have contiguous memory location.
Java array is an object that contains elements of
similar data type. It is a data structure where we store similar elements. We can store only
fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Advantage of Java Array
● Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
● Random access: We can get any data located at any index position.
Disadvantage of Java Array
● Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in java.

Types of Array in java


There are two types of array.
1. Single Dimensional Array 2. Multidimensional Array

1. Single Dimensional Array in java


It is a simple array which can store the multiple elements inside which must belong to the same
data type.
Syntax : dataType[] arr; (or) dataType arr[];

2. Multidimensional array in java


In such case, data is stored in row and column based index (also known as
matrix form). There are three types of array.
1. Multidimensional Array
2. Rectangular Array
3. Jagged Array

Multidimensional Array
Syntax : dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


int[][] arr=new int[3][3]; //3 row and 3 column
Example to initialize Multidimensional Array in java
arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5;
arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9; GO to index page
Rectangular array in java
Rectangular arrays are, as the name implies, arrays which look like a table. A 2D rectangular
array can be represented as a plane rectangle, and a 3D rectangular array can be represented
as a cuboid. [4] Whatever the case, the idea is the same – in rectangular arrays, every row has
the same number of columns.

Jagged array in java


It is an array of arrays where each element is, in turn, an array. A special feature of this type
of array is that it is a Multidimensional array whose each element can have different sizes.
For Example, a two-dimensional array in Java is an array of single dimension array. In the case
of a two-dimensional array, each one-dimensional array will have different columns.

Given below is a pictorial representation of a Jagged array.


From the above pictorial representation, we got an idea of how does it look. Above shown is a
two-dimensional Jagged array. Each individual element of this array is a one-dimensional array
that has varied sizes as shown above.
The first 1D array has 3 columns; the second row has 2 columns while the third has 4 columns.
Create & Initialize Jagged Array
While creating an array of arrays you only specify the first dimension that represents a number
of rows in the array.
You can create a two-dimensional jagged array as follows:
int myarray[][] = new int[3][];
In the above declaration, a two-dimensional array is declared with three rows.
Once the array is declared, you can define it as a Jagged array as shown below:
myarray[1] = new int[2];
myarray[2] = new int[3];
myarray[3] = new int[4];

The first statement above indicates that the first row in the 2D array will have 2 columns.
The second row will have 3 columns while the third row will have 4 columns thereby making it
a Jagged array.
Once the array is created, you can initialize it with values. Note that if you don’t explicitly
initialize this array (as in the above case), then it will take the default values as initial values
depending on the data type of the array. GO to index page
Initializing a Jagged array is as shown below:
int[][]myarray ={ new int[] { 1, 2, 3 }; new int[] { 4, 5, 6, 7 }; new int[] { 8, 9 }; };
As you can see above, the new operator is omitted and the array is initialized as well as
declared in the same statement.
You can also omit all the new operators altogether and have a declaration and initialization
statement as shown below.
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9 } };
The program below initializes a ragged array by assigning initial values to each row. Here each
row of the array is initialized to the column values.
Example:
class Main {
public static void main(String[] args) {
int myarray[][] = new int[3][]; // Declare a 2-D array with 3 rows
// define and initialize jagged array
myarray[0] = new int[]{1,2,3};
myarray[1] = new int[]{4,5};
myarray[2] = new int[]{6,7,8,9,10};
// display the jagged array
System.out.println("Two dimensional Jagged Array:");
for (int i=0; i&lt;myarray.length; i++) {
for (int j=0; j&lt;myarray[i].length; j++) System.out.print(myarray[i][j] + " ");
System.out.println();
}
}
}
Command Line Argument Array
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used
as an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
Example:
class CommandLineExample {
public static void main(String args[]) {
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample OM
Output: Your first argument is: OM GO to index page

OOP Concepts
(Class, Object, Encapsulation, Inheritance, Polymorphism)

Object Oriented Programming


In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm
that provides many concepts such asinheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming
paradigm where everything is represented as an object, is known as truly object-oriented
programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is
a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
1. Object 4. Polymorphism
2. Class 5. Abstraction
3. Inheritance 6. Encapsulatio

Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
✔ object is a member (also called an instance) of a Java class.
✔ Object is a real world entity and runtime entity.
✔ objects are the things or the units of code that are eventually derived from the process.
✔ An object is an instance of a class.
✔ Objects have states and behaviors.
✔ An object is an entity that has a state, specific behavior, and has been created for a specific
purpose.

Class
✔ Collection of objects is called class. It is a logical entity.
✔ It is also called a blue print of your whole programming structure which contains all the
members of your class.
✔ class is a basic building block of an object-oriented language
✔ class is a logical template to create objects that share common properties and methods.
✔ class is Blueprint of an object which describes/ shows all the functions and data that are
provided by an object of a specific class
✔ A class is a user defined blueprint or prototype from
which objects are created.
✔ A class can be defined as a template/blueprint that
describes the behavior/state that the object of its type
support.
GO to index page
Difference between object and class
There are many differences between object and class. A list
of differences between object and class are given below:
No. Object Class
1) Object is an instance of a class. Class is a blueprint or template from which
objects are created.
2) Object is a real world entity such as pen, Class is a group of similar objects.
laptop, mobile, bed, keyboard etc.
3) Object is a physical entity. Class is a logical entity.
4) Object is created through new Class is declared using class keyword e.g.
keyword e.g. Abc o1=new Abc(); class Abc{}
5) Object is created many times as per Class is declared once.
requirement.
6) It allocates memory when it is created. It doesn't allocated memory when it is created.
Inheritance
When one object
acquires all the properties
and behaviours of
parent object i.e. known
as inheritance. It
provides code reusability.
It is used to achieve
runtime polymorphism.
Different Terms used in Inheritance
Parent Class - Child Class
Super Class - Sub Class
Base Class - Derived Class

Polymorphism
“Poly” means many and “Morph” means Forms. One Name
Many Forms.
When one task is performed by different ways is known as
polymorphism.
For example: to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to
achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing. In java, we use abstract class and interface to
achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is
known as encapsulation.
For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private here. GO to index page
The following represents the data hiding (encapsulation) structure in class.
Advantage of OOPs over Procedure-oriented programming language
● OOPs make development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
● OOPs provide data hiding whereas in Procedure-oriented programming language a global
data can be accessed from anywhere.
● OOPs provide ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming
language.
Difference between object-oriented programming language and
object-based programming language

Object based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object based programming languages.
GO to index page
Creating and using Class with members
 A class in Java 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.
 Class does not occupy memory.
 Class is a group of variables of different data types and a group of methods.
A Class in Java can contain:
Data member, Method, Constructor, Nested Class, Interface.
Example:
class Student { Class Declaration in Java
int id; // data member (Instance variable) access_modifier class <class_name>
String name; // data member (Instance variable) {
public static void main(String args[]) { data member;
Student s1 = new Student();// creating an object method;
System.out.println(s1.id); constructor;
System.out.println(s1.name); nested class;
} interface;
} }
Output:
0
null

Constructor
 A constructor in Java is a special method that is used to initialize objects.
 In Java, Constructor is a block of codes similar to the method.
 It is called when an instance of the class is created.
 At the time of calling the constructor, memory for the object is allocated in the memory.
 It is a special type of method that is used to initialize the object.
 Every time an object is created using the new() keyword, at least one constructor is called.
It is not necessary to write a constructor for a class. It is because the java compiler creates a
default constructor (constructor with no arguments) if your class doesn’t have any.
How Java Constructors are Different From Java Methods?
 must have the same name as the class within which it is defined it is not necessary for the
method in Java.
 Constructors do not return any type while method(s) have the return type or void if does
not return any value.
 Constructors are called only once at the time of Object creation while method(s) can be
called any number of times.
Types of Constructors in Java
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor GO to index page
1. Default Constructor (No-Argument Constructor) in Java
A default constructor is one that doesn’t take any arguments. It’s also called a no-argument
constructor. If not provided, the Java compiler will automatically generate one for you.
2. Parameterized Constructor
A parameterized constructor takes arguments to initialize the object’s attributes.
In addition, these types of constructors are usually used fors constructor overloading to
differentiate between multiple constructors with different data types.
3. Copy Constructor
A copy constructor is used to create an exact copy of an object. It takes an object of the same
class as a parameter and copies its attributes.

finalize() method
The java.lang.Object.finalize() is called by the garbage collector on an object when garbage
collection determines that there are no more references to the object. A subclass overrides
the finalize method to dispose of system resources or to perform other cleanup.
There are other ways to release the used resources in Java like the close() method in case of
file handling or destroy() method. But, the issue with these methods is they don't work
automatically, we have to call them manually every time.

Declaration
Following is the declaration for java.lang.Object.finalize() method
Overriding is a feature in Java, where parent class(superclass) methods can be reimplemented
in child classes(subclass).
While overriding any parent class method: name, return type, and parameters of the method
should be the same in child class.
Object class is the superclass of all the classes in Java hence, Object class methods like
the finalize() method can be overridden.

Example
public class JavafinalizeExample1 {
public static void main(String[] args) {
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
System.gc(); // calling garbage collector
System.out.println("end of garbage collection"); }
@Override
protected void finalize()
{ System.out.println("finalize method called"); }
}
Output:
2018699554
end of garbage collection
finalize method calleds
GO to index page
Static and Non-Static Members
There are three types of variables in Java:
1. Local Variables
2. Instance Variables
3. Static Variables
The Local variables and Instance variables are together called Non-Static variables. Hence it
can also be said that the Java variables can be divided into 2 categories:
● Static Variables:
⮚ When a variable is declared as static, then a single copy of the variable is created and
shared among all objects at a class level. Static variables are, essentially, global variables.
⮚ All instances of the class share the same static variable.
⮚ Important points for static variables: We can create static variables at class level only.
● Non-Static Variable
Instance Variables:
⮚ Instance variables are non-static variables and are declared in a class outside any method,
constructor or block.
⮚ As instance variables are declared in a class, these variables are created when an object
of the class is created and destroyed when the object is destroyed.
⮚ Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
⮚ Initialisation of Instance Variable is not Mandatory. Its default value is 0
⮚ Instance Variable can be accessed only by creating objects.
Local Variables:
⮚ A variable defined within a block or method or constructor is called local variable.
⮚ These variables are created when the block in entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
⮚ The scope of these variables exists only within the block in which the variable is declared.
i.e. we can access this variable only within that block.
⮚ Initialisation of Local Variable is Mandatory.
⮚ The main differences between static and non static variables are:
Static variable Non static variable
Static variables can be accessed using class Non static variables can be accessed using
name instance of a class
Static variables can be accessed by static Non static variables cannot be accessed
and non-static methods inside a static method.
Static variables reduce the amount of Non static variables do not reduce the
memory used by a program. amount of memory used by a program
Static variables are shared among all Non static variables are specific to that
instances of a class. instance of a class.
Static variable is like a global variable and is It is like a local variable and they can be
available to all methods. accessed through only instance of a class.
It is declared with the “static” keyword. No need to declare with any keyword.
GO to index page
It is a member of a class but is not a It belongs to a class and is both a member
member of an instance of that class. and an instance of that class.
Only static methods and data members It can access static and non-static data
from the same class or another class may members and methods of the class.
be accessed by it.
Memory allocation happens only once. When the method is called, memory is
allocated.
No object needs to be created in order to To access it, you must create a class object.
access it.
It uses compile-time or early binding. It uses dynamic or runtime binding.
It cannot be overridden. It can be overridden.
Overloading (Constructor & Method)
Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded
constructor is called based on the parameters specified when a new is executed.
The constructor overloading can be defined as the concept of having more than one
constructor with different parameters so that every constructor can perform a different task.
When do we need Constructor Overloading?
Sometimes there is a need of initializing an object in different ways. This can be done using
constructor overloading.
What is the Difference between Method Overloading and Constructor Overloading in Java?
Constructor is used to initialize an object whereas a method is used to perform certain
functions of a class.
Constructors are invoked implicitly when an object is created whereas methods are called
explicitly by the user.
Constructors don’t have a return type whereas methods have a return type of either a type of
Object or void.
Constructor should have the same name as that of the class whereas method name should not
be of the same name as that of class.

Varargs, IIB (Instance Initialization Block) in Java


Varargs
Let’s suppose you are creating a Java method. However, you are not sure how many arguments
your method is going to accept. To address this problem, Java 1.5 introduced varargs. Varargs
is a short name for variable arguments. In Java, an argument of a method can accept arbitrary
number of values. This argument that can accept variable number of values is called varargs.
The syntax for implementing varargs is as follows:
accessModifier methodName(datatype… arg)
{
// method body
} GO to index page
In order to define vararg, ... (three dots) is used in the formal parameter of a method.
A method that takes variable number of arguments is called a variable-arity method, or simply
a varargs method.
Example using varargs:
class Test1 {
// A method that takes number of integer arguments.
static void fun(int... a) {
System.out.println("Number of arguments: " + a.length);
for (int i : a) System.out.print(i + " "); // using for each loop to display contents of a
}
public static void main(String args[]) {
// Calling the varargs method with different number of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}
Output
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0

IIB (Instance Initialization Block)


Instance Initializer block is used to initialize the instance data member. It run each time when
object of the class is created.
The initialization of the instance variable can be done directly but there can be performed
extra operations while initializing the instance variable in the instance initializer block
use of instance initializer block
while we can directly assign a value in instance data member
For example:
class Bike{ int speed=100; }
Why use instance initializer block?
Suppose I have to perform some operations while assigning value to instance data member
e.g. a for loop to fill a complex array or error handling etc.
class Bike {
int speed;
Bike7() { System.out.println("speed is "+speed); }
// instance initializer block
{ speed=100; }
}

GO to index page

You might also like