You are on page 1of 112

Java Basic

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Introduction
• JAVA was originated at Sun Microsystems Inc.,
in 1991.

• It was conceived by James Gosling and Patrick


Naughton.

• Simple programming language to write, compile


and debug a program easily.

• Helps
WAY TO toIT create modular programs and
COMPUTER reusable
EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Powerful Features

• Java has the following features


– Object Oriented
– Simplicity
– Robustness
– Platform Independence (Portable)
– Security
– Distributed Applications
– Multithreading

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java is Object Oriented

• Object oriented programming is a method in


which programs are organized as collection of
objects, each of which represents an instance of
a class

• 4 main concepts of OOP are


– Abstraction
– Encapsulation
– Inheritance
– Polymorphism

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Object Oriented Programming
• Abstraction
– Denotes the extraction of essential characteristics of an
object that distinguish from all other kinds of objects.
• Encapsulation
– Hiding the implementation details of a class.
– Forces the user to use an interface to access the data.
• Inheritance
– Process by which one class acquires the properties and
functionalities of the other.
• Polymorphism
WAY – TO ITthe ability of methods to existCOMPUTER
Means in several different
EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java is a Simple Language

• Does not have complex features as other


programming languages like

– Operator overloading,
– Multiple inheritance through classes, pointers
and
– Explicit memory allocation.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java is a Robust Language

• Two main hurdles which cause program failures


i.e memory management mistakes and
mishandled runtime errors can be overcome.

– Memory management mistakes can be overcome by


garbage collection. Garbage collection is automatic
de-allocation of objects which are no longer needed.

– Mishandled runtime errors are resolved by Exception


Handling procedures.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java is Secure

• Provides a virtual firewall between the


application and the computer.

• Java codes are confined within Java


Runtime Environment (JRE).

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java is Distributed

• Java is designed for the distributed


environment of the internet.

• Objects on one JVM can execute


procedures on a remote JVM.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Multithreading

• Enables a program to perform several


tasks simultaneously.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Write Once, Run Anywhere
Java is Platform Independent

JAVA COMPILER
(translator
)

JAVA BYTE CODE


(same for all platforms)

JAVA INTERPRETER
(one for each different system)

Windows 7 Macintos Solari Windows Vista


WAY TO IT h s COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java is Platform Independent

• An application developed on Java can run in any


machine.

• When Java is compiled, it is not compiled into


platform specific machine or platform
independent byte code.
• The byte code is distributed over the web and
interpreted by Java Virtual Machine (JVM) on
whichever platform it is run.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java Virtual Machine(JVM)
• JVM acts as an interpreter and converts byte codes to
machine codes.
• The source code of Java is stored with “.java” extension
and the compiler ie., javac converts .java code into byte
code.
• Byte codes are Binary Language codes and will be in a file
with extension “.class”.
• The byte codes are interpreted by JVM and .class file that is
generated is the machine code of the processor.
• JVM is platform dependent.
WAY TOJVMITmust be implemented on a COMPUTER
• The EDUCATION
particular platform
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Installing and Using Java

• First install Java 2 JDK version 7

• This can be downloaded from the official


website of Java

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Setting the Environmental Variables
• Environmental variables describe the operating environment
of the process.
• Some common environmental variables describe the home
directory and command search path.
• How to set environmental variables?
⚫ Setting JAVA_HOME helps to derive all other environmental
variables used in JVM.
⚫ The following commands can be typed in the command
prompt,
⚫ Windows:
JAVA_HOME=C:\Java installation directory
⚫ UNIX:
JAVA_HOME=/var/usr/java
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Setting the CLASSPATH

• Windows:
– Set CLASSPATH=%CLASSPATH%;%JAVA_HOME%\lib\tools.jar;

• UNIX:
– Set CLASSPATH=$CLASSPATH:$JAVA_HOME/lib/tools.jar;

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Setting the PATH

• The PATH variable is used to locate the


executable files by the operating system.

• Windows:
– Set PATH=%PATH%; %JAVA_HOME%\bin

• UNIX:
– Set PATH=$PATH: $JAVA_HOME/bin

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Compilation and Execution of Java Program

• To create a java code an editor such as


notepad, text pad or an IDE like eclipse can
be used.
• Sample Java Program:
public class WelcomeApp {
public static void main(String[] args){
System.out.println(“Welcome to Java”);
}//End of main
}//End of WelcomeApp Class

Output : Welcome to Java

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
• In the above program the class WelcomeApp has
public access and hence declared public.

• ‘class’ is the keyword used to create a class.

• For running stand alone programs ‘main’ method


is needed which has a signature similar to the one
defined in the above program.

• ‘Main’ method takes an array of strings as an


argument. The name of the array can be anything.

• To display the output, pass the string as an


argument to the method system.out.println
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Compiling and Executing a Java Program
• Step1: Save the source file as WelcomeApp.java
• Step2: Open command prompt and navigate to the directory where
you have stored the file.
• Step 3: To compile, type javac WelcomeApp.java and press Enter.
• Step 4: On successful compilation, you will see the command
prompt and WelcomeApp.class file in the same folder where
WelcomeApp.java is stored. This is the byte code of the program.
• Step 5: To execute, type java WelcomeApp. Do not type the
extension while executing.
• Step 6: See the output Welcome to Java displayed on the console.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Common Programming Errors in Java
The following are the general programming errors and the solution for them
while running on windows machine.

‘javac’ is not recognized as an internal or external command, operable


program or batch file
This means that the operating system cannot find the compiler - javac. In
order to resolve this the PATH variable has to be set.

Exception in thread “main”java.lang.NoClassDefFoundError:


WelcomeApp
This error means that java cannot find your compiled byte code,
WelcomeApp.class. If the class file is present in directory other than the
directory where java file is stored, then the CLASSPATH must be set
pointing to the directory that contain compiled class files.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Java Development Kit

• javac - The Java Compiler


• java - The Java Interpreter
• jdb- The Java Debugger
• appletviewer -Tool to run the applets

• javap - to print the Java bytecodes


• javaprof - Java profiler
• javadoc - documentation generator
• javah - creates C header files

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Data Types

There are two data types available in Java:


•Primitive Data Types
•Reference/Object Data Types

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive
data types are predefined by the language and named by a key
word. Let us now look into detail about the eight primitive data
types.

•byte: Byte data type is a 8-bit signed two's complement integer.


– Minimum value is -128 (-2^7)
– Maximum value is 127 (inclusive)(2^7 -1)
– Default value is 0
– Byte data type is used to save space in large arrays, mainly in
place of integers, since a byte is four times smaller than an int.
– Example : byte a = 100 , byte b = -50

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Primitive Data Types
• short: Short data type is a 16-bit signed two's complement
integer.
– Minimum value is -32,768 (-2^15)
– Maximum value is 32,767(inclusive) (2^15 -1)
– Short data type can also be used to save memory as byte data
type. A short is 2 times smaller than an int
– Default value is 0.
– Example : short s= 10000 , short r = -20000

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Primitive Data Types
• int: Int data type is a 32-bit signed two's complement integer.
– Minimum value is - 2,147,483,648.(-2^31)
– Maximum value is 2,147,483,647(inclusive).(2^31 -1)
– Int is generally used as the default data type for integral values
unless there is a concern about memory.
– The default value is 0.
– Example : int a = 100000, int b = -200000

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Primitive Data Types
• long: Long data type is a 64-bit signed two's complement
integer.
– Minimum value is -9,223,372,036,854,775,808.(-2^63)
– Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
– This type is used when a wider range than int is needed.
– Default value is 0L.
– Example : int a = 100000L, int b = -200000L

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Primitive Data Types
• float: Float data type is a single-precision 32-bit IEEE 754
floating point.
– Float is mainly used to save memory in large arrays of floating point
numbers.
– Default value is 0.0f.
– Float data type is never used for precise values such as currency.
– Example : float f1 = 234.5f

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Primitive Data Types
• double: double data type is a double-precision 64-bit IEEE
754 floating point.
– This data type is generally used as the default data type for decimal
values. generally the default choice.
– Double data type should never be used for precise values such as
currency.
– Default value is 0.0d.
– Example : double d1 = 123.4

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Primitive Data Types
• boolean: boolean data type represents one bit of
information.
– There are only two possible values : true and false.
– This data type is used for simple flags that track true/false
conditions.
– Default value is false.
– Example : boolean one = true

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Primitive Data Types
• char: char data type is a single 16-bit Unicode character.
– Minimum value is '\u0000' (or 0).
– Maximum value is '\uffff' (or 65,535 inclusive).
– Char data type is used to store any character.
– Example . char letterA ='A'

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Reference Data Types
• Reference variables are created using defined
constructors of the classes. They are used to access
objects. These variables are declared to be of a specific
type that cannot be changed. For example, Employee,
Puppy etc.
• Class objects, and various type of array variables come
under reference data type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of
the declared type or any compatible type.
• Example : Animal animal = new Animal("giraffe");

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Identifiers
• Keywords
– Lexical elements (or identifiers) that have a
special, predefined meaning in the language
– Cannot be redefined or used in any other way
in a program
– Ex: public, private, if, class, throws

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Identifiers
• Other Identifiers
– Defined by programmer
– Java API defines quite a few for us
• e.g. System, Scanner, String, out
– are used to represent names of variables, methods
and classes
– Cannot be keywords
– We could redefine those defined in Java API if we
wanted to, but this is generally not a good idea
– Java IDs must begin with a letter, followed by any
number of letters, digits, _ (underscore) or $
characters
• Similar to identifier rules in most programming langs

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Identifiers
– Important Note:
• Java identifiers are case-sensitive – this means that upper
and lower case letters are considered to be different – be
careful to be consistent!
• Ex: ThisVariable and thisvariable are NOT the same
– Naming Convention:
• Many Java programmers use the following conventions:
– Classes: start with upper case, then start each word with an
upper case letter
– Ex: StringBuffer, BufferedInputStream,
ArrayIndexOutOfBoundsException
– Methods and variables: start with lower case, then start each
word with an upper case letter
– Ex: compareTo, lastIndexOf, mousePressed

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Literals
• Values that are hard-coded into a program
– They are literally in the code!
• Different types have different rules for specifying literal
values
– They are fairly intuitive and similar across most programming
languages
– Integer
• An optional +/- followed by a sequence of digits
• Ex: 1024, -78, 1024786074
– Character
• A single character in single quotes
• Ex: ‘a’, ‘y’, ‘q’
– String
• A sequence of characters contained within double quotes
• Ex: “This is a string literal”
– See p. 75-77 for more literals
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Statements
• Units of declaration or execution
• Every Java statement must be terminated by a semicolon (;)
• Variable declaration statement
<type> <variable>, <variable>, …;
Ex: int var1, var2;
• Assignment statement
<variable> = <expression>;
Ex. var1 = 100;
var2 = 100 + var1;
• Method call
<method ID>(<expression>,<expression>,...);
System.out.println(“Answer is “ + var1);
• We’ll discuss others later

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Variables
• Memory locations that are associated with identifiers
• Values can change throughout the execution of a program
• In Java, must be specified as a certain type or class
– The type of a variable specifies its properties: the data it can
store and the operations that can be performed on it
• Ex: int type: discuss
– Java is fairly strict about enforcing data type values
• You will get a compilation error if you assign an incorrect type to a
variable: Ex: int i = “hello”;

incompatible types found: java.lang.String


required: int
int i = "hello";
^

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Variables
– Note: For numeric types, you even get an error if the value
assigned will “lose precision” if placed into the variable
• Generally speaking this means we can place “smaller” values into
“larger” variables but we cannot place “larger” values into “smaller”
variables
– Ex: byte < short < int < long < float < double
– Ex: int i = 3.5;

possible loss of precision found : double


required: int
int i = 3.5;
^

– Ex: double x = 100;


» This is ok

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Variables
– Floating point literals in Java are by default double
• If you assign one to a float variable, you will get a “loss of
precision error” as shown in the previous slide
– If you want to assign a “more precise” value to a “less precise”
variable, you must explicitly cast the value to that variable type
int i = 5;
int j = 4.5;
float x = 3.5;
Error check each of the float y = (float) 3.5;
statements in the box to double z = 100;
the right
i = z;
y = z;
z = i;
j = (long) y;
WAY TO IT COMPUTER EDUCATION
j = (byte) y;
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Variables
• In Java, variables fall into two categories:
• Primitive Types
– Simple types whose values are stored directly in the memory
location associated with a variable
– Ex: int var1 = 100;

var1 100

– There are 8 primitive types in Java:


byte, short, int, long, float, double, char, boolean
– See Section 2.3 and ex2a.java for more details on the primitive
numeric types

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Variables
• Reference Types (or class types)
– Types whose values are references to objects that are stored
elsewhere in memory
– Ex: String s = new String(“Hello There”);

s
Hello There

– There are many implications to using reference types, and we


must use them with care
– Different objects have different capabilities, based on their
classes
– We will discuss reference types in more detail in Chapter 3 when
we start looking at Objects

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Variables
• In Java, all variables must be declared before they can be used
Ex: x = 5.0;
– This will cause an error unless x has previously been declared
as a double variable
cannot resolve symbol symbol : variable x

location : class classname


x = 5.0;
^
• Java variables can be initialized in the same statement in which
they are declared
– Ex: double x = 5.0;
• Multiple variables of the same type can be declared and initialized
in a single statement, as long as they are separated by commas
– Ex: int i = 10, j = 20, k = 45;

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Operators and Expressions
• Expressions are parts of statements that
– Describe a set of operations to be performed
– Are evaluated at run time
– Ultimately result in a single value, the result of the computation
• Result replaced the expression in the statement
– Ex: Consider the assignment statement : x=1+2+3+4;
• 1+2+3+4 is evaluated to be 10 when the program is run
• X ultimately gets assigned the value 10
• Operators describe the operations that should be done
– Simple numeric operations
– Other more advanced operations (to be discussed later)

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Operators and Expressions
• Numeric operators in Java include
+, –, *, /, %
• These are typical across most languages
• A couple points, however:
– If both operands are integer, / will give integer division, always
producing an integer result – discuss implications
– The % operator was designed for integer operands and gives
the remainder of integer division
– However, % can be used with floating point as well
int i, j, k, m;
i = 16; j = 7;
k = i / j; // answer?
m = i % j; // answer?

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Operators and Expressions
– Precedence and Associativity
• See chart on p. 81 and on p. 678
• Recall that the precedence indicates the order in which
operators are applied
• Recall that the associativity indicates the order in which
operands are accessed given operators of the same
precedence
• General guidelines to remember for arithmetic operators:
*, /, % same precedence, left to right associativity
+, – same (lower) precedence, also L to R
– Ok, let’s do another example
• ex2a.java

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Operators and Expressions
• Java has a number of convenience operators
– Allow us to do operations with less typing
– Ex:
X = X + 1; X++;
Y = Y – 5; Y –= 5;
– See Sections 2.11 and 2.12 for more details
– One point that should be emphasized is the difference
between the prefix and postfix versions of the unary
operators
• What is the difference between the statements:
X++; ++X;

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
References
– What do we mean by “references”?
• The data stored in a variable is just the “address” of the
location where the object is stored
– Thus it is separate from the object itself
» Ex: If I have a Contacts file on my PC, it will have the
address of my friend, Joe Schmoe (stored as Schmoe, J.)
» I can use that address to send something to Joe or to go
visit him if I would like
» However, if I change that address in my Contacts file, it
does NOT in any way affect Joe, but now I no longer know
where Joe is located
• However, I can indirectly change the data in the object
through the reference
– Knowing his address, I can go to Joe’s house and steal his
plasma TV

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Using Objects
• What do we mean by "objects"?
– Let's first discuss classes
• Classes are blueprints for our data
– The class structure provides a good way to encapsulate the data
and operations of a new type together
• Instance data and instance methods
• The data gives us the structure of the objects and the operations
show us how to use them
• Ex: A String

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Using Objects
– User of the class knows the general nature of the data, and the
public methods, but NOT the implementation details
• But does not need to know them in order to use the class
– Ex: BigInteger
– We call this data abstraction
– Java classes determine the structure and behavior of Java
objects
• To put it another way, Java objects are instances of
Java classes

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
More References
• Back to references, let's now see some of the
implications of reference variables
– Declaring a variable does NOT create an object
• We must create objects separately from declaring variables
StringBuffer S1, S2;
– Right now we have no actual StringBuffer objects – just two
variables that could access them
– To get objects we must use the new operator or call a method
that will create an object for us
S1 = new StringBuffer("Hello");
– S1 now references an instance of a StringBuffer object but S2
does not

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
More References
• So what value does S2 have?
– For now we will say that we should not count on it to
have any value – we must initialize it before we use it
– If we try to access it without initializing it, we will get an
error
– Multiple variables can access and alter the same
object
S2 = S1;
• Now any change to S1 or S2 will update the same
object
S1
Hello
S2

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
More References
– Properties of objects (public methods and public
instance variables) are accessed via "dot" notation
S1.append(" there Java maestros!");
• S2 will also access the appended object
– Comparison of reference variables compares the
references, NOT the objects
StringBuffer S3 =
new StringBuffer("Hello there Java maestros!");
if (S1 == S2) System.out.println("Equal"); // yes
if (S1 == S3) System.out.println("Equal"); // no
• What if we want to compare the objects?

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
More References
• We use the equals() method
– This is generally defined for many Java classes to
compare data within objects
– We will see how to define it for our own classes soon
– However, the equals() method is not (re)defined for the
StringBuffer class, so we need to convert our
StringBuffer objects into Strings in order to compare
them:
if (S1.toString().equals(S3.toString()))
System.out.println("Same value"); //
yes
• It seems complicated but it will make more sense
when we get into defining new classes

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
More references
• Note the difference in the tests:
– The == operator shows us that it is the same object
– The equals method show us that the values are in some
way the same (depending on how it is defined)
– References can be set to null to initialize or reinitialize
a variable
• Null references cannot be accessed via the "dot"
notation
• If it is attempted a run-time error results
S1 = null;
S1.append("This will not work!");

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
More references
• Why?
– The method calls are associated with the OBJECT that is
being accessed, NOT with the variable
– If there is no object, there are no methods available to
call
– Result is NullPointerException – common error so
remember it!

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Static Variables

•The static key word is used to create variables that will


exist independently of any instances created for the class.
Only one copy of the static variable exists regardless of the
number of instances of the class.

•Static variables are also known as class variables. Local


variables cannot be declared static.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Static Methods

•The static key word is used to create methods that will


exist independently of any instances created for the class.

•Static methods do not use any instance variables of any


object of the class they are defined in. Static methods take
all the data from parameters and compute something from
those parameters, with no reference to variables.

•Class variables and methods can be accessed using the


class name followed by a dot and the name of the variable
or method.
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
final Variables

•A final variable can be explicitly initialized only once. A


reference variable declared final can never be reassigned
to refer to an different object.

•However the data within the object can be changed. So


the state of the object can be changed but not the
reference.

•With variables, the final modifier often is used with static to


make the constant a class variable.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Final Methods

•A final method cannot be overridden by any subclasses.


As mentioned previously the final modifier prevents a
method from being modified in a subclass.

•The main intention of making a method final would be that


the content of the method should not be changed by any
outsider.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Final Classes

•The main purpose of using a class being declared as final


is to prevent the class from being subclassed. If a class is
marked as final then no class can inherit any feature from
the final class.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Inheritance
Inheritance can be defined as the process where one object acquires the
properties of another. With the use of inheritance the information is made
manageable in a hierarchical order. In Java multiple inheritance is not allowed.
When we talk about inheritance the most commonly used keyword would
be extends and implements. These words would determine whether one
object IS-A type of another. By using these keywords we can make one object
acquire the properties of another object.

IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how
the extends keyword is used to achieve inheritance.
With use of the extends keyword the subclasses will be able to inherit all the
properties of the superclass except for the private properties of the superclass.
Mammal IS-A Animal
Animal is the superclass of Mammal class.
Reptile IS-A Animal
Animal is the superclass of Reptile class.
Mammal and Reptile are sub classes of Animal Dog IS-A Mammal
class. Hence : Dog IS-A Animal as well
Dog is the subclass of both Mammal and Animal
WAY TO IT
classes COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Overriding the Parent Class Method
If a class inherits a method from its super class, then there is a chance
to override the method provided that it is not marked final.

The benefit of overriding is: ability to define a behavior that's specific to


the sub class type. Which means a subclass can implement a parent
calss method based on its requirement

In object oriented terms, overriding means to override the functionality


of any existing method

To a reference variable of type parent class, an object reference of


child class can be stored.

During compilation only the syntax is checked and hence no error will
be reported.

During execution, JVM figures out the object type and would run the
WAY TOthatIT
method belongs to that particular object COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Rules for Overriding the Parent Class Method
•The argument list should be exactly the same as that of the overridden method.
•The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.
•The access level cannot be more restrictive than the overridden method's access level. For
example: if the super class method is declared public then the overridding method in the sub
class cannot be either private or public. However the access level can be less restrictive than
the overridden method's access level.
•Instance methods can be overridden only if they are inherited by the subclass.
•A method declared final cannot be overridden.
•A method declared static cannot be overridden but can be re-declared.
•If a method cannot be inherited then it cannot be overridden.
•A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
•A subclass in a different package can only override the non-final methods declared public or
protected.
•An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should not throw
checked exceptions that are new or broader than the ones declared by the overridden method.
The overriding method can throw narrower or fewer exceptions than the overridden method.
•Constructors cannot be overridden.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Using Super Keyword

When invoking a superclass version of an overridden method


the super keyword is used

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Abstract Classes

An abstract class is one that cannot be instantiated. All other


functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner. You just cannot
create an instance of the abstract class.

If a class is abstract and cannot be instantiated, the class does not


have much use unless it is sub-classed. This is typically how abstract
classes come about during the design phase.

A parent class contains the common functionality of a collection of child


classes, but the parent class itself is too abstract to be used on its own.

Use the abstract keyword to declare a class abstract. The keyword


appears in the class declaration before the class keyword

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Abstract Methods
If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can declare
the method in the parent class as abstract.

The abstract keyword is also used to declare a method as abstract.


An abstract methods consist of a method signature, but no method body.
Abstract method would have no definition, and its signature is followed by a
semicolon, not curly braces

Declaring a method as abstract has two results:


The class must also be declared abstract. If a class contains an abstract method,
the class must be abstract as well.

Any child class must either override the abstract method or declare itself abstract.

A child class that inherits an abstract method must override it. If they do not, they
must be abstract,and any of their children must override it.

Eventually, a descendant class has to implement the abstract method; otherwise,


you would have a hierarchy of abstract classes that cannot be instantiated

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Interfaces
An interface is a collection of abstract methods. A class implements an
interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but


they are two different concepts. A class describes the attributes and behaviors
of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of
the interface need to be defined in the class

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
An interface is similar to a class in the following ways:
•An interface can contain any number of methods.
•An interface is written in a file with a .java extension, with the name of
the interface matching the name of the file.
•The bytecode of an interface appears in a .class file.
•Interfaces appear in packages, and their corresponding bytecode file
must be in a directory structure that matches the package name.
However, an interface is different from a class in several ways,
including:
•The interface keyword is used to declare an interface
•You cannot instantiate an interface.
•An interface does not contain any constructors.
•All of the methods in an interface are abstract.
•An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final.
•An interface is not extended by a class; it is implemented by a class.
•An interface can extend multiple interfaces.
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Interfaces have the following properties:
•An interface is implicitly abstract. You do not need to use
the abstract keyword when declaring an interface.
•Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
•Methods in an interface are implicitly public.

When a class implements an interface, you can think of the class


as signing a contract, agreeing to perform the specific behaviors
of the interface.

If a class does not perform all the behaviors of the interface, the
class must declare itself as abstract.

A class uses the implements keyword to implement an


interface. The implements keyword appears in the class
declaration following the extends portion of the declaration

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Rules for Overriding the Parent Class Method

When overriding methods defined in interfaces there are several rules


to be followed:
•Checked exceptions should not be declared on implementation
methods other than the ones declared by the interface method or
subclasses of those declared by the interface method.
•The signature of the interface method and the same return type or
subtype should be maintained when overriding the methods.
•An implementation class itself can be abstract and if so interface
methods need not be implemented.

When implementation interfaces there are several rules:


•A class can implement more than one interface at a time.
•A class can extend only one class, but implement many interface.
•An interface can extend another interface, similarly to the way that a
class can extend another class.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Extending Interfaces:
An interface can extend another interface, similarly to the way that a
class can extend another class. The extends keyword is used to
extend an interface, and the child interface inherits the methods of the
parent interface.
Extending Multiple Interfaces:
A Java class can only extend one parent class. Multiple inheritance is
not allowed. Interfaces are not classes, however, and an interface can
extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event,
it would be declared as:
public interface Hockey extends Sports, Event

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exceptions &
Exception Handling

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exceptions
•Exception is an exceptional case that can happen in a program

c = a/b;

⁻ There is no error in the above statement

⁻ Still, it is not guaranteed to work in all cases

⁻ This statement will not work, if b is zero

⁻ The value of b becoming zero is an exceptional case and


hence an Exception

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exceptions

•An exception is an event, which occurs during the execution of a


program, that disrupts the normal flow of the program's instructions

•An exception can occur for many different reasons, including the
following:
– A user has entered invalid data.

– A file that needs to be opened cannot be found.

– A network connection has been lost in the middle of


communications, or the JVM has run out of memory.

– Some of these exceptions are caused by user error, others by


programmer error, and others by physical resources that have failed
in some manner

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Handling

•When there is an exception

– Normally the program crashes and prints a system generated error


message

– Not acceptable in a mission critical application

•The programmer can handle the exception, preventing the program


from crashing

•Exception Handler is a set of instructions that handles an exception

•The Java programming language provides a mechanism to help


programs report and handle errors

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Handling

•When an error occurs, the program throws an exception

•The exception object that is thrown contains information about the


exception

•The runtime environment attempts to find the Exception Handler

– The exception handler attempts to recover from the error

– If the error is unrecoverable, provide a gentle exit from the program


after clean up operations like closing open files etc.

•Helpful in separating the execution code from the error handler

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Handling
•The exception in the earlier example can be easily handled by the
following code

if (b == 0)
System.out.println(“Error”);
else
c = a/b;

• Handling an exception may not be this easy in many cases

• In the above example, the same programmer is detecting and


handling the exception and hence could manage with a simple if
statement

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Handling

•Programmer 1 is creating a class List for storing a list of objects

•Programmer 2 is using this library to store a list of Policy objects

•What should the class List do when a wrong index is passed to the
method get(int index)?

– Programmer 2 wants to print an error message “Such a Policy does


not exist”

– The class List cannot do this as it is a generic class for storing any
kind of object

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Handling

•One part of the system can detect the exception but does not know
how to handle it

– The Object get(int index) method of List class

•Another part of the system cannot detect the exception but knows
how to handle it

– The second programmer’s method that is trying to get a Policy


object from the List class

•In such cases, a simple if statement cannot be used to handle


exceptions

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Handling

•An exception occurs when one part of a system is unable to do


what it was asked to do

– All it can do is to throw an exception indicating that something has


gone wrong

•Another part of the program can handle the exception

– It should catch the exception and handle it

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exceptions & Errors

•Exceptions are situations within the control of an application, that it


should try to handle

•Errors indicate serious problems and abnormal conditions that


most applications should not try to handle

– These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer.

– Errors are typically ignored in your code because you can rarely do
anything about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Hierarchy
•All exceptions are represented as objects in Java
– When an exception is to be thrown in a Java program, one of these
objects is thrown
•All exception classes are subtypes of the java.lang.Exception class

Throwable

Error Exception

IOException RuntimeException

ArrayIndexOutOfBoundsExcept ArithmeticExceptio
ion n
NullPointerException

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Run Time Exception
•These are exceptions thrown at runtime

– When a Java program tries to divide by zero, the runtime will create
and throw an object of ArithmeticException

– When a Java program tries to access an element outside the


boundary of an array, the runtime will create and throw an object of
ArrayIndexOutOfBoundsException

– When a Java program tried to use a reference that is not referring


to an object, the runtime will create and throw an object of
NullPointerException

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Types of Exceptions

•Unchecked exceptions: Runtime Exceptions are also known as


Unchecked Exceptions as the compiler will not check whether the
programmer has handled them or not.

•Checked exceptions: All exceptions other than Runtime


Exceptions are also known as Checked Exceptions as the compiler
will check whether the programmer has handled them or else
generates a compilation error.

– For example, if a file is to be opened, but the file cannot be found, an


exception occurs. These exceptions cannot simply be ignored at the
time of compilation.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Throwing an Exception
•When an error occurs within a method, the method creates an
object and hands it off to the runtime system.

•The object, called an exception object, contains information about


the error, including its type and the state of the program when the
error occurred

•Creating an exception object and handing it to the runtime system


is called throwing an exception

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Call Stack
•After a method throws an exception, the runtime system attempts to find
something to handle it.

•The set of possible "somethings" to handle the exception is the ordered


list of methods that had been called to get to the method where the error
occurred.

•The list of methods is known as the call stack

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Exception Handler
•The runtime system searches the call stack for a method that
contains a block of code that can handle the exception

•This block of code is called an exception handler.

•The search begins with the method in which the error occurred and
proceeds through the call stack in the reverse order in which the
methods were called

•When an appropriate handler is found, the runtime system passes


the exception to the handler

•An exception handler is considered appropriate if the type of the


exception object thrown matches the type that can be handled by
the handler

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Catching the Exception
•The exception handler chosen is said to catch the exception

•If the runtime system exhaustively searches all the methods on the
call stack without finding an appropriate exception handler, as
shown in the next figure, the runtime system (and, consequently, the
program) terminates

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Catching the Exception
•A method catches an exception using a combination of the try and
catch keywords

•A try/catch block is placed around the code that might generate an


exception. Code within a try/catch block is referred to as protected
code

•A catch statement involves declaring the type of exception you are


trying to catch

•If an exception occurs in protected code, the catch block (or


blocks) that follows the try is checked

•If the type of exception that occurred is listed in a catch block, the
exception is passed to the catch block much as an argument is
passed into a method parameter
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Catching the Exception
A try block can be followed by more
try
than one catch blocks
{
//Protected code
try
} catch(ExceptionName e1)
{
{ //Protected code
//Catch block }catch(ExceptionType1 e1)
} {
//Catch block
try{ }catch(ExceptionType2 e2)
{
c = a/b;
//Catch block
} }catch(ExceptionType3 e3)
catch(ArithmeticException e){ {
System.out.println(“Divide By //Catch block
Zero”); }
WAY } TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
throws/throw keyword
•If a method does not handle a checked exception, the method must
declare it using the throws keyword

•The throws keyword appears at the end of a method's signature.

•You can throw an exception, either a newly instantiated one or an


exception that you just caught, by using the throw keyword.

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
throws/throw keyword - Example
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

•A method can declare that it throws more than one exception, in which
case the exceptions are declared in a list separated by commas

public void withdraw(double amount) throws RemoteException,


InsufficientFundsException
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
finally keyword
•The finally keyword is used to create a block of code that follows a try
block. A finally block of code always executes, whether or not an
exception has occurred.

•Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.

•A finally block appears at the end of the catch blocks

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
finally keyword
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Important Points on try & catch
•A catch clause cannot exist without a try statement.

•It is not compulsory to have finally clauses when ever a


try/catch block is present.

•The try block cannot be present without either catch clause or


finally clause.

•Any code cannot be present in between the try, catch, finally


blocks

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Declaring Your Own Exception
•All exceptions must be a child of Throwable.

•If you want to write a checked exception that is automatically


enforced by the Handle or Declare Rule, you need to extend the
Exception class.

•If you want to write a runtime exception, you need to extend


the RuntimeException class

•You just need to extend the Exception class to create your own
Exception class. These are considered to be checked
exceptions.

class MyException extends Exception{


}

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Multithreading

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Multitasking
•Multitasking allows to execute more than one tasks at the same
time, a task being a program

•In multitasking one CPU switches from one program to another


program so quickly that's why it gives the appearance of executing
all of the programs at the same time

•Multitasking allow processes (i.e. programs) to run concurrently on


the program

•For Example while using the spreadsheet program, you are


working with word processor also

•Multitasking is running heavyweight processes by a single OS

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Multithreading
•Multithreading is a technique that allows a program or a process to
execute many tasks concurrently (at the same time and parallel)

•Multithreading allows a process to run its tasks in parallel mode on a


single processor system 

•In the multithreading concept, several multiple lightweight


processes are run in a single process/task or program by a single
processor.

•For Example, When you use a word processor you perform a


many different tasks such as printing, spell checking and so on

•Multithreaded software treats each process as a separate program

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Multithreading
•In Java, the Java Virtual Machine (JVM) allows an application to have multiple
threads of execution running concurrently
•A multithreaded program contains two or more parts that can run concurrently.
Each part of such a program is called a thread, and each thread defines a
separate path of execution
•It allows a program to be more responsive to the user
•When a program contains multiple threads then the CPU can switch between
the two threads to execute them at the
• A same time
process consists of the memory space
allocated by the operating system that
can contain one or more threads
• A thread cannot exist on its own; it must
be a part of a process
• A process remains running until all of the
threads are done executing
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Creating a Thread
1.By implementing Runnable interface
₋ The class must override the run() method

public class Test implements Runnable {


public void run(){
....
}
}

₋ Must instantiate the Thread class and call start() method

2.By extending Thread class


₋ The class must override the run() method

₋ Must also call start( ) using the instance of the sub class, to begin
WAY TO IT execution of the new thread COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Creating a Thread
•Step 1: Define a class to implement the Runnable Interface

•Step 2: Define a class member of type Thread

•Step 3: In the constructor of this class, instantiate Thread class

•Step 4: Invoke the start() method

•Step 5: Override run() method (This methods is invoked


automatically when start() method is invoked)

•Step 6: In the main class, instantiate the above class and invoke
the default constructor

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Thread Priorities
•Every Java thread has a priority that helps the operating system
determine the order in which threads are scheduled.

•Java priorities are in the range between MIN_PRIORITY (a


constant of 1) and MAX_PRIORITY (a constant of 10)

•By default, every thread is given priority NORM_PRIORITY (a


constant of 5).

•Threads with higher priority are more important to a program and


should be allocated processor time before lower priority threads

•However, thread priorities cannot guarantee the order in which


threads execute and very much platform dependent

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Life Cycle of a Thread

NEWBORN
DEAD
start()
run() returns or
thread interrupted

notify(), notifyAll()
WAITING RUNNABLE
Sleep interval
expires
yield() or end of scheduled
time slice
SLEEPING sleep() wait()

I/O completion RUNNING


BLOCKED
I/O request

NON-RUNNABLE
ALIVE

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Thread Interference
•Interference happens when two operations, running in different threads, but
acting on the same data, interleave

•This means that the two operations consist of multiple steps, and the sequences
of steps overlap

•Consider the below piece of code


• Counter is designed so that each invocation of
class Counter { increment will add 1 to c, and each invocation of
private int c = 0; decrement will subtract 1 from c
public void increment() {
c++; • However, if a Counter object is referenced from
} multiple threads, interference between threads
public void decrement() { may prevent this from happening as expected
c--;
} • It might not seem possible for operations on
public int value() { instances of Counter to interleave, since both
return c;
operations on c are single, simple statements
WAY TO IT
} COMPUTER EDUCATION
} DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Thread Interference
• The single expression c++ can be decomposed into three steps:
1. Retrieve the current value of c.
2. Increment the retrieved value by 1.
3. Store the incremented value back in c
• Similarly c- - can be decomposed
• Suppose Thread A invokes increment at about the same time Thread B
invokes decrement
• If the initial value of c is 0, their interleaved actions might follow this
sequence:
1. Thread A: Retrieve c.
2. Thread B: Retrieve c.
3. Thread A: Increment retrieved value; result is 1.
4. Thread B: Decrement retrieved value; result is -1.
5. Thread A: Store result in c; c is now 1.

WAY TO 6.IT
Thread B: Store result in c; c is now -1. COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Synchronization
•When two or more threads need access to a shared resource,
they need some way to ensure that the resource will be used by
only one thread at a time

•The process by which this is achieved is called synchronization

•A synchronized block ensures that a call to a method that is a


member of object occurs only after the current thread has
successfully entered object's monitor

•In Java, there are two types of synchronization

• Synchronized Methods

• Synchronized Statements
WAY TO IT COMPUTER EDUCATION
DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Synchronized Methods

•To make a method synchronized, simply add the synchronized


keyword to its declaration

•If an object is visible to more than one thread, all reads or writes to
that object's variables are done through synchronized methods

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Synchronized Methods
public class SynchronizedCounter { • It is not possible for two invocations of
private int c = 0;
synchronized methods on the same object to
public synchronized void interleave
increment() {
c++; • When one thread is executing a synchronized
}
method for an object, all other threads that
public synchronized void invoke synchronized methods for the same
decrement() { object block (suspend execution) until the first
c--;
} thread is done with the object

public synchronized int value() { • when a synchronized method exits, it


return c; automatically establishes a happens-before
}
• constructors cannot be
} relationship with any subsequent invocation
synchronized. of a synchronized method for the same object
• using the synchronized keyword with
a constructor is a syntax error • This guarantees that changes to the state of
the object are visible to all threads
• Synchronizing constructors doesn't make sense, because only the thread that creates
an object should have access to it while it is being constructed

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Synchronized Statement

•Unlike synchronized methods, synchronized statements must


specify the object that provides the lock

•The synchronized keyword in Java creates a block of code referred


to as a critical section

•Every Java object with a critical section of code gets a lock


associated with the object

•To enter a critical section, a thread needs to obtain the


corresponding object's lock

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE
Synchronized Statement

General form of the synchronized • Here, object is a reference to


statement the object being synchronized
synchronized(object) {
// statements to be synchronized • A synchronized block ensures
that a call to a method that is a
}
member of object occurs only
public void addName(String name) { after the current thread has
synchronized(this) { lastName = name; successfully entered object's
nameCount++; } monitor
nameList.add(name);
}

WAY TO IT COMPUTER EDUCATION


DON’T JUST LEARN, BECOME AN EXPERT AND LEAPFROG IN LIFE

You might also like