OOP2024 JavaSlides W1 JavaBasics-StructuredProgramming
OOP2024 JavaSlides W1 JavaBasics-StructuredProgramming
Using Java
Structured Programming
Quan Thai Ha
HUS
February 20, 2024
Presentation Outline
4 Memory Model
6 References
1 162
Computer System
The computer system consist of both software and hardware components. The operating
system is a system software that manages all the crucial functions of the computer system.
A computer system is a digital electronic device that needs to be programmed to perform
any meaningful task. The computer program directs the computer microprocessor (CPU)
to perform the desired operations as per the program instructions.
2 162
Computer Program
Computer Program
The computer program consist of set of program instructions and each of these instruction
performs a specific task. The computer program can be written using any high level
programming language.
Some of the most popular and commonly used programming languages include C language,
C++, Java, Python, JavaScript, C# (C Sharp), and many other high level languages.
3 162
Program Compilation
When the user initiates the
program execution, the
operating system allocates the
necessary resources in terms of
processor time and the main
memory (RAM). The CPU is
the brain of the computer
system. The CPU reads these
instructions from the memory
and executes the program
instructions one by one.
The computer system can understand and execute only machine code instructions in
binary. The binary code consist of only two numbers that is 0 (zero) and 1 (one).
And therefore, all the programs written in any programming language must be first
converted to machine code instructions in binary which computer CPU can interpret and
execute. This conversion process is known as program compilation.
4 162
Programming Paradigms
5 162
Programming Paradigms
The programming paradigms are simply different approaches to organize and structure the
program code. Alternately paradigms can also be referred as methodology, approach or a
particular style to write and organize the program code.
The computer science has evolved both in the hardware and software domain. Similarly,
the computer programming approaches and problem solving techniques has also evolved
over the period of last few decades.
There are a number of alternative approaches to program methodology and the manner in
which the program is written and organized while building a software. Each of these
programming style offers different advantages and limitations.
These different programming styles are referred to as programming paradigms. Each of
these paradigm represent fundamentally different approaches to building solutions to
specific types of problems using programming.
Different programming languages came in to existence which allow the programmers to
write the code as per one paradigm. Most programming languages fall under one
paradigm, but some languages have elements of multiple paradigms.
6 162
Non-Structured Programming
The non-structured programming paradigm was used in the first generation of
programming languages. Basic, COBOL and Assembly language are examples of
non-structured programming.
As per non-structured programming style of programming, the code is organized as
collection of program statement which gets sequentially executed from first statement till
the last statement.
In non-structured programming paradigm the code is written in a single continuous file.
Each program statement has a statement number or label.
One of the major limitation of non-structured approach was the difficulties due to
spaghetti code which makes the program code difficult to debug.
The spaghetti code is a badly entangled code due to liberal use of GOTO statement. In
large and complex code it is difficult to track the flow of control due multiple use of GOTO
statements.
The non–structured programming also had major limitation in terms of difficulty to reuse
the program code. Further, it was not possible to secure the data from unintended changes
in this approach.
7 162
Structured Programming
The next generation of programming
languages like C language and Pascal were
based on the concept of structured
programming.
In structured programming, the program
code is modularized in the form of functions.
The function once defined can be called
number of times. A large chunk of code can
be replaced by a single function.
The structured programming approach also made it easy to debug the program code. For
example the logical errors in the program code can be easily fixed by making the necessary
corrections in the function code.
A structured language has constructs like IF-THEN-ELSE condition statement,
WHILE-NEXT conditional loop, SWITCH-CASE statements, DO-WHILE loop, and
FOR-NEXT loop. These statements helps to simplify the program algorithm.
8 162
Limitations Of Structured Programming
In structured programming approach, it was difficult to secure the data and it was difficult
to protect the data was unwarranted operations. In large and complex code, it is difficult to
track the operations of various functions operating on the same data which can lead to
spaghetti code.
9 162
Object-Oriented Programming Introduction
In structured programming, first it was difficult to secure the data and second, it was also
difficult to model the real world entities.
The OOP methodology does not provide direct access to the program data. The OOP
allows the data to be treated as private and the programmer can restrict the data access.
Further, with object-oriented approach, allows the programmers to easily and realistically
model the real world entities.
10 162
What Is Object-Oriented Programming?
The objects are the basic units of OOP. In OOP methodology, the program code is
organized in the form of set of classes. The class defines the object in the program code.
Each and every class represents a real world entity. In other words, the entities are
objects that need to be represented in the program code.
11 162
Presentation Outline
4 Memory Model
6 References
12 162
History of Java
13 162
History of Java
Java was developed by James Gosling and his colleagues while working on a project at Sun
Microsystems in year 1991. The Java language was initially developed for developing
embedded software for electronic gadgets.
The Java language development project started as a project called "Oak" by James Gosling.
However, due to some legal issues this language was later on renamed as Java. Java was
officially released in year 1995.
The Java language syntax is quite similar to the syntax of C language and C++. However,
some crucial features of these languages were excluded in Java syntax in order to make the
Java more secure language.
The primary motive of the development of Java was to create language that is platform
independent. This means Java program should have the capability of "Write Once, Run
Anywhere".
The Java’s birth also coincided with the advent of smart mobile handsets. The Java’s
capabilities were tailor made for mobile and touch screen devices. Java soon became one of
the most popular, versatile and widely used language which now powers over 3 billion
devices.
14 162
What Is Java?
15 162
Java Environment
The Java developers would typically need all the three components required for the
development and also for testing (JDK = JRE + Tools) the Java applications.
Whereas the end user (client) machine would need only components (JRE = JVM + Class
Libraries) necessary for execution of Java program.
16 162
Java Environment
The Java Development Kit (JDK) as the name suggest is primarily required for development
of Java applications. The JDK consist of two components. These two components are Java
Runtime Environment and some other application development tools.
The JDK is intended for java developers. The JDK includes all the three components
required for the development and also for testing the Java applications (JDK = JRE + Tools).
The Java Runtime Environment (JRE) as the name suggest is primarily required for
providing runtime environment to the Java applications. The JRE consist of two
components. These two components are Java Virtual Machine and some class libraries.
The JRE is installed on the end user machines for providing runtime environment to the
Java software application needed for software deployment (JRE = JVM + Class Libraries).
The Java Virtual Machine (JVM) is a vital component of the JRE which provides runtime
environment to the Java application.
The JVM accepts the platform independent Bytecode (dot class file) generated by the Java
compiler (javac) as input. The JVM converts the Bytecode into platform specific native
machine code and executes this code line by line.
17 162
Java Environment
18 162
How Java Program Works?
Instead, the Java program first gets compiled into a platform independent Bytecode. In the
first stage we use the Java compiler (javac) which compiles the high level Java program
code into intermediate Bytecode (dot class file).
This Bytecode is a platform independent code that gets further compiled to native machine
code. The JVM then executes this platform specific native machine code line by line.
19 162
Java Program Compilation
20 162
C++ vs. Java Compilation
21 162
Program Development Process
22 162
Run Cycle for C Programs
Writing/Editing Program
▶ Use an editor, e.g. vim
▶ Source code must have a .c extension
Compiling Program
▶ Use a C compiler, e.g. gcc
▶ Default executable file [Link]
Executing binary
▶ Type name of executable file
23 162
Run Cycle for Java Programs
Writing/Editing Program
▶ Use an text editor, e.g. vim
▶ Compiled binary has .class extension
Compiling Program
▶ Use a Java compiler, e.g. javac
▶ Compiled binary has .class extension
▶ The binary is also known as Java executable
Bytecode
Executing binary
▶ Run on a Java Virtual Machine (JVM)
e.g. java HelloWorld
24 162
Java Compile Once, Run Anywhere
25 162
How To Write Java Program?
26 162
Java Program Structure
27 162
Java Program Structure
28 162
Java Documentation Section
The documentation section is optional and contains the comments in the java program
code. The comments are part of the program that are ignored and not compiled by the
compiler.
The main purpose of the comments in the documentation section is to improve the
readability and the maintainability of the java program code.
The comments are added to the program code especially in the large and complex project
where number of programmers are writing the program code. The comments inserted in
the program code makes it easier to understand the program code.
Example:
▶ Single Line Comment: // Example Comment Text
▶ Multiple Line Comment:
/* Example Multi-line Comment Line 1
This Is comment Line 2 */
▶ Documentation Comment:
/** Example Documentation Comment
Generated Automatically */
29 162
Java Package Statement
The Java package allows the programmer to create a group of similar types of classes,
interfaces and sub-packages. These packages once created can be easily imported into the
program code.
The Java packages allows the code re-usability and the programmer can simply add the
required classes by importing the package that contains these classes. The Java packages
can be either built-in packages or user-defined package.
The package statement in Java program is optional and identifies the package that a Java
program is a part of that package. The program belongs to the default package if the Java
program does not include a package statement.
If program does not include the package statement then the program belongs to the
default package, which is simply a package without any name.
Example:
package [Link];
30 162
Java Import Section
The Java programmer can use the classes defined in other packages by directly importing
the packages into the program code using import statement. The programmer can either
import some classes or all the classes present in the package.
Java import statement is optional. The Java programming language provide number of
built-in packages which programmer can use to add additional functionality to the
program.
Once the required package is imported, the classes in the package become available in the
program code and can be referred to directly by using only its name. The import statement
is very useful and frequently used in the Java program.
Example:
import [Link].* ;
31 162
Java Class Definitions
In Java program, all the entities that need to be represented in the program in the form of
objects are included as class. And therefore, a Java program may contain several classes
defined in the program.
The class declarations are an important element of the Java program code and the Java
program contains number of classes .
The Java program can contain number of classes. However, the Java program file which will
be compiled to generate the Bytecode must have one public class that contains the main
method.
The Java program file must be saved with the same class name that contains the main
method. This main method is the starting point of the program execution.
32 162
Java Program Structure Example
33 162
Java Program: HelloWorld
Let us now create and understand our first Java program HelloWorld. You can write this
program using any text editor (such as Notepad) and then compile this program on the
command prompt.
In order to write and successfully execute the Java program HelloWorld, you need to follow
the following steps.
▶ Install the JDK on your computer.
▶ Set the JDK path with Environment Variable.
▶ Write the program in text editor.
▶ Save the program file with class name ([Link]).
▶ Compile the program: javac [Link]
▶ This will create Java Bytecode ([Link])
▶ Execute the program: java HelloWorld
▶ This will print: Hello World.
34 162
Presentation Outline
4 Memory Model
35 162
Java Program
The Java program is essentially a collection of objects which are represented in the
program code in the form of a classes. These objects communicate with each other to
perform the various tasks as per the program instructions.
Like any other programming language, the Java program code must be written as per the
set of rules and principles that govern the structure of the Java program code and the
statements.
Java is a class based language. And therefore, all the program code is enclosed in a class
except the package import statements, documentation statements and package
declaration.
The Java program code can be organized in various packages. The package is a collection of
related classes. These pages can be imported into Java program code using import keyword.
Java Is Strongly Types Language.
▶ Java is said to be a strongly typed language because as the Java syntax rules all the variables
used in the program code must be declared and the datatype should be specified.
36 162
Java Class Declaration
Java program can have any number of classes. These classes are organized in packages to
improve the readability of the program code.
The class should be declared as per Java syntax rules. The class is declared using the Java
keyword class followed by the class name. The initial letter of the class name is capitalized
by convention.
The Java source code file with .java extension can contain only one public class. The Java
main method should be declared in this public class which is starting point of program
execution. The Java source code file should be saved with the same name as Java public
class name.
37 162
Presentation Outline
4 Memory Model
38 162
Variables in Java
The data is an important element of the Java program. During the program execution, the
data needs to be stored into the memory (RAM) so that the CPU can operate on the data
as per the program instructions.
The variables are named memory locations with specific data type assigned to it
which acts as a container for temporarily storing the values in the memory during
the program execution.
The variable is temporary memory space created during the program execution that can
store some value as per the data type defined in a program instruction. This memory space
can be accessed using a variable name as specified in the program code.
A variable can be declared with only one data type. Once the variable is declared of a
specific data type then during the program execution different values of same data type
can be stored into the variable.
Each data type has specific range of the minimum and maximum value that can be stored
into the variable. Depending upon the variable data type the required bytes of memory is
allocated by the operating system.
39 162
Variables in Java
40 162
Java Variable Declaration
The variables are used to store the data during the program execution. The variables are
referred in the program code by user specified variable names.
And therefore, the program defines the names to these memory locations and the specific
data type is also assigned to these named memory locations. The program data is stored
into these named memory locations depending upon the data type.
The Java program variables must be declared in the program code along with its name and
data type. The suitable name is given to the variable as per the variable naming
convention (CamelCase).
The variables are created during the program execution and the operating system allocates
the required memory as per the data type of the variable.
The scope and the visibility of the variable depends upon the type of the variable (local,
instance or static variable). The type of the variable depends upon where it is declared
within a class and the type of the value assigned to the variable.
41 162
Java Variable Declaration
42 162
Java Variable Scope
The Java variable is said to be in scope if the variable value can be accessed and operated
upon within the segment of the program code.
The Java variable scope depends upon the location where the variable is declared and the
access modifier that precedes the variable name in the variable declaration statement.
The Java programmer can control the scope (visibility) of the program variables by using
the access modifiers (public, private, protected and default) and the location where the
variable is declared.
43 162
Java Variable Types
The Java programming language makes use of different types of variables. The Java
variable types can be broadly grouped into two categories based on the type of the value
stored into the variable and the scope of the variable.
The first category of the Java variable type is based on the type of the data stored in a
variable. As per this criterion, the Java variable can either be of reference type or it can be
of non-reference (primitive) type.
▶ Primitive variable
▶ Reference variable
The second category of variable type is based on the scope and the life span of the variable.
As per this criterion, the Java variables can be categorized into three types which includes
local variable, instance variable and static variable.
▶ Local variable
▶ Instance variable
▶ Static variable
44 162
Java Variable Types
Primitive variable
▶ The Java despite being an object-oriented language, the Java supports primitive data type and
the programmer is allowed to use the primitive data types in the Java program code.
Reference variable
▶ The Java programming language is said to be extensible because you can create a class and
declare a variable of that class type. Then we can use the Java new keyword and invoke the
constructor to create an object.
▶ Once the class is declared, we can create a variable of that class type and such variables are
called reference variable. The reference variable can be assigned the address of an object. And
therefore, when a reference variable contains the memory location of an object, we say that it
refers (points) to an object.
▶ In Java, an object variable (that is, a variable whose type is a class) does not actually hold an
object. It merely holds the memory location of an object. The object itself is stored elsewhere
(Heap).
▶ There is a reason for this behavior. Objects can be very large. It is more efficient to store only
the memory location instead of the entire object.
45 162
Java Reference Variable Example
Let us consider one example of a Student class. We can create class Student using Java
keyword class. After creating the Student class, now we can create a reference variable
Student class (s1) which holds the address of an object and this reference variable (s1)
points to the actual object.
46 162
Local Variable
A local variable is said to be a block level variable. The local variables are declared and
created within a block. A block is a group of Java statements enclosed within a curly braces.
For example variable declaration inside a methods, constructor and blocks.
A local variable in Java is a variable that is declared within the body of a method or within
a instance block or in a constructor body. The local variable once declared can exist only
within the method or constructor body or inside a instance block.
The local variables are not initialized and are not given the initial default values. These
variables are created only during the method execution or when the constructor is invoked.
1 p u b l i c i n t c r e a t e L o c a l V a r i a b l e ( i n t argument ) {
int localVariable ;
3 l o c a l V a r i a b l e = argument ;
return localVariable ;
5 }
47 162
Local Variable Declaration And Initialization
The local variables are not given the initial default values and therefore local variables
must be first initialized and assigned a value before it is used in any program statement.
The memory (Stack) is allocated to the local variable when a method is invoked (called)
since the local variables are declared inside the method body. The memory to the local
variable is taken away and the local variables come to an end when the method execution
is over.
The local variables cannot use any of the access modifiers as they exist only inside the
method body. But the local variable can be declared as final using non-access modifier.
The scope of the local variables is only within a method body and the local variables
cannot be accessed and used outside the method, constructor or block body.
1 p u b l i c i n t c r e a t e L o c a l V a r i a b l e ( i n t argument ) {
int localVariable = 1;
3 }
48 162
Instance Variable
The instance variables are variables that are declared inside a class but outside the body of
a method, constructor or a block without using static keyword. The instance variables
belongs to the an object.
The instance variables are said to be an object level variable. The instance variables belongs
to an instance (object) of a class. Each object will have its own copy of the instance variable.
The instance variables are created when the object is created and destroyed when object is
destroyed. The object is created when a class is instantiated by using a Java new keyword
and by invoking the constructor. This is then assigned to a reference variable of that class
type.
The instance variable initialization is not compulsory. However, if the instance variable is
not initialized then its default value is zero (0). The instance variables can be accessed by
creating an object and by using the dot operator with reference to an object created.
The instance variables for an object defines the state of an object and stores values
pertaining to the state of an object. The instance variables can be declared using any one
of the four access modifiers (public, private, protected and default).
49 162
Instance Variable Example
21 / / Create o b j e c t
B i c y l e b i c y c l e = new B i c y l e ( 9 , 1 0 , 1 ) ;
50 162
Static Variable
The static keyword is a non-access modifier in Java that can be used while declaring a
method or a variable. The Java keyword static indicates that the method or variable
belongs to the class and can be accessed without creating an object of the class.
The static variables are variables that are declared inside the class but outside the body of a
method, constructor or a block using the Java static keyword.
The static variables are said to be a class variable. The static variables belongs to a class
and all the objects share a common copy of the static variable regardless of the number of
objects.
The static variables are created when the JVM loads the Java program dot class (Bytecode)
file into the memory for the execution. The static variables are destroyed when the
Bytecode execution is over.
The memory allocation to the static variables happens only once when class is loaded into
the memory. It is the JVM which loads the class (Bytecode) into the memory.
The static variables belong to the class and can be accessed anywhere within the class. And
therefore, the static variable cannot be declared inside a method in Java.
51 162
Static Variable Example
4 / / Three i n s t a n c e v a r i a b l e s
p r i v a t e i n t cadence ;
6 p r i v a t e i n t gear ;
p r i v a t e i n t speed ;
8
public Bicycle ( i n t startCadence , i n t startSpeed , i n t startGear ) {
10 gear = startGear ;
cadence = startCadence ;
12 speed = s t a r t S p e e d ;
}
14
p u b l i c v o i d s e t C a d e n c e ( i n t newValue ) {
16 c a d e n c e = newValue ;
}
18
...
20 }
22 / / Create o b j e c t
B i c y l e b i c y c l e = new B i c y l e ( 9 , 1 0 , 1 ) ;
52 162
Presentation Outline
4 Memory Model
53 162
Data Types In Java
The variables are created and declared in the Java program to temporarily store the values
during the program execution. The programmer also needs to specify the data type of
variables in the variable declaration statements.
Based on the data type of a variable, the operating system allocates the required memory.
The data type of the variable decides what kind of values that can be stored into this
named memory location.
For example, the integer type variables can store integer values (such as 4, 7, 23, 1004), float
type variables can store floating point type values (such as 3.14, 245.009, 0.7). The string
type variables can store String type values (such as "Color", "Red"). The class type reference
variables can store object references.
The data types in Java can be broadly grouped into two types primitive types and
non-primitive types. The primitive data types can be further grouped into two types that is
numeric and non-numeric. The non-numeric data types include character and boolean
type. The non-primitive data types include strings, arrays and class types.
54 162
Data Types In Java
55 162
Primitive Data Types In Java
There are eight primitive data types supported by Java. The primitive data
types are predefined by the Java language and each data type is named by a keyword.
The primitive data types are the most commonly used and a special group of
data types that is used extensively in the Java programming. Although Java is
object-oriented but supports the primitive data types with the help of wrapper classes.
The sizes of the primitive data types is the same for all the operating system. This is one of
the key features of the Java language that makes Java so portable.
56 162
Primitive Data Types In Java
57 162
Non-primitive Data Types In Java
The non-primitive data type in Java include string data types, arrays and class types also
referred to as reference data types.
The Java programming language is extensible because the programmer can create classes
and then define a reference variable of that class type. The reference data type do not store
the values rather they store the address which points to an object.
The non-primitive data types are created by programmers as per the need of the program.
The non-primitive data types are not predefined in the Java language like primitive data
types.
When we define a reference variable of non-primitive data types, it points to a memory
location where data is actually stored in the Heap memory where an object is actually
stored.
For example, we can use arrays when we need to create a large number of variables of the
same data type. An array is a single object that contains multiple values of the same data
type that can be referred to with the same array name.
58 162
Non-primitive Data Types In Java
59 162
Presentation Outline
4 Memory Model
60 162
Java Keywords
61 162
Presentation Outline
4 Memory Model
62 162
Operators In Java
The operator in Java is a symbol that is used to perform specific operation as defined in the
Java language syntax.
The Java program statement or expression can contain number of operators. An operator in
Java is a special symbol that directs the compiler to perform some specific mathematical or
non-mathematical operations on one or more operands.
The Java language provides different types of operators to perform various operations. For
example unary operator, arithmetic operator, relational operator, shift operator, bitwise
operator, ternary operator and assignment operator.
The Java language supports eight different types of operators.
▶ Arithmetic ▶ Logical
▶ Uniry ▶ Ternary
▶ Assignment ▶ Bitwise
▶ Relational ▶ Shift
63 162
Operators In Java
64 162
Presentation Outline
4 Memory Model
65 162
Java Control Statements
The Java program is a collection of program statements. As the name suggests, the control
statements allows the programmer to control the logical flow of the program as per the
program logic.
The conditional control statements allow to first test the condition (usually an
mathematical expression) and then execute the statement block depending upon the
outcome of the condition.
The loop statements are also a type of program statement used in structured programming
languages to repeat ( reiteration ) some program statements for required number of times.
The loop will reiterate the statement block till the time the looping condition is evaluated
to either true or false.
Java control statement types:
▶ Conditional Control Statements
▶ Looping Control Statements
▶ Jumping Control Statements
66 162
Java Control Statements
67 162
Java Conditional Statements
The control statements are used to control the flow of the program. The conditional control
statements allow to first test the condition (usually an mathematical expression) and then
execute the statement block depending upon the outcome of the condition (either true or
false).
The control flow statements allow the Java program execution either sequentially, or
conditionally (with the help of if-else, and switch) or iteratively (with the help of loops) or
by using the combination of various control statements depending upon the program logic.
Conditional statement include:
▶ if statement
▶ if-else Statement
▶ Nested if-else statement
▶ switch statement
68 162
Java Looping Statements
The Java looping statements are used to repeat the program statement or a block of
statements code either certain number of times or till the time the looping condition is
evaluated to either true or false.
The Java programming language provides three types of looping constructs which can be
used by the programmer whenever a block of statements is required to be executed
number of times.
The Java looping control statements include:
▶ while loop statement
▶ do-while loop statement
▶ for loop statement
69 162
Java While Loop
A while loop is a control flow statement that allows the block of statements to be executed
repetitively based on a given boolean condition is evaluated to either true or false.
A while loop provides a exit mechanism such as loop counter variable which will keep the
track of the number of iterations after being incremented or decremented and the loop will
be terminated once condition is evaluated to false.
The while loop will always evaluate the looping condition first and then execute the code if
the boolean condition is evaluated to true.
1 while ( expression ) {
statement ( s )
3 }
70 162
Java Do While Loop
A do-while loop is a control flow statement that allows the block of statements to be
executed repetitively based on a given boolean condition is evaluated to either true or false.
The do-while loop will always first execute the statements in the loop body and then it will
test the looping condition.
The do-while execute the code at least once. The do while loop will continue the repeated
execution till boolean condition is evaluated to true. The loop will exit when the boolean
condition is evaluated to false.
1 do {
statement ( s )
3 } while ( expression ) ;
71 162
Java Do While Loop
A do while loop must provide a exit mechanism such as loop counter variable which will
keep the track of the number of iterations after being incremented or decremented.
The main difference between while loop and do-while loop is the order of execution of the
loop condition. The while loop always first test the loop condition whereas the do-while
loop will always first execute the statements in the loop body and then test the loop
condition.
1 c l a s s DoWhileDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 i n t count = 1 ;
do {
5 System . o u t . p r i n t l n ( " Count i s : " + c o u n t ) ;
count ++;
7 } while ( count < 1 1 ) ;
}
9 }
72 162
Java For Loop
The for loop will keep executing the code within its body for the specified number of times
as defined in the looping condition expression and will continue till the condition
expression is evaluated to true.
The control will exit the for loop either when the looping condition expression is evaluated
to false or the code executes a break (keyword) statement which terminates the for loop.
The for loop is mainly used in the program code where the number of loop iterations
are known before the loop starts and the loop counter is defined in the condition
expression to track the current number of the iteration completed by the for loop.
1 f o r ( i n i t i a l i z a t i o n ; c o n d i t i o n ; update ) {
statement ( s )
3 }
73 162
How Java For Loop Works?
1. The for loop starts with first initialization of the loop counter variable which is executed
only once in the beginning of the loop.
2. The loop condition expression is then evaluated with current value of the loop counter.
3. The statements within loop body are executed if the loop condition boolean
expression result to true.
4. The control is sent to the loop counter update section (increment / decrement) where the
counter is modified.
5. The control then again checks the loop condition with reference to the current value of the
loop counter variable.
6. The loop will exit if condition loop expression is evaluated to false.
74 162
Presentation Outline
4 Memory Model
75 162
Java Method Declaration
The Java program contains classes and a class contains member variables and functions
(methods). A method is a named block of code which performs a specific task as per the
program statements.
The variables within a class defines the state of an object whereas the methods defines the
behavior of an object. The methods operate on the data (variables) to perform various
operations.
The method needs to be explicitly called (invoked) in the program code along with the
arguments. The methods are also alternately referred as functions in other language but
both means the same.
The Java programmer can make use of either built-in methods or user defined methods
created as per the program needs.
The built-in methods are part of the classes that program can readily use by importing the
package which contains the class in which these methods have been defined.
76 162
Java Method Declaration
77 162
Java Method Types
The methods can be classified in Java in number of ways. The Java methods can either be
standard library methods (built-in methods) or user defined methods.
The Java languages provides extensive library of standard methods which are predefined in
the Java language. The programmer can simply import the package which contains the
class in which the method is defined to use in the program.
The programmer can also create and define a method as per the program requirements.
The programmer can use these methods by organizing the classes containing these
methods into various packages.
▶ Pre-defined (built-in) methods
▶ User-defined methods
78 162
Java Method Types
The Java methods can also be classified on the basis of scope of the method into two types
such as instance method and static methods.
Instance method
▶ The programmer can also create a method by declaring a method within a class body. The
method declared inside a class is referred as instance method. Which means each object
(instance) of the class will have this method.
▶ The instance method can be called (invoked) by creating an object of the class and by using
the object reference and the dot operator.
Static method
▶ A method can also be declared at the class level by using the java static keyword. The static
method will be one single method common for all objects. The static method can access only
static member variables within a class.
▶ The static method can be called (invoked ) without creating an object of the class and by using
the class name and the dot operator. The main method is an example of the static method.
79 162
Java Static Method Example (Structured Programming)
80 162
Presentation Outline
4 Memory Model
Stack
Heap
Variables and Program Memory in Java
6 References
81 162
Memory Layout
82 162
Presentation Outline
4 Memory Model
Stack
Heap
Variables and Program Memory in Java
6 References
83 162
What is Stack?
Stack is an abstract data type, a linear data structure that holds a collection of elements
that are added or removed in a Last In First Out (LIFO) manner. This means the element
added at the top will be removed first, just like we have a pile of plates one on top of the
other and you will take out the plate at the top first.
Stack supports two main operations:
▶ Push: Adding a data item to the array or list.
▶ Pop: Removing the most recently added data item.
The size of the stack gets adjusted based on Push or Pop operation.
84 162
Stack-Based Memory Allocation
Stack memory gets allocated to adjacent blocks or chunks of memory. Since this allocation
of memory happens in a function called Stack, it is named as Stack memory allocation.
Therefore, the popular use of Stack at the architecture level is memory allocation. A Stack
is that part of a computer memory that is used for contiguous, temporary memory
allocation. Stack has a fixed starting location, but variable size.
This memory allocation is temporary in nature and stores local variables along with those
arguments which are passed through a function along with their return addresses. All the
data belonging to the function which completes execution is quickly removed from the
Stack.
What this really means is that the value stored in Stack memory is available only until the
execution is still running and it will automatically erase the Stack memory after the task is
completed.
85 162
Stack Memory
86 162
Key Features of Stack Memory
It grows and shrinks as new methods are called and returned, respectively.
Variables inside the stack exist only as long as the method that created them is running.
It’s automatically allocated and deallocated when the method finishes execution.
If this memory is full, Java throws [Link].
Access to this memory is fast when compared to Heap memory.
This memory is threadsafe, as each thread operates in its own Stack.
87 162
Benefits and Drawbacks of Stack
Benefits
▶ Stack memory offers multiple advantages to the programmer at the time of compilation of the
code.
▶ The process of allocation and deallocation of memory can be controlled.
▶ The capability to manage data in LIFO (Last In First Out) gives the stack an edge over the
heap.
▶ Stack offers auto clean-up objects in memory and variables cannot be resized.
▶ The local variables are stored in the “called function” in the stack and are quickly terminated
on return.
Drawbacks
▶ Stack has a limited size for memory, which makes it unsuitable in case of the requirement of
large memory size.
▶ During the compilation of code, stack overflow can happen if the number of objects exceeds
the size of the stack.
88 162
Presentation Outline
4 Memory Model
Stack
Heap
Variables and Program Memory in Java
6 References
89 162
Heap Space
Heap space is used for the dynamic memory allocation of Java objects and JRE classes at
runtime. New objects are always created in Heap space, and the references to these objects
are stored in Stack memory.
These objects have global access and we can access them from anywhere in the application.
We can break this memory model down into smaller parts, called generations, which are:
1. Young Generation – this is where all new objects are allocated and aged. A minor Garbage
collection occurs when this fills up.
2. Old or Tenured Generation – this is where long surviving objects are stored. When objects
are stored in the Young Generation, a threshold for the object’s age is set, and when that
threshold is reached, the object is moved to the old generation.
3. Permanent Generation – this consists of JVM metadata for the runtime classes and
application methods.
The Garbage Collector (GC) is a program that manages the objects on the Heap, it deletes
objects that are no longer being used - freeing memory for future allocations. The GC frees
programmers of these memory management responsibilities.
90 162
Heap Memory Allocation
The allocation of Heap memory takes place at the time of execution of the instructions of the
programmer. The term Heap refers to a collection of memory that can be allocated and deallocated
by the programmer. Therefore, the Heap has no relation to the heap data structure.
It is important to understand that while the construction of an object happens in a Heap, however,
the corresponding information for these objects is saved in Stack memory. Heap memory often
suffers from security issues due to the visibility and accessibility of data stored in all threads.
This, sometimes, can lead to a situation of memory leak in the application if the programmer misses
handling Heap memory with care.
In Heap, data is stored in a hierarchical manner which leads to slow access as compared to Stack.
Do you remember how the old platter hard drives used to get clogged due to fragmentation?
Something similar happens with Heap memory as well. Fragmentation leads to the clogging of
Heap memory.
One of the major advantages of heap Hemory lies in the fact that there is no limitation on the size
of the memory and it also allows for resizing of variables as and when needed.
Heap memory is stored randomly, and that explains the slow speed of access because the data will
have to be pulled from multiple random places on the chip.
91 162
Key Features of Java Heap Memory
It’s accessed via complex memory management techniques that include the Young
Generation, Old or Tenured Generation, and Permanent Generation.
If Heap space is full, Java throws [Link].
Access to this memory is comparatively slower than Stack memory.
This memory, in contrast to Stack, isn’t automatically deallocated.
It needs Garbage Collector to free up unused objects so as to keep the efficiency of the
memory usage.
Unlike Stack, a Heap isn’t threadsafe and needs to be guarded by properly synchronizing
the code.
92 162
Advantages and Disadvantages of Heap
Advantages
▶ The heap does not have any limitation on the size of memory. This feature gives the Heap an
added advantage over the Stack.
▶ The variables in Heap memory can be accessed globally and can also be resized based on
requirements.
Disadvantages
▶ As compared to the Stack, Heap not only has a slower execution time but also the
management of memory is a complicated process.
▶ The computation process is also slow as compared to the stack. Continuous use of heap
memory can consume all the RAM from the computer.
93 162
Analyzing this code to assess how to manage memory
c l a s s Person {
2 private int id ;
p r i v a t e S t r i n g name ;
4
p u b l i c P e r s o n ( i n t i d , S t r i n g name ) {
6 this . id = id ;
t h i s . name = name ;
8 }
}
10
public class PersonBuilder {
12 p r i v a t e s t a t i c P e r s o n b u i l d P e r s o n ( i n t i d , S t r i n g name ) {
P e r s o n p e r s o n = new P e r s o n ( i d , name ) ;
14 return person ;
}
16
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
18 int id = 23;
S t r i n g name = " John " ;
20 Person person = n u l l ;
p e r s o n = b u i l d P e r s o n ( i d , name ) ;
22 }
}
94 162
How is memory managed?
1. When we enter the main() method, a space in Stack memory is created to store primitives
and references of this method.
▶ Stack memory directly stores the primitive value of integer id.
▶ The reference variable person of type Person will also be created in Stack memory, which will
point to the actual object in the Heap.
2. The call to the parameterized constructor Person(int, String) from main() will allocate
further memory on top of the previous Stack. This will store:
▶ The this object reference of the calling object in Stack memory.
▶ The primitive value id in the Stack memory.
▶ The reference variable of String argument name, which will point to the actual string from
String Pool in Heap memory.
3. The main method is further calling the buildPerson() static method, for which further
allocation will take place in Stack memory on top of the previous one. This will again store
variables in the manner described above.
4. However, Heap memory will store all instance variables for the newly created object person
of type Person.
95 162
Java Program Structure Example
96 162
Stack vs. Heap
97 162
Presentation Outline
4 Memory Model
Stack
Heap
Variables and Program Memory in Java
6 References
98 162
Variables and Program Memory
A computer program has memory allocated to it by the OS that is used to hold the data
that the program uses (i.e. to store variables) and other things.
We can think of that memory as being divided into different parts: the Stack, the Heap,
and everything else in the program’s memory (like the program’s machine instructions).
The Stack and the Heap store the values of the program’s variables – i.e. they store the
configuration of bits that a variable refers to. Thinking in this way: a variable is essentially
an association between a name in the source code and a block of memory which either
lives on the Stack or the Heap, with the contents of the block (some configuration of bits)
being the value of the variable.
Each Java variable has a specific type, and the contents of the memory block associated
with a given variable depend on its type.
Java variables fall into two distinct type categories – value types and reference types,
which are handled differently in memory. The type of a variable – specifically whether it’s
a reference or value type – and the context in which it was declared, determine whether it
is stored on the Stack or Heap.
99 162
Value Types vs. Reference Types
Value types
▶ A value type variable does hold the value to which it is associated.
Value types
▶ The value of a reference type is a reference (or null), meaning the value of a reference type is
the memory address of the object to which it refers. So, a reference type variable does not
hold the value of the object it refers to, it holds a reference to that object.
100 162
Where do Java variables get stored?
Java variables are stored on either the Stack or Heap, which one depends on whether the
variable is of reference or value type, and on the context in which the variable is declared.
Local variables (i.e. those that are declared inside methods) are stored on the Stack. This
means their values are stored on the Stack, therefore meaning that local reference type
variables have references stored on the Stack and local value type variables have actual
values stored on the Stack.
Objects of reference type variables (i.e. the things that references point to) always live on
the Heap.
Instance variables that are part of a reference type instance (e.g. a field on a class) are
stored on the Heap with the object itself.
Instance variables that are part of a value type instance are stored in the same context as
the variable that declares the value type. This means that a variable that is declared in a
method will live on the Stack, whilst a variable that is declared inside a class (i.e. a field on
the class) will live on the Heap.
101 162
Example of Allocating Local Primitive, Reference and Object
p u b l i c c l a s s Car {
2 p r i v a t e S t r i n g manufacturer ;
private int price ;
4
p u b l i c Car ( S t r i n g m a n u f a c t u r e r , i n t p r i c e ) {
6 t h i s . manufacturer = manufacturer ;
this . price = price ;
8 }
10 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
int price = 20000;
12 Car t e s t C a r = new Car ( " Audi " , p r i c e ) ;
}
14 }
102 162
Example of Allocating Local Primitive, Reference and Object
103 162
Example of Allocating Local Primitive, Reference and Object
In the main() method we’re declaring and initializing a local variable, price, of type int (value type),
we’re then declaring a variable of type Car (reference type), testCar, and initializing it with a
reference to a Car object. price is a local variable of value type, therefore it will live on the Stack;
testCar is a local variable of reference type, therefore it will live on the Stack, but, again, it’s a
reference type and so the thing stored on the Stack is a reference (i.e. a memory address), as
depicted in the diagram above. The actual Car object that the reference in testCar points to lives on
the Heap.
When the right-hand side of Car testCar = new Car("Audi", price) runs, the constructor to the Car
class runs, which is a method and so a new Stack frame is added to the Stack to hold the variables
for that method. The Car constructor is being called with the price variable as an argument for the
price parameter, therefore the int value from price (in main() Stack frame) is getting copied into the
price variable in the Car Stack frame (method parameters are local variables too).
There is also the manufacturer parameter on the constructor, which is being passed a new string
instance directly inside the call to the Car constructor, therefore there is a variable, manufacturer,
of type String on the Stack, living in the Car Stack frame. The Car constructor then copies the
values of these two variables from the Car Stack frame into the corresponding fields on the Car
object on the Heap.
104 162
Example of Allocating Object That Contains Another Object
p u b l i c c l a s s NumberOfSeatsAndDoors {
2 p r i v a t e i n t numSeats ;
p r i v a t e i n t numDoors ;
4
p u b l i c NumberOfSeatsAndDoors ( i n t numSeats , i n t numDoors ) { ... }
6 }
8 p u b l i c c l a s s Car {
p r i v a t e S t r i n g manufacturer ;
10 private int price ;
p r i v a t e NumberOfSeatsAndDoors numberOfSeatsAndDoors ;
12
public Car ( S t r i n g m a n u f a c t u r e r , i n t p r i c e , NumberOfSeatsAndDoors numberOfSeatsAndDoors ) {
14 this . manufacturer = manufacturer ;
this . price = price ;
16 this . numberOfSeatsAndDoors = numberOfSeatsAndDoors ;
}
18
p u b l i c s t a t i c v o i d main ( s t r i n g [ ] a r g s ) {
20 NumberOfSeatsAndDoors x = new NumberOfSeatsAndDoors ( 5 , 4 ) ;
Car t e s t C a r 1 = new Car ( " Audi " , 2 0 0 0 0 , x ) ;
22 Car t e s t C a r 2 = t e s t C a r 1 ;
}
24 }
105 162
Example of Allocating Object That Contains Another Object
106 162
Example of Allocating Object That Contains Another Object
107 162
Example of Allocating Memory When Calling a Funtion
p u b l i c c l a s s Car {
2 p u b l i c S t r i n g manufacturer ;
public int price ;
4
p u b l i c Car ( S t r i n g m a n u f a c t u r e r , i n t p r i c e ) {
6 t h i s . manufacturer = manufacturer ;
this . price = price ;
8 }
}
10
p u b l i c c l a s s Program {
12 p u b l i c s t a t i c v o i d main ( s t r i n g [ ] a r g s ) {
int price = 20000;
14 Car t e s t C a r = new Car ( " Audi " , p r i c e ) ;
inreaseCarPrice ( testCar , 5000) ;
16 }
18 p u b l i c s t a t i c v o i d i n c r e a s e C a r P r i c e ( Car c a r , i n t p r i c e I n c r e a s e ) {
c a r . p r i c e += p r i c e I n c r e a s e ;
20 }
}
108 162
Example of Allocating Memory When Calling a Funtion
109 162
Example of Allocating Memory When Calling a Funtion
We’re creating an int and assigning it into a local variable price, and declaring a variable,
testCar, and initializing it with a reference to a Car object, both of these variables live on
the Stack, whilst the Car object lives on the Heap.
Next, we’re calling the increaseCarPrice() method, which results in a new Stack frame
being pushed onto the Stack to contain the local variables of that method. testCar is being
passed as an argument for the car parameter, meaning the reference that it holds is being
copied into the local variable car in the Stack frame of the increaseCarPrice() method; a
new int of value 5000 is being created and assigned into the priceIncrease parameter. As a
result, the Stack frame associated with increaseCarPrice() contains an integer with value
5000 and a reference pointing to a Car object on the Heap. The line of code in the
increaseCarPrice() method is then being executed which changes the price field on the Car
object on the Heap.
When the program reaches the closing curly brace of the increaseCarPrice() method, the
corresponding Stack frame is popped off the Stack, resulting in the earlier Stack frame -
corresponding to the main() method - being at the top and its contents being in scope.
110 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
public static void main(String[] args) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
111 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
112 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
113 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1();
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
114 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
115 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
116 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2();
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
117 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
public static void func2() {
15 int d = 0;
}
17 }
118 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
119 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
120 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
121 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
122 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
[Link]("Done.");
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
123 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
124 162
Example of Stack Memory Allocation
1 p u b l i c c l a s s StackDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 int a = 42;
int b = 17;
5 func1 ( ) ;
System . o u t . p r i n t l n ( " Done . " ) ;
7 }
9 p u b l i c s t a t i c void func1 ( ) {
int c = 99;
11 func2 ( ) ;
}
13
p u b l i c s t a t i c void func2 ( ) {
15 int d = 0;
}
17 }
125 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
public static void main(String[] args) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
126 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 [Link](factorial(4));
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
127 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial(int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
128 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
129 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial(int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
130 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
131 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial(int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
132 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
133 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial(int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
134 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
135 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
136 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
137 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
138 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
139 162
Example of Stack Memory Allocation with Recursive Calls
1 public c l a s s FactorialDemo {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
3 System . o u t . p r i n t l n ( f a c t o r i a l ( 4 ) ) ;
}
5
public static int factorial ( int n) {
7 i f ( n == 1 ) {
return 1;
9 }
11 return n ∗ f a c t o r i a l (n − 1) ;
}
13 }
140 162
Presentation Outline
4 Memory Model
6 References
141 162
Parameter Passing Mechanism
Understanding the technique used to pass information between variables and into
methods can be a difficult task for a Java developer, especially those accustomed to a much
more verbose programming language, such as C or C++. In these expressive languages, the
developer is solely responsible for determining the technique used to pass information
between different parts of the system. For example, C++ allows a developer to explicitly
pass a piece of data either by value, by reference, or by pointer. The compiler simply
ensures that the selected technique is properly implemented and that no invalid operation
is performed.
In the case of Java, these low-level details are abstracted, which both reduces the onus on
the developer to select a proper means of passing data and increases the security of the
language (by inhibiting the manipulation of pointers and directly addressing memory).
In addition, though, this level of abstraction hides the details of the technique performed,
which can obfuscate a developer’s understanding of how data is passed in a program.
We should examine the various techniques used to pass data and deep-dive into the
technique that the Java Virtual Machine (JVM) and the Java Programming Language use to
pass data.
142 162
Terminology
In general, there are two main techniques for passing data in a programming language:
▶ Passing by value
▶ Passing by reference
Some languages consider passing by reference and passing by pointer two different
techniques, in theory, one technique can be thought of as a specialization of the other,
where a reference is simply an alias to an object, whose implementation is a pointer.
143 162
Presentation Outline
4 Memory Model
6 References
144 162
Passing by Value
Passing by value constitutes copying of data, where changes to the copied value are not
reflected in the original value.
Example
3 u s i n g namespace s t d ;
11 i n t main ( ) {
i n t someValue = 7 ;
13 c o u t << " V a l u e b e f o r e f u n c t i o n c a l l : " << someValue << e n d l ; // 7
p r o c e s s ( someValue ) ;
15 c o u t << " V a l u e a f t e r f u n c t i o n c a l l : " << someValue << e n d l ; // 7
17 return 0;
}
145 162
Passing by Value
The change made to the argument passed into the process() function was not preserved
after we exited the scope of the function. This loss of data was due to the fact that a copy
of the value held by the someValue variable was placed on the call stack prior to the
execution of the process function. Once the process function exited, this copy was popped
from the call stack and the changes made to it were lost.
146 162
Passing by Value
The figure illustrates the action of popping the call stack at the completion of the process
method.
The value copied as the argument to the process method is lost (reclaimed) once the call
stack is popped, and therefore, all changes made to that value are in turn lost during the
reclamation step.
147 162
Presentation Outline
4 Memory Model
6 References
148 162
Passing by Reference
Passing by reference consitutes the aliasing of data, where changes to the aliased value are
reflected in the original value.
Example
149 162
Passing by Reference
When exiting the function, the assignment we made to our argument that was passed by reference
was preserved outside of the scope of the function.
In the case of C++, we can see that under-the-hood, the compiler has passed a pointer into the
function that points to the someValue variable. Thus, when this pointer is dereferenced (as happens
during reassignment), we are making a change to the exact location in memory that stores the
someValue variable.
150 162
Presentation Outline
4 Memory Model
6 References
151 162
Parameter Passing Mechanism in Java
Unlike in C++, Java does not have a means of explicitly differentiating between pass by
reference and pass by value. Instead, the Java Language Specification declares that the
passing of all data, both object and primitive data, is defined by the rule: All data is passed
by value.
Primitives are Pass-By-Value
▶ They are always stored inside the Stack Memory. Different methods have different Stack
spaces. So changes to the values in another Stack Space are not present in the former location.
Objects are also Pass-By-Value
▶ The value associated with an object is actually a pointer, called a reference, to the object in
memory.
▶ Objects are stored inside the Heap. The reference/pointer is stored on the Stack. So changes to
the content of the object by another method are present to all references which identify the
same object. The object’s reference is passed by value, so the Heap address of the object is
copied and passed as a parameter to the called method.
Arguments in Java are always passed-by-value. There is NO pass-by-reference semantic in Java.
152 162
Example of Passing Object in Java
153 162
Example of Passing Object in Java
We can change the fields of the object that its reference passed into a method and invoke
its methods, but we cannot change the object that the reference points to.
Since the pointer is passed into the method by value, the original pointer is copied to the
call stack when the method is invoked. When the method scope is exited, the copied
pointer is lost, thus losing the change to the pointer value.
Although the pointer is lost, the changes to the fields are preserved because we are
dereferencing the pointer to access the pointed-to object: The pointer passed into the
method and the pointer copied to the call stack are identical (although independent) and
thus point to the same object.
Thus, when the pointer is dereferenced, the same object at the same location in memory is
accessed. Therefore, when we make a change to the dereferenced object, we are changing a
shared object.
Passing by reference in Java is also known as pass-by-sharing.
154 162
Example of Assigning Primitive to Variable
i n t someValue = 1 0 ;
2 i n t a n o t h e r V a l u e = someValue ;
someValue = 1 7 ;
4 System . o u t . p r i n t l n ( " Some v a l u e = " + someValue ) ;
System . o u t . p r i n t l n ( " A n o t h e r v a l u e = " + a n o t h e r V a l u e ) ;
Command window
1 Some v a l u e = 17
A n o t h e r v a l u e = 10
155 162
Example of Passing Primitive to Method
8 P r i m i t i v e P r o c e s s o r p r o c e s s o r = new P r i m i t i v e P r o c e s s o r ( ) ;
i n t someValue = 7 ;
10 System . o u t . p r i n t l n ( " B e f o r e c a l l i n g method ( v a l u e = " + someValue + " ) " ) ;
p r o c e s s o r . p r o c e s s ( someValue ) ;
12 System . o u t . p r i n t l n ( " A f t e r c a l l i n g method ( v a l u e = " + someValue + " ) " ) ;
Command window
B e f o r e c a l l i n g method ( v a l u e = 7 )
2 E n t e r e d method ( v a l u e = 7 )
Changed v a l u e w i t h i n method ( v a l u e = 5 0 )
4 L e a v i n g method ( v a l u e = 5 0 )
A f t e r c a l l i n g method ( v a l u e = 7 )
156 162
Example of Assigning Reference to Variable
3 B a l l s o m e B a l l = new B a l l ( ) ;
System . o u t . p r i n t l n ( " Some b a l l b e f o r e c r e a t i n g a n o t h e r b a l l = " + s o m e B a l l ) ;
5 B a l l anotherBall = someBall ;
s o m e B a l l = new B a l l ( ) ;
7 System . o u t . p r i n t l n ( " Some b a l l = " + s o m e B a l l ) ;
System . o u t . p r i n t l n ( " A n o t h e r b a l l = " + a n o t h e r B a l l ) ;
Command window
Some b a l l b e f o r e c r e a t i n g a n o t h e r b a l l = B a l l @ 6 0 7 3 f 7 1 2
2 Some b a l l = B a l l @ 2 f f 5 6 5 9 e
Another b a l l = Ball@6073f712
157 162
Example of Passing Reference to Method
158 162
Example of Passing Reference to Method
159 162
Example of Passing Reference to Method
Command window
160 162
Presentation Outline
4 Memory Model
6 References
161 162
References
162 / 162
Thank You!