0% found this document useful (0 votes)
11 views216 pages

Java Data Structures & Algorithms Guide

The document provides a comprehensive overview of data structures and algorithms using Java, covering topics such as algorithms, asymptotic notations, and time and space complexity. It introduces Java programming concepts, including object-oriented programming, arrays, selection statements, iteration statements, and the structure of Java applications. Additionally, it discusses Java's features, data types, identifiers, and variable declarations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views216 pages

Java Data Structures & Algorithms Guide

The document provides a comprehensive overview of data structures and algorithms using Java, covering topics such as algorithms, asymptotic notations, and time and space complexity. It introduces Java programming concepts, including object-oriented programming, arrays, selection statements, iteration statements, and the structure of Java applications. Additionally, it discusses Java's features, data types, identifiers, and variable declarations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Data Structure and Algorithm Using Java

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 ?

An algorithm is any well


defined computational
procedure that takes some
value or set of values, as
input and produces some
value or set of values as
output.
We can also view an
algorithm as a tool for
solving a well specified
computational problem.
Selection Statements
Java supports two selection statements: if
and switch.

These statements allow you to control the


flow of your program’s execution based
upon conditions known only during run
time.
If Statement
Executes a block of statements only if a test is true

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

• A nested if is an if statement that is the target of


another if or else.

• When you nest ifs, the main thing to remember is


that an else statement always refers to the nearest
if statement that is within the same
Example
Chooses between outcomes using many tests
if (test) {
statement(s);
} else if (test) {
statement(s);
} else {
statement(s);
}

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

• If the condition is true, the statement is executed


• Then the condition is evaluated again, and if it is still true, the statement is executed again
• The statement is executed repeatedly until the condition becomes false
Logic of a while Loop
condition
evaluated

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

• The body of a do loop executes at least once


Comparing while and do
The while Loop The do Loop

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:

The initialization The statement is


is executed once executed until the
before the loop begins condition becomes false

for ( initialization ; condition ; increment )


statement;

The increment portion is executed at the


end of each iteration
Logic of a for loop
initialization

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

• The output of the above code will be :-


1
2
Asymptotic notation (Big Oh )
Asymptotic notation (Big Oh )
Asymptotic notation (Big Oh )
Example 1
Asymptotic notation (Big Oh )
Example 1

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

So, as per the definition of Big Oh

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

As per the definition of notation


Asymptotic notation (Theta)
Example 8
Asymptotic notation (Theta)
Example 8

As per the definition of notation

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

Apply L Hospital Rule


Comparisons of functions
Standard notations and common functions
Java language was developed by company Sun Microsystems
and creator is James Gosling
JAVA introduction:-

Author James Gosling


Access User Info
Vendor Sun Micro System
Project name Green Project
Type open source & free software
Initial
Administrator OAK language
Present Name Display java User Info
Retrieve
Extensions Account
User Profile
.java & .class & .jar
Initial version Info jdk 1.0 (java development kit)
Present version java 8
Operating System multi Operating System User Account Info
Implementation Lang c, cpp……
Symbol Validate coffee cup with saucer
SUN Update Stanford Universally Network
User Info
Slogan/Motto Enter/Update/
User Info
Delete
WORA (write once run
Update/Delete anywhere)
User Info
Features of Java Language

• 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:

• For most computer languages, the name of file that holds


the source code to a program is arbitrary. However this is
not the case with Java. The first thing you must learn
about Java is that the name you give to a source file
should match the name of the class holds the main()
method. So, in our case name of program is none other
than [Link].
First Java Application Program...

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...

• Here public is an access specifier that declares the main


method as unprotected and therefore making it
accessible to all other classes.

• Next appears the keyword static which declares this


method as one that belongs to the entire class and not a
part of any objects of the class. The main must always be
declared as static since the interpreter uses this method
before any objects are created. The type modifier void
states that main method does not return any value.
First Java Application Program...

• In main(), there is only one parameter String args[ ]


• declared a parameter named args, which is an array of
objects of the class String. Objects of type String store
character strings. args receives any command-line
arguments present when the program is executed. This
program does not make use of this information.
First Java Application Program...

• Fourth statement is

[Link](“This is First Application”);


• The println method is a member of the out object, which
is a static data member of System class. This line prints
the string to the screen. The method println always
appends a newline character to the end of the string. So
for the output to be printed on the same line use print in
place of println.
First Java Application Program...
• To compile the Java program, execute the compiler, javac,
specifying the name of the source file on command line:
• C:\> javac [Link]
• The javac compiler creates a file called [Link]
that contains the bytecode version of the program. The
bytecode is the intermediate representation of your
program that contains instructions the Java Interpreter
will execute. So, to run your program you use Java
interpreter java.
• C:\> java HelloWorld
First Java Application Program...
• When Java source code is compiled each individual class
is put its own output file named after the class and using
the .class extension. This is why it is important to give
source the same name as the class they contain, so when
you execute your program you are actually executing the
class by the interpreter. It will automatically search for a
file by that name that has the .class extension. If it finds
the file, it will execute the code contained in the specified
class.
Keywords in Java...

• There are 49 reserved keywords currently defined in the


Java language. These keywords, combined with the syntax
of the operators and separators, form the definition of the
Java language. These keywords cannot be used as names
for a variable, Class, or method.
Data Types in Java...

• In Java , there are really two different categories in


which data types have been divided :

• 1. Primitive Types

• 2. Reference Types
Data Types in Java...

[Link] Data Type Size


byte Byte length integer 1 byte
Short Short Integer 2 bytes
int Integer 4 bytes
long Long Integers 8 bytes
float Single precision number 4 bytes
double Double Precision number 8 bytes
char Character (16 bit Unicode) 2 bytes
boolean Has value true or false A Boolean Value
Range of Data Types…

Data Type Range


byte -128 to 127
short -32768 to 32767
int -2,147,483,648 to 2,147,483,647
long -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 3.4e-038 to 3.4e+038
double 1.7e-308 to 1.7 e+308
char 0 to 65535
Identifiers in Java...

• Identifiers are the names of variables , methods , classes ,


packages and interfaces. Identifiers must be composed of
letters , numbers , the underscore and the dollar sign.$.
• They cannot contain white spaces, Identifiers may only
begin with a letter, the underscore or a dollar sign. You
cannot begin a variable name with a number. All variable
are case sensitive for example
• MyVariable is not same as myVariable
Invalid Variable Names...

• My Variable // contains a space

• 9pins // Begins with a digit

• a+b // the plus sign is not an alphanumeric character


• testing 1-2-3
Integer Variables...

• The following lines show how to create variables of


integer types :

• long My_First_Byte = 10;

• int a=20;
Boolean Variables...

• A Boolean Variable is not a number. It can have one of two


values true or False. There are two ways to set its values .
• The first way to do this is explicitly.

• Ex :a) boolean firstboolean = false;

• b) boolean firstboolean = secondboolean;


Float & Double Variables...
• In Java, floating point numbers are represented by the
types float and double . Both of these follow a standard
floating point specification.
• float a = 35.6f; double x = 356556.25;
• float b = 35.7F; double y = 356556.25;
• a,b,x,y are variables.
• Note : 35.6f and 35.7F are single Precision Literals. As
Floating point numbers are treated as double precision
quantities. To force them to single precision we use f and
F.
Literals...

• Literals are pieces of Java source code that indicates


explicit values. Literals in Java refer to fixed values that
do not change during the execution of a program. Java
supports several types of constants.

A) Integer Constants
B) Real Constants
C) Single Character Constants
D) String Constants
String Literals...

• The String Literal is always enclosed in double quotes .


Java uses a String class to implement Strings whereas C
and C++ use an array of characters.

• For example :
• String poem = “Java supports Multithreading”;
Boolean Literals...

• Boolean Literal can have either of the values : true or


false.

• They do not correspond to the numeric value 1 and 0 as in


C and C++.
Operators in JAVA

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Operator
• An operator is a symbol that operates on one or more operands to produce

a result.

• Java provides a rich set of operators to manipulate operands.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Operands
• Operands are the values on which the operators act upon.

• An operand can be:

o A numeric variable - integer, floating point or character

o Any primitive type variable - numeric and boolean

o Reference variable to an object

o A literal - numeric value, boolean value, or string.

o An array element, "a[2]“

o char primitive, which in numeric operations is treated as an


unsigned two byte integer
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Types of Operators
1. Assignment Operators

2. Increment Decrement Operators

3. Arithmetic Operators

4. Bitwise Operators

5. Relational Operators

6. Logical Operators

7. Ternary Operators

8. Comma Operators

9. Instanceof Operators

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Assignment Operators
• The assignment statements has the following syntax:

<variable> = <expression>

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Assigning values Example

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Increment and Decrement
operators
++ and --
• The increment and decrement operators add an integer variable by

one.

• increment operator:

• two successive plus signs, ++

• decrement operator: --

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Increment and Decrement
operators
++ and --

Common Shorthand
a = a + 1; a++; or ++a;
a = a - 1; a--; or --a;

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


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

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.

• Their operands are of numeric type.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Arithmetic Operators
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Simple Arithmetic
public class Example {
public static void main(String[] args) {
int j, k, p, q, r, s, t;
j = 5;
k = 2;
p = j + k;
q = j - k;
r = j * k;
s = j / k;
t = j % k;
[Link]("p = " + p);
[Link]("q = " + q);
[Link]("r = " + r);
[Link]("s = " + s);
[Link]("t = " + t);
}
} > java Example
p = 7
q = 3
r = 10
s = 2
t = 1
>
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Bitwise Operators
• Java's bitwise operators operate on individual bits of integer (int and long)

values.

• If an operand is shorter than an int, it is promoted to int before doing the

operations.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Bitwise Operators
Operator Name Description

a&b and 1 if both bits are 1.

a|b or 1 if either bit is 1.

a^b xor 1 if both bits are different.

~a not Inverts the bits.

Shifts the bits of n left p positions. Zero bits are shifted


n << p left shift into the low-order positions.

Shifts the bits of n right p positions. If n is a 2's


complement signed number, the sign bit is shifted into
n >> p right shift the high-order positions.

Shifts the bits of n right p positions. Zeros are shifted


n >>> p right shift into the high-order positions.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Example
class Test {
of Bitwise Operators
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


[Link]("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */
[Link]("a | b = " + c );

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Example Cont.,
c = a ^ b; /* 49 = 0011 0001 */
[Link]("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */


[Link]("~a = " + c );

c = a << 2; /* 240 = 1111 0000 */


[Link]("a << 2 = " + c );
Output:
a & b = 12
c = a >> 2; /* 215 = 1111 */ a | b = 61
[Link]("a >> 2 = " + c ); a ^ b = 49
~a = -61
a << 2 = 240
c = a >>> 2; /* 215 = 0000 1111 */
a >> 15 a >>> 15
[Link]("a >>> 2 = " + c );
}}
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Relational Operators
• A relational operator compares two values and determines the relationship

between them.

• For example, != returns true if its two operands are unequal.

• Relational operators are used to test whether two values are equal,

whether one value is greater than another, and so forth.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Relational Operators
> < >= <= == !=

Primitives
• Greater Than >
• Less Than <
• Greater Than or Equal >=
• Less Than or Equal <=

Primitives or Object References


• Equal (Equivalent) ==
• Not Equal !=

The Result is Always true or false

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Relational Operators
Operator Description

== Checks if the value of two operands are equal or not, if yes


then condition becomes true.

!= Checks if the value of two operands are equal or not, if


values are not equal then condition becomes true.

> Checks if the value of left operand is greater than the value
of right operand, if yes then condition becomes true.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Relational Operators
Operator Description
< Checks if the value of left operand is less than the value
of right operand, if yes then condition becomes true.

>= Checks if the value of left operand is greater than or


equal to the value of right operand, if yes then condition
becomes true.

<= Checks if the value of left operand is less than or equal to


the value of right operand, if yes then condition becomes
true.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Relational Operator Examples
public class Example {
public static void main(String[] args) {
int p =2; int q = 2; int r = 3;
Integer i = new Integer(10);
Integer j = new Integer(10);

[Link]("p < r " + (p < r));


[Link]("p > r " + (p > r));
[Link]("p == q " + (p == q));
[Link]("p != q " + (p != q));

[Link]("i == j " + (i == j));


[Link]("i != j " + (i != j));
}
> java Example
} p < r true
p > r false
p == q true
p != q false
i == j false
i != j true
>

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Example of Relational
Operators
public LessThanExample
{
public static void main(String args[])
{
int a = 5; int b = 10;
if(a < b)
{
[Link]("a is less than b");
}
}
}

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Logical Operators
• These logical operators work only on boolean operands. Their return

values are always boolean.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Logical Operators
Operator Description

&& Called Logical AND operator. If both the operands are non
zero then then condition becomes true.

|| Called Logical OR Operator. If any of the two operands


are non zero then then condition becomes true.

! Called Logical NOT Operator. Use to reverses the logical


state of its operand. If a condition is true then Logical
NOT operator will make false.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Logical (&&) Operator Examples

public class Example {


public static void main(String[] args) {
boolean t = true;
boolean f = false;

[Link]("f && f " + (f && f));


[Link]("f && t " + (f && t));
[Link]("t && f " + (t && f));
[Link]("t && t " + (t && t));

}
}
> java Example
f && f false
f && t false
t && f false
t && t true
>

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Logical (||) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;

[Link]("f || f " + (f || f));


[Link]("f || t " + (f || t));
[Link]("t || f " + (t || f));
[Link]("t || t " + (t || t));

}
}
> java Example
f || f false
f || t true
t || f true
t || t true
>

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Logical (!) Operator Examples

public class Example {


public static void main(String[] args) {
boolean t = true;
boolean f = false;

[Link]("!f " + !f);


[Link]("!t " + !t);

}
}
> java Example
!f true
!t false
>

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Example of Logical
public class ANDOperatorExample{
Operators
public static void main(String[] args){
char ans = 'y';
int count = 1;
if(ans == 'y' & count == 0){
[Link]("Count is Zero.");}
if(ans == 'y' & count == 1) {
[Link]("Count is One."); }
if(ans == 'y' & count == 2) {
[Link]("Count is Two.");
}}}

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Ternary Operators
• Java has a short hand way by using ?: the ternary aka conditional operator

for doing ifs that compute a value.

• Unlike the if statement, the conditional operator is an expression which

can be used for

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Ternary Operator
? :
Any expression that evaluates
to a boolean value.

boolean_expression ? expression_1 : expression_2

If true this expression is If false this expression is


evaluated and becomes the evaluated and becomes the
value entire expression. value entire expression.

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Ternary ( ? : ) Operator Examples

public class Example {


public static void main(String[] args) {
boolean t = true;
boolean f = false;

[Link]("t?true:false "+(t ? true : false ));


[Link]("t?1:2 "+(t ? 1 : 2 ));
[Link]("f?true:false "+(f ? true : false ));
[Link]("f?1:2 "+(f ? 1 : 2 ));
}
} > java Example
t?true:false true
t?1:2 1
f?true:false false
f?1:2 2
>

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Example of Ternary Operator
// longhand with if:
int answer;
if ( a > b )
{
answer = 1;
}
else
{
answer = -1;
}
// can be written more tersely with the ternary operator as: int
answer = a > b ? 1 : -1;
PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR
Comma Operators
• Java has an often look past feature within it’s for loop and this is the

comma operator.

• Usually when people think about commas in the java language they think

of a way to split up arguments within a functions parameters

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Example of Comma Operator
//: c03:[Link]

// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002

// [Link]. See copyright notice in [Link].

public class CommaOperator {

public static void main(String[] args) {

for(int i = 1, j = i + 10; i < 5;

i++, j = i * 2) {

[Link]("i= " + i + " j= " + j);

} ///:~

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR


Static Members in java

• The class level members which have static keyword in their


definition are called static members.
Types of Static Members: Java supports four types of static members
• Static Variables
• Static Blocks
• Static Methods
• All static members are identified and get memory location at the time of
class loading by default by JVM in Method area.

• 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:-

 If any variable we declared as static is known as static variable.


 Static variable is used for fulfil the common requirement.
Access User Info

 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

User Account Info

Validate
Update
User Info
Enter/Update/ Delete
Update/Delete User Info
User Info
Example of static variable.

In the below example College_Name is always same, and it is declared as static.


Access User Info

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

The body of a static method can instantiate


Display objects. Retrieve User Info
Account
User Profile
Example (the [Link] file) Info

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?

• Static blocks will be executed at the time of class


loading by the JVM by creating separate stack frames in
java stacks area.
• Static blocks will be executed in the order they defined
from top to bottom.
Example For Order of execution of static block
and main method:
class StaticBlockDemo
{
public static void main (String[] args) throws [Link]
{
[Link]("Main method executed");
}
static{
[Link]("First static block executed");
}
Output:
static{
First static block execu
[Link]("Second static block executed"); Second static block exe
} Third static block execu
static{ Main method executed
[Link]("Third static block executed");
Method Overloading
• Overloading is also a feature of OOP languages like Java
that is related to compile time (or static) polymorphism.
• If a class have multiple methods by same name but
different parameters, it is known as Method Overloading.
• If we have to perform only one operation, having same
name of the methods increases the readability of the
program.
Example
class Calculation{
void sum(int a,int b)
{
[Link](a+b);
}
void sum(int a,int b,int c){
[Link](a+b+c);
}
public static void main(String args[]){
Calculation obj=new Calculation();
[Link](10,10,10);
[Link](20,20);
}
}
Can we overload static
methods?
• The answer is ‘Yes’. We can have two ore more static
methods with same name, but differences in input
parameters.
• For example, consider the following Java program.
// filename [Link]
public class Test {
public static void foo() {
[Link]("[Link]() called ");
}
public static void foo(int a) {
[Link]("[Link](int) called ");
Output:
} [Link]() called [Link](int)
public static void main(String args[]) called
{
[Link]();
[Link](10);
Arrays
Arrays
• An array is an ordered list of Each
The entire array
values
value has a numeric index
has a single name

0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1

This array holds 10 values that are indexed from 0 to 9


Arrays
• A particular value in an array is referenced using the array
name followed by the index in brackets
• For example, the expression
scores[2]
refers to the value 94 (the 3rd value in the array)
• That expression represents a place to store a single integer
and can be used wherever an integer variable can be used
Arrays
• For example, an array element can be assigned a value,
printed, or used in a calculation:
scores[2] = 89;
scores[first] = scores[first] + 2;
mean = (scores[0] + scores[1])/2;
[Link] ("Top = " + scores[5]);
Arrays
• The values held in an array are called array elements
• An array stores multiple values of the same type – the
element type
• The element type can be a primitive type or an object
reference
• Therefore, we can create an array of integers, an array
of characters, an array of String objects, an array of
Coin objects, etc.
• In Java, the array itself is an object that must be
instantiated
Arrays
• Another way to depict the scores array:

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:

float[] prices = new float[500];


boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
Using Arrays
• The iterator version of the for loop can be used when
processing array elements
for (int score : scores)
[Link] (score);

• This is only appropriate when processing all array elements from


top (lowest index) to bottom (highest index)
final int LIMIT = 15, MULTIPLE = 10;

int[] list = new int[LIMIT];

// Initialize the array values


for (int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;

list[5] = 999; // change one array value

// Print the array values


for (int value : list)
[Link] (value + " ");
Bounds Checking
• Once an array is created, it has a fixed size
• An index used in an array reference must specify a valid
element
• That is, the index value must be in range 0 to N-1
• The Java interpreter throws an
ArrayIndexOutOfBoundsException if an array index is
out of bounds
• This is called automatic bounds checking
Bounds Checking
• For example, if the array codes can hold 100 values, it
can be indexed using only the numbers 0 to 99
• If the value of count is 100, then the following reference
will cause an exception to be thrown:
[Link] (codes[count]);
• It’s common to introduce off-by-oneproblem
errors when using
arrays
for (int index=0; index <= 100; index++)
codes[index] = index*50 + epsilon;
Bounds Checking
• Each array object has a public constant called length
that stores the size of the array
• It is referenced using the array name:
[Link]
• Note that length holds the number of elements, not the
largest index
ReverseOrder
Scanner scan = new Scanner ([Link]);

double[] numbers = new double[10];

[Link] ("The size of the array: " + [Link]);

for (int index = 0; index < [Link]; index++) {


[Link] ("Enter number " + (index+1) + ": ");
numbers[index] = [Link]();
}

[Link] ("The numbers in reverse order:");

for (int index = [Link]-1; index >= 0; index--)


[Link] (numbers[index] + " ");
Alternate Array Syntax
• The brackets of the array type can be associated with
the element type or with the name of the array
• Therefore the following two declarations are equivalent:
float[] prices;
float prices[];

• The first format generally is more readable and should


be used
Multidimensional Arrays

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...

There are a couple of subtle differences. To declare a


multidimensional array variable, specify each additional index
using another set of square brackets. For example, the following
declares a two-dimensional array variable called twoD.

int twoD[ ][ ] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this


matrix is implemented as an array of arrays of int.
Multidimensional Arrays...
class TwoDArray {
public static void main(String args[]) {
int twoD[ ][ ]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++; }
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link](); } }}

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...

When you allocate memory for a multidimensional array, you need


only specify the memory for the first (leftmost) dimension. You can
allocate the remaining dimensions separately. For example, this
following code allocates memory for the first dimension of twoD
when it is declared. It allocates the second dimension manually.

int twoD[ ][ ] = new int[4][ ];


twoD[0] = new int[2];
twoD[1] = new int[4];
twoD[2] = new int[1];
twoD[3] = new int[3];
Multidimensional Arrays...
class TwoDAgain {
public static void main(String args[]) {
int twoD[ ][ ] = new int[4][ ];
twoD[0] = new int[1]; twoD[1] = new int[2];
twoD[2] = new int[3]; twoD[3] = new int[4];

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 use of uneven multidimensional arrays is not recommended


for most applications, because it runs contrary to what people
expect to find when
a multidimensional array is encountered. However, it can be used
effectively in some situations.
Strings...

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( ).

For example, consider the following fragment:

String str = "this is a test";


[Link](str);
Strings...

Here, str is an object of type String. It is assigned the string “this


is a test”. This string is displayed by the println( ) statement.

Alternative Way

String stringname = new String(“string”);

The string class defines a number of methods that allow us


accomplish a variety of string manipulation tasks.
Strings...

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:

boolean equals(String object)


int length( )
char charAt(int index)
Strings...
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String"; String strOb3 = strOb1;
[Link]("Length of strOb1: " + [Link]());
[Link]("Char at index 3 in strOb1: " + [Link](3));
if([Link](strOb2))
[Link]("strOb1 == strOb2");
else
[Link]("strOb1 != strOb2");
if([Link](strOb3))
[Link]("strOb1 == strOb3");
else
[Link]("strOb1 != strOb3");}}

O/P: len=12, char is s(4th char) etc.


Wrapper Class
• Wrapper classes are classes that allow primitive types to be accessed as objects.

• 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.

• Wrapper classes make the primitive type data to act as objects.


Primitive Data Types and Wrapper Classes
Data Type Wrapper Class

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;

Integer y = new Integer(33);


The first statement declares an int variable named x and initializes it
with the value 25.
• The second statement instantiates an Integer object. The object is initialized with the
value 33 and a reference to the object is assigned to the object variable y.
• Clearly x and y differ by more than their values:
x is a variable that holds a value;
y is an object variable that holds a reference to an object.
What is the need of Wrapper Classes?
• Wrapper classes are used to be able to use the primitive data-types as objects.

• Many utility methods are provided by wrapper classes.

To get these advantages we need to use wrapper classes.


Boxing and Unboxing
• The wrapping is done by the compiler.

• 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.

Example of boxing and unboxing:

• Integer x, y; x = 12; y = 15; [Link](x+y);

• 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 .

• Short, Integer, Double and Long implement Comparable interface.


Features of Numeric Wrapper Classes
• All the numeric wrapper classes provide a method to convert a numeric string into a
primitive value.

public static type parseType (String 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.

public static String toString (type value)

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)

• Determines whether this number object is equal to the argument.

• 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.

• The constructor for Character is :


Character(char ch)

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

• It returns the encapsulated character.


Boolean Class
• Boolean is a wrapper around boolean values.

• It defines these constructors:


Boolean(boolean boolValue)
Boolean(String boolString)

• In the first version, boolValue must be either true or false.

• 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");
}

public static void main(String arg[]){


fun1();
}
}
Passing Arguments
class ABC{
static void fun2(int i){
[Link]("Called fun2() - Single Argument Recieved :" + i);
}

public static void main(String arg[]){


fun2(8);
}
}
Returning Value
class ABC{
static int fun3(int i){
[Link]("Called fun3() - Single Argument Recieved :" + i);
[Link]("This function returns double of recieved argument");
return i*2;
}

public static void main(String arg[]){


int k = fun3(16);
[Link](k);
[Link](fun3(20));
}
}
Calling a Method
• For using a method, it should be called. There are two ways in
which a method is called i.e., method returns a value or returning
nothing (no return value).
• The process of method calling is simple. When a program invokes
a method, the program control gets transferred to the called
method. This called method then returns control to the caller in
two conditions, when −
• the return statement is executed.
• it reaches the method ending closing brace.
METHOD
public class StudentTest {
public static void main ( String[] args ) {
Student s1 = new Student () ;
Student s2 = new Student ( "Sai", 3 );
Student s3 = new Student ( "Gautham" , 4 , 98 , 100, 96);
[Link]("Student s1: ");
[Link]();  Object s1 calling method printDetails()
[Link]("\nStudent s2: ");
[Link]();  Object s2 calling method printDetails()
[Link]("\nStudent s3: ");
[Link]();  Object s3 calling method printDetails()
}

}
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

Java always passes object references to method by value. That means


passing the memory address of the object that the variable points to, not
passing the variable itself, not the object itself. So we cannot change
reference of a passed-in variable in a method.
Recursion in Java
• Recursion in java is a process in which a method calls itself
continuously. A method in java that calls itself is called recursive
method.
• It makes the code compact but complex to understand.
• Syntax:
returntype methodname()
{
//code to be executed
methodname();
//calling same method
}
Working of Recursion
Java Recursion Example 1 : Finite times
public class RecursionExample2 {
static int count=0;
static void p(){ Output:
count++; hello 1
if(count<=5){ hello 2
hello 3
[Link]("hello "+count); hello 4
p(); hello 5
}
}
public static void main(String[] args) {
p();
}
Java Recursion Example 2: Factorial Number
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


[Link]("Factorial of 5 is: "+factorial(5));
}
}
Working Of the Example
• Working of above program:
factorial(5)
factorial(4)
factorial(3)
Output:
factorial(2) Factorial of 5 is: 120
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120  Final Output
Java Recursion Example 3: Fibonacci Series
public class RecursionExample4 {
static int n1=0,n2=1,n3=0;
static void printFibo(int count){
if(count>0){
n3 = n1 + n2; Output:
n1 = n2;
0 1 1 2 3 5 8 13 21 34
n2 = n3;
[Link](" "+n3);
55 89 144 233 377
printFibo(count-1);
}
}
public static void main(String[] args) {
int count=15;
[Link](n1+" "+n2); //printing 0 and 1
printFibo(count-2);
//n2 because 2 numbers are already printed
}
Sets and Maps
• Sets
• Maps
• The Comparator Interface
• Sets and Maps in Java Collections API
• TreeSet
• TreeMap
• Review for Exam
• Reading: 13.1-13.6
Sets
• A set is a collection of elements with no duplicates
• The Set follows the unordered way and it found
in [Link] package. Duplicate item will be ignored in Set
and it will not print in the final output.
public class SetExample {

public static void main(String[] args)


{
Set<String> Set = new
HashSet<String>();
[Link]("one");
[Link]("two");
[Link]("three");
[Link]("four");
[Link]("five");
[Link](Set);
}
}
Maps
• A map is a collection that establishes a relationship between
keys and values
• The implementation should provide an efficient way to
retrieve a value given its key
• There must be a one-to-one mapping from a key to a value –
each key must have only one value, but multiple keys can
have the same value
• Therefore, there isn’t necessarily a one-to-one mapping from
a value to a key
• found in [Link] package
{ Map<Integer, String> map
= new HashMap<Integer,
String>();
// Adding Elements using Map.
[Link](100, "Amit");
[Link](101, "Vijay");
[Link](102, "Rahul");
for ([Link] m : [Link]()) {
[Link]([Link]() +
""
+ [Link]());
}
}
}
Thank
you

You might also like