Java Data Structures & Algorithms Guide
Java Data Structures & Algorithms Guide
Table of Content
AIM
1. Brief idea of algorithms,
2. Asymptotic notations,
3. The notion of time and space complexity.
4. Introduce object-oriented programming (using Java).
5. Arrays: Representation of Linear Arrays in Memory,
6. Single-Dimensional Arrays With Traversal, Selection,
Searching, Insertion, Deletion, Sorting Operations.
7. Two-Dimensional Arrays, Array of Strings,
Multidimensional Arrays,
8. Variable Length Arrays,
9. Sets and Maps.
What is an Algorithm ?
if (test) {
statement;
...
statement;
}
• Example:
double gpa = [Link]();
if (gpa >= 2.0) {
[Link]("Application accepted.");
}
The if/else statement
Executes one block if a test is true, another if false
if (test) {
statement(s);
} else {
statement(s);
}
• Example:
double gpa = [Link]();
if (gpa >= 2.0) {
[Link]("Welcome to Mars University!");
} else {
[Link]("Application denied.");
}
Nested if/else
• Example:
if (number > 0) {
[Link]("Positive");
} else if (number < 0) {
[Link]("Negative");
} else {
[Link]("Zero");
}
Nested if/else/if
• If it ends with else, one code path must be taken.
• If it ends with if, the program might not execute any path.
if (test) {
statement(s);
} else if (test) {
statement(s);
} else if (test) {
statement(s);
}
• Example:
if (place == 1) {
[Link]("You win the gold medal!");
} else if (place == 2) {
[Link]("You win a silver medal!");
} else if (place == 3) {
[Link]("You earned a bronze medal.");
}
Iteration Statements
• Repetition statements allow us to execute a group of
statements multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
• the while loop
• the do loop
• the for loop
• The programmer should choose the right kind of loop for
the situation
The while Statement
• A while statement has the following syntax:
while ( condition )
statement;
true false
statement
The while
• An example of aStatement
while statement:
int count = 1;
while (count <= 5)
{
[Link] (count);
count++;
}
• If the condition of a while loop is false initially, the statement is never executed
• Therefore, the body of a while loop will execute zero or more times
The while Repetition
Structure
• Flowchart of while loop int product
product == 2;
2;
int
while (( product
while product <= <=
int product = 2 1000 ))
1000
product == 22 **
product
product;
product;
true
product <= 1000 product = 2 * product
false
Example--Parts of a while
loop
int x = 1;
while (x < 10) {
[Link](x);
x++;
}
• Label the following loop
int product = 2;
while ( product <= 1000 )
product = 2 * product;
Nested Loops
• Similar to nested if statements, loops can be nested as
well
• That is, the body of a loop can contain another loop
• For each iteration of the outer loop, the inner loop
iterates completely
Nested Loops
• How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
[Link] ("Here");
count2++;
}
count1++;
}
The
• A dodo Statement
statement has the following syntax:
do
{
statement;
}
while ( condition )
• The statement is executed once initially, and then the condition is evaluated
• The statement is executed repeatedly until the condition becomes false
Logic of a do Loop
statement
true
condition
evaluated
false
The do Statement
• An example of a do loop:
int count = 0;
do
{
count++;
[Link] (count);
} while (count < 5);
statement
condition
evaluated
true
condition
true false
evaluated
statement
false
Choosing a Loop Statement
• If you know how many times the loop will be iterated, use a for
loop.
• If you don’t know how many times the loop will be iterated, but
• it could be zero, use a while loop
• it will be at least once, use a do-while loop.
• Generally, a while loop is a safe choice.
The
• A forfor Statement
statement has the following syntax:
condition
evaluated
true false
statement
increment
The for Statement
• A for loop is functionally equivalent to the following
while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
For Loop Example
class ForLoop
{
public static void main(String args[])
{
for(int i=1;i<=3;i++)
{
[Link](i); }
}
}
Because
Asymptotic notation (Big Oh )
Example 2
Asymptotic notation (Big Oh )
Example 2
Asymptotic notation (Big Oh )
Example 3
Asymptotic notation (Big Oh )
Example 3
Hence
Asymptotic notation (Big Omega )
Asymptotic notation (Big Omega )
Asymptotic notation (Big Omega )
Example 4
Asymptotic notation (Big Omega )
Example 4
Asymptotic notation (Theta)
Asymptotic notation (Theta)
Example 7
Asymptotic notation (Theta)
Example 7
is true
Asymptotic notation (Little Oh )
Asymptotic notation (Little Oh )
Example 9
Asymptotic notation (Little Oh )
Example 9
Asymptotic notation (Little Oh )
Example 10
Asymptotic notation (Little Oh )
Example 10
Asymptotic notation (Little omega )
Asymptotic notation (Little omega )
Example 11
Asymptotic notation (Little omega )
Example 11
Asymptotic notation (Little Oh omega )
Example 12
Asymptotic notation (Little Oh omega )
Example 12
• Simplicity
• Object Oriented
• Platform Independent
• Distributed
• Robust & Secure
• Multi-Threaded
• Compiled and Interpreted
First Java Application Program...
class HelloWorld
{
public static void main(String args[ ])
{
[Link](“Hello World”);
}
}
First Java Application Program...
• Explanation:
Explanation:
Second statement class HelloWorld
Declares a class name HelloWorld so as to place
everything inside this class.
Third statement public static void main(String args[ ])
Defines a method main. This is the starting point for any
java program.
First Java Application Program...
• Fourth statement is
• 1. Primitive Types
• 2. Reference Types
Data Types in Java...
• int a=20;
Boolean Variables...
A) Integer Constants
B) Real Constants
C) Single Character Constants
D) String Constants
String Literals...
• For example :
• String poem = “Java supports Multithreading”;
Boolean Literals...
a result.
3. Arithmetic Operators
4. Bitwise Operators
5. Relational Operators
6. Logical Operators
7. Ternary Operators
8. Comma Operators
9. Instanceof Operators
<variable> = <expression>
one.
• increment operator:
• decrement operator: --
Common Shorthand
a = a + 1; a++; or ++a;
a = a - 1; a--; or --a;
int j, p, q, r, s;
j = 5;
p = ++j; // j = j + 1; p
= j;
[Link]("p = " +
p);
q = j++; // q = j; j
= j + 1;
[Link]("q = " +
q);
[Link]("j = " +
j);
r = --j; // j = j -1; r
= j;
[Link]("r = " +
r);
s = j--; // s = j; j
= j - 1;
} > java example
[Link]("s = " +
s);
} p = 6
q = 6
j = 7
r = 6
s = 6
>
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Arithmetic Operators
• The arithmetic operators are used to construct mathematical expressions
as in algebra.
values.
operations.
c = a | b; /* 61 = 0011 1101 */
[Link]("a | b = " + c );
between them.
• Relational operators are used to test whether two values are equal,
Primitives
• Greater Than >
• Less Than <
• Greater Than or Equal >=
• Less Than or Equal <=
> Checks if the value of left operand is greater than the value
of right operand, if yes then condition becomes true.
&& Called Logical AND operator. If both the operands are non
zero then then condition becomes true.
}
}
> java Example
f && f false
f && t false
t && f false
t && t true
>
}
}
> java Example
f || f false
f || t true
t || f true
t || t true
>
}
}
> java Example
!f true
!t false
>
comma operator.
• Usually when people think about commas in the java language they think
i++, j = i * 2) {
} ///:~
• Only static variables get memory location, methods will not have separate
memory location like variables.
• Static Methods are just identified and can be accessed directly without
object creation.
Static variable:-
For Example company name of employees, college name of students etc. Name of the college is
common for all students.
Administrator
The static variable allocate memory only Display
once in class areaRetrieve
at the time of class loading.
User Info
Account
User Profile
Info
Advantage of static variable
User Account Info
• Using static variable we make our program memory efficient (i.e. it saves memory).
Validate
Update
User Info
Enter/Update/ Delete
Update/Delete User Info
User Info
When and why we use static variable
Suppose we want to store record of all employee of any company, in this case employee id is unique
for every
Access employee
User Info but company name is common for all.
When we create a static variable as a company name then only once memory is allocated otherwise it
Administrator
Display Retrieve User Info
allocate a memory space each time for every employee.
Account
User Profile
Info
Validate
Update
User Info
Enter/Update/ Delete
Update/Delete User Info
User Info
Example of static variable.
class Student
Administrator
{ Display Retrieve User Info
Account
int roll_no; User Profile
Info
String name;
User Account Info
static String College_Name="ITM";
} Validate
Update
User Info
Enter/Update/ Delete
Update/Delete User Info
User Info
class StaticDemo
{
public static void main(String args[])
Student s2=new Student();
{
s2.roll_no=200;
Student s1=new Student(); [Link]="zyx";
[Link](s2.roll_no);
s1.roll_no=100;
[Link]([Link]);
[Link]="abcd"; [Link](Student.College_Name);
[Link](s1.roll_no); }
}
[Link]([Link]);
[Link](Student.College_Na
me);
Static Variables
Any instance variable can be declared static by including the word “static”
immediately before the type specification
public
public class
class StaticStuff
StaticStuff {
{
Access User Info public
public static
static double
double staticDouble;
staticDouble;
public
public static
static String
String staticString;
staticString;
.. .. ..
}
}
Administrator
What’s Different about a static variable?
Display Retrieve User Info
1) A static variable can be referenced
Account
either using its class name or
an name object. User Profile
2) Instantiating a second object ofInfo
the same type does not increase
the number of static variables.
User Account Info
Example StaticStuff s1, s2;
s1 = new StaticStuff();
s2 = new StaticStuff();
Validate
[Link]
Update = 3.7;
User Info
Enter/Update/ Delete [Link]( [Link] );
Update/Delete User Info
User Info [Link]( [Link] );
[Link] = “abc”;
[Link] = “xyz”;
[Link]( [Link] );
©[Link](
2006 Pearson Addison-
[Link] );
Important
• We can not declare local variables as static it leads to compile time
error "illegal start of expression".
• Because being static variable it must get memory at the time of
class loading, which is not possible to provide memory to local
variable at the time of class loading.
• All static variables are executed by JVM in the order of they defined
from top to bottom.
• JVM provides individual memory location to each static variable in
method area only once in a class life time.
Life time and scope:
• Static variable get life as soon as class is loaded into JVM and is
available till class is removed from JVM or JVM is shutdown.
• And its scope is class scope means it is accessible throughout the
class.
Static Methods
In Java it is possible to declare methods to belong to a class rather
than an object. This is done by declaring them to be static.
theAccess
declaration
User Info public
public class
class DemoStatic
DemoStatic {
{
Static methods are declared by
inserting the word “static” public
public static
static int
int sum(int
sum(int n)
n) { {
int
int total
total = = 0;
0;
immediately for
for (int
(int k=0;
k=0; k!=n;
k!=n; k++)
k++) { {
after the scope specifier (public,
Administrator
total
total = = total
total ++ k;
k;
private or protected). }
}Display Retrieve User Info
Account
return
return total;
total;
User Profile
}
} Info
}
}
User Account Info
the call
Validate
Static methods are called using the int
int x=10;
x=10;
Update
...
... User Info
name of their class in place Delete
Enter/Update/ of Update/Delete User Info
User Info Int
Int result
result = = [Link](x);
[Link](x);
an object reference.
Static Methods - Why?
Static methods are useful for methods that are disassociated from all objects, excepting their parameters.
A good
Access User example
Info of the utility of static method is found in the standard Java class,
called Math.
public
public class
class Math
Math {
{
public
public static
static double
double abs(double
abs(double d) d) {...}
{...}
Administrator
public
public static
static int
int abs(int
abs(int k)
k) {...}
{...}
Display Retrieve User Info
public static double cos(double
public static double cos(double Account d) {...}
d) {...}
public User Profile
public static
static double
double pow(double
pow(double b,
b, double
double exp)
Info
exp) {...}
{...}
public
public static
static double
double random()
random() {...}
{...}
public
public static
static int
int round(float
round(float f)f) {...}
{...}
User Account Info
public
public static
static long
long round(double
round(double d) d) {...}
{...}
public
public static
static double
double sin(double
sin(double d) d) {...}
{...}
public
public static
static double
double sqrt(double d)
d) {...}
sqrt(doubleValidate {...}
Update
public
public static
static double
double tan(double d)
tan(double Userd) {...}
{...}
Info
Enter/Update/ Delete
.. .. .. User Info Update/Delete User Info
}
}
Static Method Restrictions
Since a static method belongs to a class, not an object, there are limitations.
The body of a static method cannot reference any non-static (instance) variable.
Access User Info
The body of a static method cannot call any non-static method unless it is applied to some other
instantiated object.
However, ...
Administrator
public
public class
class run
run {
{
public
public static
static void
void main(String[]
main(String[] args)
args) {
{ User Account Info
Driver
Driver driver
driver = = new
new Driver();
Driver();
}
}
Validate
}
} Update
User Info
Enter/Update/ Delete
Update/Delete User Info
User Info
Comparator class with Static methods
/* [Link]: A class with static data items comparison class MyClass {
methods*/ public static void main(String args[])
{
class Comparator { String s1 = "Melbourne";
public static int max(int a, int b) String s2 = "Sydney";
{
String s3 = "Adelaide";
if( a > b)
return a; Directly accessed using
int a = 10; ClassName (NO Objects)
else
int b = 20;
return b;
}
[Link]([Link](a, b));
// which number is big
public static String max(String a, String b)
{
[Link]([Link](s1, s2));
if( [Link] (b) > 0) // which city is big
return a; [Link]([Link](s1, s3));
else // which city is big
return b; }
} }
}
Order of execution of static variables and
main method:
• First all static variables are executed in the order they defined from top to bottom
then main method is executed.
Example Program:
class StaticDemo
{
static int a=m1();
static int m1() {
[Link]("variable a is created");
return 10;
}
static int b=m2();
static int m2(){
[Link]("variable b is created");
return 20;
}
public static void main(String [] args){
[Link]("in main method"); OUTPUT
[Link]("a="+a); 10
[Link]("b="+b); 30
} 30
} 30
Static block in Java
• Static block also known as static initializer
• Static blocks are the blocks with static keyword.
• Static blocks wont have any name in its prototype.
• Static blocks are class level.
• Static block will be executed only once.
• No return statements.
• No arguments.
• No this or super keywords supported.
When and where static blocks will be executed?
0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91
scores 79
87
94
82
67
98
87
81
74
91
Declaring Arrays
• The scores array could be declared as follows:
int[] scores = new int[10];
• The type of the variable scores is int[] (an array of
integers)
• Note that the array type does not specify its size, but
each object of that type has a specific size
• The reference variable scores is set to a new array
object that can hold 10 integers
• An array is an object, therefore all the values are
initialized to default ones (here 0)
Declaring Arrays
• Some other examples of array declarations:
2D Array
In Java, multidimensional arrays are actually arrays of arrays.
These, as you might expect, look and act like regular
multidimensional arrays.
Multidimensional Arrays...
O/P: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 in 4 lines.
Multidimensional Arrays...
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++; }
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
[Link](twoD[i][j] + " ");
[Link](); } }}
Multidimensional Arrays...
O/P: 0
12
345
6789
The String type is used to declare string variables. You can also
declare arrays of strings. A quoted string constant can be
assigned to a String variable. A variable of type String can be
assigned to another variable of type String. You can use an object
of type String as an argument to println( ).
Alternative Way
The String class contains several methods that you can use. Here
are a few. You can test two strings for equality by using equals( ).
You can obtain the length of a string by calling the length( )
method. You can obtain the character at a specified index within
a string by calling charAt( ). The general forms of these three
methods are shown here:
• Wrapper class is wrapper around a primitive data type because they "wrap" the
primitive data type into an object of that class.
What is Wrapper Class?
• Each of Java's eight primitive data types has a class dedicated to it.
• They are one per primitive type: Boolean, Byte, Character, Double, Float, Integer,
Long and Short.
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean
Difference b/w Primitive Data Type and
Object of a Wrapper Class
• The following two statements illustrate the difference between a primitive data type
and an object of a wrapper class:
int x = 25;
• if we use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class.
• Similarly, if we use a number object when a primitive is expected, the compiler un-boxes the object.
• When x and y are assigned integer values, the compiler boxes the integers because x and y are integer
objects.
• In the println() statement, x and y are unboxed so that they can be added as integers.
Unboxing
• “Unboxing” means taking an Integer object and
assigning its value to a primitive int.
• This is done using the .intValue( ) method.
• Example;
Integer z = new Integer(7); // box
int y = [Link]( ); // unbox
Numeric Wrapper Classes
• All of the numeric wrapper classes are subclasses of the abstract class Number .
• parseInt()
• parseFloat()
• parseDouble()
• parseLong()
…
Features of Numeric Wrapper Classes
• All the wrapper classes provide a static method toString to provide the string
representation of the primitive values.
Example:
public static String toString (int a)
Features of Numeric Wrapper Classes
• All numeric wrapper classes have a static method valueOf, which is used to create a
new object initialized to the value represented by the specified string.
public static DataType valueOf (String s)
Example:
Integer i = [Link] (“135”);
Double d = [Link] (“13.5”);
Methods implemented by subclasses of
Number
boolean equals(Object obj)
• The methods return true if the argument is not null and is an object of the same type
and with the same numeric value.
Character Class
• Character is a wrapper around a char.
Here, ch specifies the character that will be wrapped by the Character object being
created.
• To obtain the char value contained in a Character object, call charValue( ), shown here:
char charValue( );
• In the second version, if boolString contains the string “true” (in uppercase or
lowercase), then the new Boolean object will be true. Otherwise, it will be false.
The ArrayList Class
• The ArrayList class is part of the [Link] package
• An ArrayList is like an array, but it automatically grows
and shrinks as elements are added or deleted (so, there
are never ANY empty elements in an ArrayList)
• Items can be inserted or removed with a single method
call
• It stores references to the Object class, which allows it to
store ANY kind of object – so, you can store different
types in the same array
• We cannot store primitive types (int, double, char,
boolean) in an ArrayList. Instead, you would store
their Wrapper Class equivalents:
• Integer
• Double
• Character
• Boolean
ArrayList Syntax
• Import [Link]
• ArrayList is a class, so you must instantiate an object of it
• If you want to add an object (such as a String) to an ArrayList, there
is no special syntax. However, if you want to add a “primitive type”
(such as int, double, char), you must add using a wrapper class.
Commonly used ArrayList methods:
• add (obj) // adds obj at the end of the list
• add (index, obj) // adds obj at the specified index
• set (index, obj) // replaces the value at the specified index with obj
• get (index) // returns the object at the specified index
• indexOf(obj) // finds the index of the specified obj
• remove (index) // deletes the object at the specified index
• size ( ) // returns the size of the ArrayList
• import [Link];
•
• public class RemoveMethod {
• public static void main(String[] args) {
• // creating an ArrayList having default size 5
• ArrayList<String> arr = new ArrayList<String>(5);
• // Adding elements to the ArrayList
• [Link]("Helen");
• [Link]("Paul");
• [Link]("Elanie");
• [Link]("Marco");
• [Link]("The list of the size is: " + [Link]());
• // Showing all the elements in the ArrayList
• for (String name : arr) {
• [Link]("Name is: " + name);
• }
• // Removing element available at position 1
• [Link](1);
• [Link]("\
nAfter removing the element the size of the ArrayList is: " + [Link]());
• // Showing all the elements in the ArrayList
• for (String name : arr) {
• [Link]("Name is: " + name);
• } } }
• When using an ArrayList, you might get this compiler
message:
filename uses unchecked or unsafe operations. Note: Recompile with -
Xlint:unchecked for details.
• This is just a warning, not an actual error. You can ignore
it.
Review: static methods
• A static method can be called without having to create
an object.
• It is called directly by using the class name (example:
[Link]( ) )
• It makes sense to make a method static when that
method doesn’t have to be unique for each object that
calls it.
• Demo: StaticMethodClass, StaticMethodClient
Static variables
• A variable can also be declared with the keyword static.
• Just like a static method, a static variable is not accessed
through an object. It is accessed by using the name of the
class itself.
• Why use a static variable? When that variable is not unique
to each object of the class; when it is the same for all
objects of the class.
• Now we know where instance variables get their name: they
are unique for every instance (every object) of the class.
• A static variable is also known as a class variable.
• Demo: StaticVariableClass & StaticVariableClient
Java - Methods
• A Java method is a collection of statements that are grouped
together to perform an operation. When you call the
[Link]() method, for example, the system actually
executes several statements in order to display a message on the
console.
• Now you will learn how to create your own methods with or without
return values, invoke a method with or without parameters, and
apply method abstraction in the program design.
Creating Method
• Syntax
public static int methodName(int a, int b)
{
// body
}
Here,
• public static − modifier
• int − return type
• methodName − name of the method
• a, b − formal parameters
• int a, int b − list of parameters
Syntax Explanation
• The syntax shown above includes −
• modifier − It defines the access type of the method and it
is optional to use.
• return Type − Method may return a value.
• Name Of Method − This is the method name. The
method signature consists of the method name and the
parameter list.
• Parameter List − The list of parameters, it is the type,
order, and number of parameters of a method. These are
optional, method may contain zero parameters.
• method body − The method body defines what the
method does with the statements.
Program Structure
class XYZ{
static RETURN_TYPE fun_name([arg-list]){
// function - body
}
public static void main(String args[]){
// Statements
fun_name([arg-list]); // calling function
// Statements
}
}
Sample Program
class ABC{
static void fun1(){
[Link]("Called fun1() - No Arguments");
}
}
What are Pass-by-value and Pass-by-reference?
• Pass-by-value:
• A copy of the passed-in variable is copied into the argument of
the method. Any changes to the argument do not affect the
original one.
• Pass-by-reference:
• The argument is an alias of the passed-in variable. Any
changes to the argument will affect the original one.
The following example proves that Java
passes object references to methods by
value:
public class Swap {
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
[Link]("x(1) = " + x);
the above program prints
[Link]("y(1) = " + y);
the following output:
}
x(1) = 20
public static void main(String[] args) {
y(1) = 10
int x = 10;
x(2) = 10
int y = 20; y(2) = 20
swap(x, y);
[Link]("x(2) = " + x);
[Link]("y(2) = " + y);
}
}
• This result proves that the x and y are swapped to each other in the inside the swap() method,
however the passed-in variables x and y did not get changed.
Modifying Reference and Changing Reference
Examples
• Given the Dog class written as below:
class Dog {
protected String name;
Dog(String name) {
[Link] = name;
}
public void setName(String name) {
[Link] = name;
}
public String getName() {
return [Link];
}
Consider the following method that modifies
a Dog reference:
public void modifyReference(Dog dog) {
[Link]("Rex");
}
• some testing code:
Dog dog1 = new Dog("Pun");
[Link]("Before modify: " + [Link]());
modifyReference(dog1);
[Link]("After modify: " + [Link]());
• The method argument points to the same Dog object as the passed-
in reference variable,
The following output:
Before modify: Pun
After modify: Rex
Consider the following method that attempts to change
reference of the passed-in parameter:
public void changeReference(Dog dog) {
Dog newDog = new Dog("Poo");
dog = newDog;
}
• some testing code:
Dog dog2 = new Dog("Meek");
[Link]("Before change: " + [Link]());
[Link](dog2);
[Link]("After change: " + [Link]());
• Since it’s impossible to change reference of a passed-in variable within a method,
hence the following output:
Before change: Meek
After change: Meek