Programs
Computer programs, known as software, are instructions to
the computer.
You tell a computer what to do through programs. Without
programs, a computer is an empty machine. Computers do
not understand human languages, so you need to use
computer languages to communicate with them.
Programs are written using programming languages.
Programming Languages
Machine Language Assembly Language High-Level Language
Machine language is a set of primitive instructions
built into every computer. The instructions are in
the form of binary code, so you have to enter binary
codes for various instructions. Program with native
machine language is a tedious process. Moreover
the programs are highly difficult to read and
modify. For example, to add two numbers, you
might write an instruction in binary like this:
1101101010011010
Programming Languages
Machine Language Assembly Language High-Level Language
Assembly languages were developed to make
programming easy. Since the computer cannot understand
assembly language, however, a program called assembler is
used to convert assembly language programs into machine
code. For example, to add two numbers, you might write
an instruction in assembly code like this:
ADDF3 R1, R2, R3
3
Programming Languages
Machine Language Assembly Language High-Level Language
The high-level languages are English-like and easy to learn
and program. For example, the following is a high-level
language statement that computes the area of a circle with
radius 5:
area = 5 * 5 * 3.1415;
4
Popular High-Level Languages
5
Interpreting/Compiling Source Code
A program written in a high-level language is
called a source program or source code.
Because a computer cannot understand a source
program, a source program must be translated
into machine code for execution. The
translation can be done using another
programming tool called an interpreter or a
compiler.
6
Interpreting Source Code
An interpreter reads one statement from the source
code, translates it to the machine code or virtual
machine code, and then executes it right away, as
shown in the following figure. Note that a statement
from the source code may be translated into several
machine instructions.
7
Compiling Source Code
A compiler translates the entire source code into a
machine-code file, and the machine-code file is
then executed, as shown in the following figure.
8
Java
v What do you know about Java?
A Little Bit of History
v 1950: FORTRAN
v 1959: COBOL
Ø Half business software still programmed in COBOL
v Mid 1960s: Basic
v 1971: Pascal
Ø Structured programming language
v 1970s & Early 1980s: Ada
A Little Bit of History
v 1972: C Programming Language
Ø What was there before C?
v 1983: ANSII C
v Early 1980’s: C++
Ø Object-oriented programming language
Ø Examples of other OO languages:
ü Smalltalk
ü Java
v 1991: Java (originally Oak) Came Into Being
A Little Bit of History
v 1993: World Wide Web Became Popular
Ø Java was saved!
v 1995: Java Formally Announced
v 2000: C#
Why Java?
v The Java programming language is robust and versatile,
enabling developers to:
Ø Write software on one platform and run it on another.
Ø Create programs to run within a web browser.
Ø Develop server-side applications for online forums, stores, polls,
processing HTML forms, and more.
Ø Write applications for cell phones, two-way pagers, and other
consumer devices.
Characteristics of Java
Java Is Simple Java is partially modeled on C++, but greatly
simplified and improved. Some people refer to
Java Is Object-Oriented Java as "C++--" because it is like C++ but
Java Is Distributed with more functionality and fewer negative
aspects.
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
15
Characteristics of Java
Java Is Simple Java is inherently object-oriented.
Although many object-oriented languages
Java Is Object-Oriented began strictly as procedural languages,
Java Is Distributed Java was designed from the start to be
object-oriented. Object-oriented
Java Is Interpreted programming (OOP) is a popular
Java Is Robust programming approach that is replacing
Java Is Secure traditional procedural programming
techniques.
Java Is Architecture-Neutral
Java Is Portable One of the central issues in software
development is how to reuse code. Object-
Java's Performance oriented programming provides great
Java Is Multithreaded flexibility, modularity, clarity, and
reusability through encapsulation,
Java Is Dynamic inheritance, and polymorphism.
16
Characteristics of Java
Java Is Simple Distributed computing involves several
computers working together on a network.
Java Is Object-Oriented Java is designed to make distributed
Java Is Distributed computing easy. Since networking
capability is inherently integrated into
Java Is Interpreted Java, writing network programs is like
Java Is Robust sending and receiving data to and from a
Java Is Secure file.
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
17
Characteristics of Java
Java Is Simple You need an interpreter to run Java
programs. The programs are compiled into
Java Is Object-Oriented the Java Virtual Machine code called
Java Is Distributed bytecode. The bytecode is machine-
independent and can run on any machine
Java Is Interpreted that has a Java interpreter, which is part of
Java Is Robust the Java Virtual Machine (JVM).
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
18
Characteristics of Java
Java Is Simple Java compilers can detect many problems
that would first show up at execution time
Java Is Object-Oriented in other languages.
Java Is Distributed
Java has eliminated certain types of error-
Java Is Interpreted prone programming constructs found in
Java Is Robust other languages.
Java Is Secure
Java has a runtime exception-handling
Java Is Architecture-Neutral feature to provide programming support
Java Is Portable for robustness.
Java's Performance
Java Is Multithreaded
Java Is Dynamic
19
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java implements several security
Java Is Robust mechanisms to protect your system against
Java Is Secure harm caused by stray programs.
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
20
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral Write once, run anywhere
Java Is Portable With a Java Virtual Machine (JVM),
Java's Performance you can write one program that will
run on any platform.
Java Is Multithreaded
Java Is Dynamic
21
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable Because Java is architecture neutral,
Java programs are portable. They can
Java's Performance be run on any platform without being
Java Is Multithreaded recompiled.
Java Is Dynamic
22
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable Java’s performance Because Java is
architecture neutral, Java programs are
Java's Performance portable. They can be run on any
Java Is Multithreaded platform without being recompiled.
Java Is Dynamic
23
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance Multithread programming is smoothly
Java Is Multithreaded integrated in Java, whereas in other
Java Is Dynamic languages you have to call procedures
specific to the operating system to enable
multithreading.
24
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance Java was designed to adapt to an evolving
environment. New code can be loaded on the
Java Is Multithreaded fly without recompilation. There is no need for
developers to create, and for users to install,
Java Is Dynamic major new software versions. New features can
be incorporated transparently as needed.
25
JDK Versions
JDK 1.02 (1995)
JDK 1.1 (1996)
JDK 1.2 (1998)
JDK 1.3 (2000)
JDK 1.4 (2002)
JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
JDK 1.6 (2006) a. k. a. JDK 6 or Java 6
JDK 1.7 (2011) a. k. a. JDK 7 or Java 7
JDK 1.8 (2014) a. k. a. JDK 8 or Java 8
26
JDK Editions
Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications
such as Java servlets, Java ServerPages, and Java
ServerFaces.
Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.
27
Popular Java IDEs
NetBeans
Eclipse
The Java Buzzwords
The key considerations were summed up by the Java
team in the following list of buzzwords:
v Simple
v Secure
v Portable
v Object-oriented
v Robust
v Multithreaded
v Architecture-neutral
v Interpreted
v High performance
v Distributed
v Dynamic
The Java Buzzwords
v simple – Java is designed to be easy for the
professional programmer to learn and use.
v object-oriented: a clean, usable, pragmatic
approach to objects, not restricted by the need for
compatibility with other languages.
v Robust: restricts the programmer to find the
mistakes early, performs compile-time (strong
typing) and run-time (exception-handling) checks,
manages memory automatically.
v Multithreaded: supports multi-threaded
programming for writing program that perform
concurrent computations
The Java Buzzwords
v Architecture-neutral: Java Virtual Machine
provides a platform independent environment for
the execution of Java byte code
v Interpreted and high-performance: Java programs
are compiled into an intermediate representation –
byte code:
Ø a) can be later interpreted by any JVM
Ø b)can be also translated into the native machine code for
efficiency.
The Java Buzzwords
v Distributed: Java handles TCP/IP protocols,
accessing a resource through its URL much like
accessing a local file.
v Dynamic: substantial amounts of run-time type
information to verify and resolve access to objects
at run-time.
v Secure: programs are confined to the Java
execution environment and cannot access other
parts of the computer.
The Java Buzzwords
v Portability: Many types of computers and
operating systems are in use throughout the
world—and many are connected to the Internet.
v For programs to be dynamically downloaded to all
the various types of platforms connected to the
Internet, some means of generating portable
executable code is needed. The same mechanism
that helps ensure security also helps create
portability.
v Indeed, Java's solution to these two problems is
both elegant and efficient.
Data Types
v Java defines eight simple types:
Ø 1)byte – 8-bit integer type
Ø 2)short – 16-bit integer type
Ø 3)int – 32-bit integer type
Ø 4)long – 64- bit integer type
Ø 5)float – 32-bit floating-point type
Ø 6)double – 64-bit floating-point type
Ø 7)char – symbols in a character set
Ø 8)boolean – logical values true and false
Data Types
vbyte: 8-bit integer type.
Ø Range: -128 to 127.
Ø Example: byte b = -15;
Ø Usage: particularly when working with data
streams.
vshort: 16-bit integer type.
Ø Range: -32768 to 32767.
Ø Example: short c = 1000;
Ø Usage: probably the least used simple type.
Data Types
vint: 32-bit integer type.
ØRange: -2147483648 to 2147483647.
ØExample: int b = -50000;
ØUsage:
ü1) Most common integer type.
ü2) Typically used to control loops and to
index arrays.
ü3)Expressions involving the byte, short
and int values are promoted to int before
calculation.
Data Types
vlong: 64-bit integer type.
Ø Range: -9223372036854775808 to
Ø 9223372036854775807.
Ø Example: long l = 10000000000000000;
Ø Usage:
ü1) useful when int type is not large enough to
hold the desired value
vfloat: 32-bit floating-point number.
Ø Range: 1.4e-045 to 3.4e+038.
Ø Example: float f = 1.5;
Ø Usage:
ü1) fractional part is needed
ü2) large degree of precision is not required
Data Types
vdouble: 64-bit floating-point
number.
ØRange: 4.9e-324 to 1.8e+308.
ØExample: double pi = 3.1416;
ØUsage:
ü1) accuracy over many iterative
calculations
ü2) manipulation of large-valued numbers
Data Types
vchar: 16-bit data type used to store
characters.
Ø Range: 0 to 65536.
Ø Example: char c = ‘a’;
Ø Usage:
ü1) Represents both ASCII and Unicode character
sets;
üUnicode defines a character set with characters
found in (almost) all human languages.
ü2)Not the same as in C/C++ where char is 8-bit
and represents ASCII only.
Data Types
vboolean: Two-valued type of logical
values.
ØRange: values true and false.
ØExample: boolean b = (1<2);
ØUsage:
ü1) returned by relational operators, such as
1<2
ü2)required by branching expressions such as
‘if’ or ‘for’
Variables
v declaration – how to assign a type to a
variable
v initialization – how to give an initial value to a
variable
v scope – how the variable is visible to other
parts of the program
v lifetime – how the variable is created, used
and destroyed
v type conversion – how Java handles automatic
type conversion
v type casting – how the type of a variable can
be narrowed down
Variables
vJava uses variables to store data.
vTo allocate memory space for a variable
JVM requires:
Ø 1) to specify the data type of the variable
Ø 2) to associate an identifier with the variable
Ø 3)optionally, the variable may be assigned an
initial value
vAll done as part of variable declaration.
Basic Variable Declaration
vdatatype identifier [=value];
vdatatype must be
Ø A simple datatype
Ø User defined datatype (class type)
v Identifier is a recognizable name
confirm to identifier rules
vValue is an optional initial value.
Variable Declaration
vWe can declare several variables at the
same time:
type identifier [=value][, identifier [=value] …];
üExamples:
§ int a, b, c;
§ int d = 3, e, f = 5;
§ byte g = 22;
§ double pi = 3.14159;
§ char ch = 'x';
Variable Scope
v Scope determines the visibility of program
elements with respect to other program elements.
v In Java, scope is defined separately for classes
and methods:
Ø 1) variables defined by a class have a global scope
Ø 2) variables defined by a method have a local scope
Ø A scope is defined by a block:
{
…
}
Ø A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
Variable Lifetime
v Variables are created when their scope is entered
by control flow and destroyed when their scope is
left
v A variable declared in a method will not hold its
value between different invocations of this
method.
v A variable declared in a block looses its value
when the block is left.
v Initialized in a block, a variable will be re-initialized
with every re-entry. Variables lifetime is confined
to its scope!
Arrays
vAn array is a group of like-typed variables
referred to by a common name, with
individual variables accessed by their
index.
vArrays are:
Ø 1) declared
Ø 2) created
Ø 3) initialized
Ø 4) used
vAlso, arrays can have one or several
dimensions.
Array Declaration
vArray declaration involves:
Ø1) declaring an array identifier
Ø2) declaring the number of dimensions
Ø3) declaring the data type of the array
elements
vTwo styles of array declaration:
Øtype array-variable[];
Øor
Øtype [] array-variable;
Array Creation
vAfter declaration, no array actually exists.
vIn order to create an array, we use the
new operator:
Øtype array-variable[];
Øarray-variable = new type[size];
vThis creates a new array to hold size
elements of type type, which reference
will be kept in the variable array-variable.
Array Indexing
vLater we can refer to the elements of this
array through their indexes:
Øarray-variable[index]
vThe array index always starts with zero!
vThe Java run-time system makes sure that
all array indexes are in the correct range,
otherwise raises a run-time error.
Array Initialization
vArrays can be initialized when they are
declared:
vint monthDays[] =
{31,28,31,30,31,30,31,31,30,31,30,31};
vNote:
Ø 1) there is no need to use the new operator
Ø 2)the array is created large enough to hold all
specified elements
Multidimensional Arrays
vMultidimensional arrays are arrays of
arrays:
v1) declaration: int array[][];
v2) creation: int array = new int[2][3];
v3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
Operators Types
vJava operators are used to build value
expressions.
vJava provides a rich set of operators:
Ø 1) assignment
Ø 2) arithmetic
Ø 3) relational
Ø 4) logical
Ø 5) bitwise
Arithmetic assignments
Basic Arithmetic Operators
Relational operator
Logical operators
Bit wise operators
Expressions
An expression is a construct made up of variables,
operators, and method invocations, which are constructed
according to the syntax of the language, that evaluates to a
single value.
Examples of expressions are in bold below:
int number = 0;
anArray[0] = 100;
System.out.println ("Element 1 at index 0: " +
anArray[0]);
int result = 1 + 2; // result is now 3 if(value1 ==
value2)
System.out.println("value1 == value2");
Expressions
v The data type of the value returned by an expression
depends on the elements used in the expression.
v The expression number = 0 returns an int because the
assignment operator returns a value of the same data
type as its left-hand operand; in this case, number is an
int.
v As you can see from the other expressions, an
expression can return other types of values as well, such
as boolean or String.
v The Java programming language allows you to construct
compound expressions from various smaller expressions
as long as the data type required by one part of the
expression matches the data type of the other.
v Here's an example of a compound expression: 1 * 2 * 3
Control Statements
v Java control statements cause the flow of
execution to advance and branch based on the
changes to the state of the program.
v Control statements are divided into three
groups:
Ø 1) selection statements allow the program to choose
different parts of the execution based on the
outcome of an expression
Ø 2) iteration statements enable program execution to
repeat one or more statements
Ø 3) jump statements enable your program to execute
in a non-linear fashion
Selection Statements
vJava selection statements allow to
control the flow of program’s execution
based upon conditions known only
during run-time.
vJava provides four selection statements:
Ø1) if
Ø2) if-else
Ø3) if-else-if
Ø4) switch
Iteration Statements
vJava iteration statements enable
repeated execution of part of a program
until a certain termination condition
becomes true.
vJava provides three iteration
statements:
Ø1) while
Ø2) do-while
Ø3) for
Jump Statements
vJava jump statements enable transfer of
control to other parts of program.
vJava provides three jump statements:
Ø1) break
Ø2) continue
Ø3) return
vIn addition, Java supports exception
handling that can also alter the control
flow of a program.
Type Conversion
vSize Direction of Data Type
Ø – Widening Type Conversion (Casting down)
ü• Smaller Data Type -> Larger Data Type
Ø – Narrowing Type Conversion (Casting up)
ü• Larger Data Type -> Smaller Data Type
v• Conversion done in two ways
Ø – Implicit type conversion
ü• Carried out by compiler automatically
Ø – Explicit type conversion
ü• Carried out by programmer using casting
Type Conversion
v• Widening Type Converstion
Ø – Implicit conversion by compilerautomatically
Type Conversion
v• Narrowing Type Conversion
Ø – Programmer should describethe conversion
explicitly
Type Conversion
vbyte and short are always promoted to
int
vif one operand is long, the whole
expression is promoted to long
vif one operand is float, the entire
expression is promoted to float
vif any operand is double, the result is
double
Type Casting
vGeneral form: (targetType) value
Ø Examples:
Ø 1) integer value will be reduced module bytes
range:
üint i;
übyte b = (byte) i;
Ø 2) floating-point value will be truncated to
integer value:
üfloat f;
üint i = (int) f;
Simple Java Program
A class to display a simple message:
class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java
program.");
}
}
Creating, Compiling, and
Running Programs
Compiling Java Source Code
You can port a source program to any machine with appropriate
compilers. The source program must be recompiled, however, because
the object program can only run on a specific machine. Nowadays
computers are networked to work together. Java was designed to run
object programs on any platform. With Java, you write the program
once, and compile the source program into a special type of object
code, known as bytecode. The bytecode can then run on any computer
with a Java Virtual Machine, as shown below. Java Virtual Machine is
a software that interprets Java bytecode.
72
animation
Trace a Program Execution
Enter main method
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
73
animation
Trace a Program Execution
Execute statement
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
74
animation
Trace a Program Execution
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
print a message to the
console
75
Java Programs
v Create or write your Java programs using any text
editor. It is always best to use a text editor that
recognizes Java instructions.
v Save your programs with a .java extension
Ø welcome.java
v Compile your java program in the command
window by typing
Ø javac welcome.java
Ø You will need to go to the directory containing your file
Java Programs
v Compiling Java programs creates a new file with
the same name and the extension .class
Ø welcome.class
v This file contains the bytecode that will be
interpreted during the next step
v You run the Java program by typing
Ø java welcome
v In this stage the program is loaded into memory
and executed
What is an Object?
v Real world objects are things that have:
Ø 1) state
Ø 2)behavior
Ø Example: Mydog:
v state – name, color, breed
v behavior – sitting, barking, waging tail,
running
v A software object is a bundle of variables
(state) and methods (operations).
What is a Class?
vA class is a blueprint that defines the
variables and methods common to all
objects of a certain kind.
vExample: ‘Mydog’ is an object of the class
Dog.
vAn object holds values for the variables
defined in the class.
vAn object is called an instance of the Class
Object Creation
vA variable is declared to refer to the objects
of type/class String:
String s;
vThe value of s is null; it does not yet refer
to any object.
vA new String object is created in memory
with initial “abc” value:
vString s = new String(“abc”);
vNow s contains the address of this new
object.
Object Destruction
v A program accumulates memory through its
execution.
v Two mechanisms to free memory that is no longer
need by the program:
Ø 1) manual – done in C/C++
Ø 2) automatic – done in Java
v In Java, when an object is no longer accessible
through any variable, it is eventually removed
from the memory by the garbage collector.
v Garbage collector is part of the Java Run-Time
Environment.
Class
vA basis for the Java language.
vEach concept we wish to describe in Java
must be included inside a class.
vA class defines a new data type, whose
values are objects:
vA class is a template for objects
vAn object is an instance of a class
Class Definition
vA class contains a name, several variable declarations
(instance variables) and several method declarations. All
are called members of the class.
vGeneral form of a class:
class classname {
type instance-variable-1;
…
type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }
…
type method-name-m(parameter-list) { … }
}
Example: Class Usage
class Container {
double width;
double height;
double depth;
}
class ContainerDemo {
public static void main(String args[]) {
Container mycontnr = new Container();
double vol;
mycontnr.width = 10;
mycontnr.height = 20;
mycontnr.depth = 15;
vol = mycontnr.width * mycontnr.height *
mycontnr.depth;
System.out.println ("Volume is " + vol);
}}
Constructor
v A constructor initializes the instance variables of
an object.
v It is called immediately after the object is created
but before the new operator completes.
Ø 1) it is syntactically similar to a method:
Ø 2) it has the same name as the name of its class
Ø 3)it is written without return type; the default return type
of a class
v constructor is the same class When the class has
no constructor, the default constructor
automatically initializes all its instance variables
with zero.
What is a Constructor?
vConstructor is a special method that gets invoked
“automatically” at the time of object creation.
vConstructor is normally used for initializing objects with
default values unless different values are supplied.
vConstructor has the same name as the class name.
vConstructor cannot return values.
vA class can have more than one constructor as long as they
have different signature (i.e., different input arguments syntax).
Defining a Constructor
Like any other method
public class ClassName {
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
Invoking:
There is NO explicit invocation statement needed: When the
object creation statement is executed, the constructor method
will be executed automatically.
Defining a Constructor: Example
public class Counter {
int CounterIndex;
// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
A Counter with User Supplied
Initial Value ?
This can be done by adding another constructor method
to the class.
public class Counter {
int CounterIndex;
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
// A New User Class: Utilising both constructors
Counter counter1 = new Counter();
Counter counter2 = new Counter (10);
Multiple Constructors: Example
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double radius) {
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Method Overloading
vConstructors all have the same name.
vMethods are distinguished by their signature:
Øname
Ønumber of arguments
Øtype of arguments
Øposition of arguments
vThat means, a class can also have multiple usual
methods with the same name.
The New this keyword
this keyword can be used to refer to the object itself.
vIt is generally used for accessing class members (from its
own methods) when they have the same name as those passed
as arguments.
public class Circle {
public double x,y,r;
// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
}
What is Garbage Collection?
vMemory Management technique.
vProcess of freeing objects.
vNo longer referenced by the program.
Why Garbage Collection?
vFree unreferenced objects.
vCombat heap fragmentation.
vRelieves programmer from manual freeing the
memory.
vHelps in ensuring program integrity.
vDisadvantages
vExtra Overhead.
vLess control over scheduling of CPU time.
Garbage Collection in Java
Purpose
Find and delete unreachable objects.
Free space as much as possible.
When??
GC is under control of JVM.
One can request but no guarantees.
How??
Discovery of unreachable objects.
With the help of Algorithms.
Garbage Collection in Java
Ways for making objects eligible for collection
vNulling a reference
vReassigning a reference variable
vIsolating a reference
Forcing garbage collection
vMethods available to perform GC
vOnly requests and no demands
vUsing Runtime class
vUsing static methods like System.gc()
Garbage Collection Algorithms
Basic Approaches
vReference Counting
vTracing
vCompacting
vCopying
vGenerational
vThe Train Algorithm
Binding
vBinding is what happens when a method
invocation is bound to an implementation
ØInvolves lookup of the method in the
class, or one or its parents
ØBoth method names and parameters
are checked
vBinding can happen at two different times
ØCompile time == static binding
ØRun time == dynamic binding
Dynamic Binding
vAchieved at runtime
ØWhen the class of an object cannot be determined at
compile time
ØMeans the JVM (not the compiler) must bind a
method call to its implementation
vInstances of a sub-class can be treated as if they were
an instance of the parent class
ØTherefore the compiler doesn’t know its type, just
its base type.
Dynamic Binding Summary
vWhenever a reference refers to an interface or a base
class, methods are dynamically bound
vMethod implementation determined at runtime
vDynamic Binding == Polymorphism
vVery powerful OO feature
ØAllows the creation of “frameworks”
vApplications that are implemented around interfaces, but
are customised by plugging in different implementations of
those interfaces
ØVery extensible
Kinds of Classes
vTop level classes
ØDeclared inside package
ØVisible throughout package, perhaps further
ØNormally, although not always, declared in their
own file
Øpublic classes must be defined in their own file
vNested and inner classes
ØDeclared inside class (or method)
Øcan be visible only to outer class, or have wider
visibility
Kinds of nested/inner classes
vInner class
Ødefined inside another class
Øbut each instance of an inner class is transparently
associated with an instance of the outer class
Ømethod invocations can be transparently redirected to
outer instance
vNested class
Ødefined inside another class
ØIt has unlimited access to its enclosing class members
ØIt does not have access to the instance variables or
methods of the outer class, unless they are explicitly
passed
Inner Classes
Description
Class defined in scope of another class
Property
Can directly access all variables & methods of
enclosing class (including private fields & methods)
Example
public class OuterClass {
public class InnerClass {
...
}
}
Example of Inner Classes
Motivating Example for Inner and Nested Classes
Let's consider a real-world scenario to make the concepts of inner
and nested classes more motivating. We will use the example of an
Online Shopping System where we have an outer class
representing an Order and inner and nested classes representing
Item and OrderStatus.
ØThe Order class has an orderId, a customer, and a list of Item
objects.
ØThe inner class Item can directly access and modify the Order's
list of items.
ØThe inner class helps in logically grouping the items with the
order they belong to.
ØThe main method creates an Order and adds items to it using the
inner class.
Example of Inner Classes
class OuterClass {
private String outerField = "Outer field";
private static String staticOuterField = "Static Outer Field";
void outerMethod() {
System.out.println("Outer Method");
}
class InnerClass {
void display() {
// Accessing outer class's private field and method
System.out.println("Accessing: " + outerField);
outerMethod();
}
}
public static void main(String[] args) {
// Instantiating inner class
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}
}
Nested Classes
Declared like a standard inner class, except you say
“static class” rather than “class”.
For example:
class LinkedList {
static class Node {
Object head;
Node tail;
}
Node head;
}
Example of Nested Classes
Scenario: Company and Department
Let's consider a Company that has multiple Departments. the
Company class contains a static nested class Department. The
Department class represents different departments within the
company and is independent of any specific instance of Company.
ØThe Company class need not have any instance variables or
methods directly related to departments.
ØThe static nested class Department represents different departments
within the company.
ØThe Department class has instance variables name and manager
and a method displayDepartment to display department details.
ØThe static nested class can be used to create and manage department
instances independently of any specific Company instance.
Example of Nested Classes
class OuterClass {
private static String staticOuterField = "Static Outer Field";
static void staticOuterMethod() {
System.out.println("Static Outer Method");
}
static class StaticNestedClass {
void display() {
// Accessing static members of the outer class
System.out.println("Accessing: " + staticOuterField);
staticOuterMethod();
}
}
public static void main(String[] args) {
// Instantiating static nested class
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display();
}
Example: Constructor
class Container {
double width;
double height;
double depth;
Container() {
System.out.println("Constructing Container");
width = 10; height = 10; depth = 10;
}
doublevolume() {
return width * height * depth;
}
}
Parameterized Constructor
class Container {
double width;
double height;
double depth;
Container(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
Methods
v General form of a method definition:
type name(parameter-list) {
… return value;
…
}
v Components:
1)type - type of values returned by the method. If
a method does not return any value, its return type
must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier
lists separated by commas
4) return value indicates what value is returned by
the method.
Example: Method
vClasses declare methods to hide their internal data
structures, as well as for their own internal use: Within
a class, we can refer directly to its member variables:
class Container {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height *
depth);
}
}
Parameterized Method
vParameters increase generality and
applicability of a method:
v1) method without parameters
Ø int square() { return 10*10; }
v2) method with parameters
Ø int square(int i) { return i*i; }
vParameter: a variable receiving value at
the time the method is invoked.
Java Modifier Types
1. Java Access Modifiers
vJava provides a number of access modifiers to set
access levels for classes, variables, methods and
constructors.
vThe four access levels are:
Ø Visible to the package, the default. No modifiers
are needed.
Ø Visible to the class only (private).
Ø Visible to the world (public).
Ø Visible to the package and all subclasses
(protected).
Java Modifier Types
vDefault Access Modifier - No keyword:
vDefault access modifier means we do not explicitly
declare an access modifier for a class, field, method, etc.
vA variable or method declared without any access
control modifier is available to any other class in the
same package.
vExample: Variables and methods can be declared
without any modifiers, as in the following example:
String version ="1.5.1";
boolean processOrder(){
return true;
}
Java Modifier Types
v Private Access Modifier - private:
v Methods, Variables and Constructors that are declared private can only
be accessed within the declared class itself.
v Variables that are declared private can be accessed outside the class if
public getter methods are present in the class.
v Using the private modifier is the main way that an object encapsulates
itself and hides data from the outside world.
v Example:
v The following class uses private access control:
public class Logger{
private String format;
public String getFormat(){
return this.format;
}
public void setFormat(String format){
this.format = format;
}
}
Java Modifier Types
v Public Access Modifier - public:
v A class, method, constructor, interface etc declared public
can be accessed from any other class. Therefore fields,
methods, blocks declared inside a public class can be
accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a
different package, then the public class still need to be
imported.
v Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.
v Example:
The following function uses public access control:
public static void main(String[] arguments){
// ...
}
Java Modifier Types
v Protected Access Modifier - protected:
v Variables, methods and constructors which are declared protected
in a superclass can be accessed only by the subclasses in other
package or any class within the package of the protected members'
class.
v Protected access gives the subclass a chance to use the helper
method or variable, while preventing a nonrelated class from trying
to use it.
v Example:
v The following parent class uses protected access control, to allow its child class
overrideopenSpeaker() method:
Ø class AudioPlayer{
Ø protected boolean openSpeaker(Speaker sp){
ü // implementation details
Ø }
Ø }
Ø class StreamingAudioPlayer{
Ø boolean openSpeaker(Speaker sp){
ü // implementation details
Ø }
Ø }
Java Modifier Types
v Access Control and Inheritance:
The following rules for inherited methods are
enforced:
Methods declared public in a superclass also must be
public in all subclasses.
Methods declared protected in a superclass must either
be protected or public in subclasses; they cannot be
private.
Methods declared without access control (no modifier was
used) can be declared more private in subclasses.
Methods declared private are not inherited at all, so there
is no rule for them.
Comparison of Types of
Access Modifier in Java
Members of Java that can be assigned
with the Java Access Modifiers
Java Modifier Types
v Non Access Modifiers:
Java provides a number of non-access modifiers to
achieve many other functionality.
The static modifier for creating class methods and
variables
The final modifier for finalizing the implementations of
classes, methods, and variables.
The abstract modifier for creating abstract classes and
methods.
The synchronized and volatile modifiers, which are used
for threads.
To use a modifier, you include its keyword in the
definition of a class, method, or variable.
Static
Purpose: Used to create class-level variables and methods,
which are shared among all instances of the class.
Example:
class StaticExample {
static int staticVariable = 10; // static variable
static void staticMethod() { // static method
System.out.println("Static method called.");
}
public static void main(String[] args) {
// Accessing static variable and method without creating an instance
System.out.println(StaticExample.staticVariable);
StaticExample.staticMethod();
}
}
staticVariable and staticMethod can be accessed without creating an instance of StaticExample.
Final
Purpose: Used to declare constants, prevent method overriding,
and prevent inheritance.
Example:
final class FinalClass { // final class
final int finalVariable = 100; // final variable
final void finalMethod() { // final method
System.out.println("Final method called.");
}
}
class FinalExample { // This will cause a compile error
// void finalMethod() { } // This will cause a compile error
public static void main(String[] args) {
FinalClass obj = new FinalClass();
System.out.println(obj.finalVariable);
obj.finalMethod();
}
}
FinalClass cannot be extended. finalVariable value cannot be changed. finalMethod cannot be overridden.
Abstract
Purpose: Used to define abstract classes and methods that must be
implemented by subclasses.
Example:
abstract class AbstractClass {
abstract void abstractMethod(); // abstract method
void concreteMethod() {
System.out.println("Concrete method called.");
}
}
class ConcreteClass extends AbstractClass {
@Override
void abstractMethod() {
System.out.println("Abstract method implemented.");
}
}
public class AbstractExample {
public static void main(String[] args) {
ConcreteClass obj = new ConcreteClass();
obj.abstractMethod();
obj.concreteMethod();
}
}
AbstractClass cannot be instantiated directly.
abstractMethod must be implemented by the subclass ConcreteClass.
Exception Handling in Java
ØException Handling
ØAdvantage of Exception Handling
ØHierarchy of Exception classes
Types of Exception
1. Checked Exception
2. Unchecked Exception
3. Error
5. Scenarios where exception may occur
Exception Types
System Errors
System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Exceptions
Exception describes errors
caused by your program
and external
circumstances. These
errors can be caught and
handled by your program.
Runtime Exceptions
Checked Exceptions vs.
Unchecked Exceptions
RuntimeException, Error and their subclasses are
known as unchecked exceptions. All other
exceptions are known as checked exceptions,
meaning that the compiler forces the programmer
to check and deal with the exceptions.
Unchecked Exceptions
String Handling
vString is probably the most commonly used class in
Java's class library. The obvious reason for this is
that strings are a very important part of
programming.
vThe first thing to understand about strings is that
every string you create is actually an object of type
String. Even string constants are actually String
objects.
vFor example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String
constant
String Handling
vJava defines one operator for String objects: +.
vIt is used to concatenate two strings. For example,
this statement
vString myString = "I" + " like " + "Java.";
results in myString containing
"I like Java."
String Handling
v The String class contains several methods that
you can use. Here are a few. You can
v 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:
v // Demonstrating some String methods.
v class StringDemo2 {
v public static void main(String args[]) {
v String strOb1 = "First String";
v String strOb2 = "Second String";
v String strOb3 = strOb1;
v System.out.println("Length of strOb1: " +
v strOb1.length());
String Handling
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}}
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
String Handling
Restrictions:
May not span multiple lines.
"This is not
a legal String."
May not contain a " character.
"This is not a "legal" String either."
Escape sequences
escape sequence: A special sequence of characters
used to represent certain special characters in a
string.
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
Example:
System.out.println("\\hello\nhow\tare \"you\"?\\\\");
Output:
\hello
Questions
What is the output of the following println
statements?
System.out.println("\ta\tb\tc");
System.out.println("\\\\");
System.out.println("'");
System.out.println("\"\"\"");
System.out.println("C:\nin\the
downward spiral");
Write a println statement to produce this output:
/ \ // \\ /// \\\
Answers
Output of each println statement:
a b c
\\
'
"""
C:
in he downward spiral
println statement to produce the line of output:
System.out.println("/ \\ // \\\\ ///
\\\\\\");
Questions
What println statements will generate this output?
This quote is from
Irish poet Oscar Wilde:
"Music makes one feel so romantic
- at least it always gets on one's nerves –
which is the same thing nowadays."
What println statements will generate this output?
A "quoted" String is
'much' better if you learn
the rules of "escape sequences."
Also, "" represents an empty String.
Don't forget: use \" instead of " !
'' is not the same as "
Answers
println statements to generate the output:
System.out.println("This quote is from");
System.out.println("Irish poet Oscar Wilde:”);
System.out.println();
System.out.println("\"Music makes one feel so romantic");
System.out.println("- at least it always gets on one's nerves -");
System.out.println("which is the same thing nowadays.\"");
println statements to generate the output:
System.out.println("A \"quoted\" String is");
System.out.println("'much' better if you learn");
System.out.println("the rules of \"escape sequences.\"");
System.out.println();
System.out.println("Also, \"\" represents an empty String.");
System.out.println("Don't forget: use \\\" instead of \" !");
System.out.println("'' is not the same as \"");
THANK YOU
Java Programming
These slides contain either partial or complete
content from various websites, presentations and
other internet based resources. The author
acknowledges the contributions of all those
whose work has become part of these slides
either in part or full and assures that these have
been used for padagogical purposes only.