Unit 1
Unit 1
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.
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.
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.
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.
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 */.
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.
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.
}
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
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.
Multidimensional Array
Syntax : dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];
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<myarray.length; i++) {
for (int j=0; j<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
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.
GO to index page