SlideShare a Scribd company logo
1 of 153
1. Java
2. Spring MVC
3. Spring Boot
Name-Aayush Chimaniya
Roll-0863CS213D01
Class-C.S.E(5th sem)
College-P.I.E.M.R.
Java
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 to create modular programs and reusable
code.
Powerful Features
• Java has the following features
– Object Oriented
– Simplicity
– Robustness
– Platform Independence (Portable)
– Security
– Distributed Applications
– Multithreading
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
• 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
– Means the ability of methods to exist in several different
forms
Object Oriented Programming
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.
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.
Java is Secure
• Provides a virtual firewall between the
application and the computer.
• Java codes are confined within Java
Runtime Environment (JRE).
Java is Distributed
• Java is designed for the distributed
environment of the internet.
• Objects on one JVM can execute
procedures on a remote JVM.
Multithreading
• Enables a program to perform several
tasks simultaneously.
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.
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.
• The JVM must be implemented on a particular platform
before compiled programs can run on that platform.
Installing and Using Java
• First install Java 2 JDK version 7
• This can be downloaded from the official
website of Java
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
Setting the CLASSPATH
• Windows:
– Set CLASSPATH=%CLASSPATH%;%JAVA_HOME%libtools.jar;
• UNIX:
– Set CLASSPATH=$CLASSPATH:$JAVA_HOME/lib/tools.jar;
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
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
• 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
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.
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.
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
Data Types
There are two data types available in Java:
• Primitive Data Types
• Reference/Object Data Types
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
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
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
• 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
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
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
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
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'
Primitive Data Types
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");
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
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
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
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
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
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";
^
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
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;
float y = (float) 3.5;
double z = 100;
i = z;
y = z;
z = i;
j = (long) y;
j = (byte) y;
Error check each of the
statements in the box to
the right
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;
– 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
var1 100
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”);
– 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
s
Hello There
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
• 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;
cannot resolve symbol symbol : variable x
location : class classname
x = 5.0;
^
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)
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?
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
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;
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
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
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
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
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
S2
Hello
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?
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
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!");
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!
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.
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.
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.
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.
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.
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
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are sub classes of Animal
class.
Dog is the subclass of both Mammal and Animal
classes
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
method that belongs to that particular object
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.
Using Super Keyword
When invoking a superclass version of an overridden method
the super keyword is used
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
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
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
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.
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
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.
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
Exceptions &
Exception Handling
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
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
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
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
Exception Handling
• The exception in the earlier example can be easily handled by
the following code
• 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
if (b == 0)
System.out.println(“Error”);
else
c = a/b;
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
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
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
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
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
RuntimeException
ArrayIndexOutOfBoundsExcept
ion
NullPointerException
ArithmeticExceptio
n
IOException
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
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.
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
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
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
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
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
try
{
//Protected code
} catch(ExceptionName e1)
{
//Catch block
}
A try block can be followed by more
than one catch blocks
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
Catching the Exception
try{
c = a/b;
}
catch(ArithmeticException e){
System.out.println(“Divide By
Zero”);
}
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.
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
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
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.
}
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
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{
}
Multithreading
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
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
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 same time
• A 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
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
execution of the new thread
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
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
Life Cycle of a Thread
WAITING
SLEEPING
BLOCKED
ALIVE
RUNNABLE
RUNNING
NEWBORN
DEAD
start()
yield() or end of
time slice
scheduled
notify(), notifyAll()
wait()
sleep()
Sleep interval
expires
I/O request
I/O completion
run() returns or
thread interrupted
NON-RUNNABLE
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
class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
• Counter is designed so that each invocation of
increment will add 1 to c, and each invocation of
decrement will subtract 1 from c
• However, if a Counter object is referenced from
multiple threads, interference between threads
may prevent this from happening as expected
• It might not seem possible for operations on
instances of Counter to interleave, since both
operations on c are single, simple statements
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.
6. Thread B: Store result in c; c is now -1.
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
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
Synchronized Methods
public class SynchronizedCounter {
private int c = 0;
public synchronized void
increment() {
c++;
}
public synchronized void
decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
• It is not possible for two invocations of
synchronized methods on the same object to
interleave
• When one thread is executing a synchronized
method for an object, all other threads that
invoke synchronized methods for the same
object block (suspend execution) until the first
thread is done with the object
• when a synchronized method exits, it
automatically establishes a happens-before
relationship with any subsequent invocation
of a synchronized method for the same
object
• This guarantees that changes to the state of
the object are visible to all threads
• constructors cannot be
synchronized.
• using the synchronized keyword with
a constructor is a syntax error
• Synchronizing constructors doesn't make sense, because only the thread that creates
an object should have access to it while it is being constructed
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
Synchronized Statement
General form of the synchronized
statement
synchronized(object) {
// statements to be synchronized
}
• Here, object is a reference to
the object being synchronized
• 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
public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++; }
nameList.add(name);
}
Spring MVC
Spring Boot
Thank You
Aayush Chimaniya
0863CS213D01

More Related Content

Similar to Java SpringMVC SpringBOOT (Divergent).ppt

Similar to Java SpringMVC SpringBOOT (Divergent).ppt (20)

Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
 
ppt_on_java.pptx
ppt_on_java.pptxppt_on_java.pptx
ppt_on_java.pptx
 
Java platform
Java platformJava platform
Java platform
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Unit 1
Unit 1Unit 1
Unit 1
 
Java Programming concept
Java Programming concept Java Programming concept
Java Programming concept
 
Letest
LetestLetest
Letest
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
 
Core java
Core java Core java
Core java
 
Core java &collections
Core java &collectionsCore java &collections
Core java &collections
 
Core java1
Core java1Core java1
Core java1
 
Skillwise Elementary Java Programming
Skillwise Elementary Java ProgrammingSkillwise Elementary Java Programming
Skillwise Elementary Java Programming
 
java slides
java slidesjava slides
java slides
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.ppt
 
JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentation
 

More from Aayush Chimaniya

More from Aayush Chimaniya (6)

Jasper Reports.pptx
Jasper Reports.pptxJasper Reports.pptx
Jasper Reports.pptx
 
Microservices Api Gateway Eureka Server.pptx
Microservices Api Gateway Eureka Server.pptxMicroservices Api Gateway Eureka Server.pptx
Microservices Api Gateway Eureka Server.pptx
 
MongoDB.pptx
MongoDB.pptxMongoDB.pptx
MongoDB.pptx
 
Asynchronous Programming.pptx
Asynchronous Programming.pptxAsynchronous Programming.pptx
Asynchronous Programming.pptx
 
SADBlood Bank.pdf
SADBlood Bank.pdfSADBlood Bank.pdf
SADBlood Bank.pdf
 
Electric Vehicle
Electric VehicleElectric Vehicle
Electric Vehicle
 

Recently uploaded

Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 

Recently uploaded (20)

Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 

Java SpringMVC SpringBOOT (Divergent).ppt

  • 1. 1. Java 2. Spring MVC 3. Spring Boot Name-Aayush Chimaniya Roll-0863CS213D01 Class-C.S.E(5th sem) College-P.I.E.M.R.
  • 3. 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 to create modular programs and reusable code.
  • 4. Powerful Features • Java has the following features – Object Oriented – Simplicity – Robustness – Platform Independence (Portable) – Security – Distributed Applications – Multithreading
  • 5. 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
  • 6. • 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 – Means the ability of methods to exist in several different forms Object Oriented Programming
  • 7. 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.
  • 8. 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.
  • 9. Java is Secure • Provides a virtual firewall between the application and the computer. • Java codes are confined within Java Runtime Environment (JRE).
  • 10. Java is Distributed • Java is designed for the distributed environment of the internet. • Objects on one JVM can execute procedures on a remote JVM.
  • 11. Multithreading • Enables a program to perform several tasks simultaneously.
  • 12. 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.
  • 13. 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. • The JVM must be implemented on a particular platform before compiled programs can run on that platform.
  • 14. Installing and Using Java • First install Java 2 JDK version 7 • This can be downloaded from the official website of Java
  • 15. 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
  • 16. Setting the CLASSPATH • Windows: – Set CLASSPATH=%CLASSPATH%;%JAVA_HOME%libtools.jar; • UNIX: – Set CLASSPATH=$CLASSPATH:$JAVA_HOME/lib/tools.jar;
  • 17. 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
  • 18. 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
  • 19. • 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
  • 20. 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.
  • 21. 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.
  • 22. 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
  • 23. Data Types There are two data types available in Java: • Primitive Data Types • Reference/Object Data Types
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. • 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 Primitive Data Types
  • 28. • 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 Primitive Data Types
  • 29. • 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 Primitive Data Types
  • 30. • 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 Primitive Data Types
  • 31. • 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' Primitive Data Types
  • 32. 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");
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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"; ^
  • 39. 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
  • 40. 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; float y = (float) 3.5; double z = 100; i = z; y = z; z = i; j = (long) y; j = (byte) y; Error check each of the statements in the box to the right
  • 41. 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; – 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 var1 100
  • 42. 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”); – 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 s Hello There
  • 43. 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 • 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; cannot resolve symbol symbol : variable x location : class classname x = 5.0; ^
  • 44. 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)
  • 45. 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?
  • 46. 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
  • 47. 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;
  • 48. 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
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. 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 S2 Hello
  • 53. 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?
  • 54. 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
  • 55. 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!");
  • 56. 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!
  • 57. 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.
  • 58. 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.
  • 59. 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.
  • 60. 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.
  • 61. 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.
  • 62. 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 Reptile IS-A Animal Dog IS-A Mammal Hence : Dog IS-A Animal as well Animal is the superclass of Mammal class. Animal is the superclass of Reptile class. Mammal and Reptile are sub classes of Animal class. Dog is the subclass of both Mammal and Animal classes
  • 63. 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 method that belongs to that particular object
  • 64. 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.
  • 65. Using Super Keyword When invoking a superclass version of an overridden method the super keyword is used
  • 66. 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
  • 67. 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
  • 68. 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
  • 69. 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.
  • 70. 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
  • 71. 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.
  • 72. 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
  • 74. 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
  • 75. 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
  • 76. 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
  • 77. 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
  • 78. Exception Handling • The exception in the earlier example can be easily handled by the following code • 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 if (b == 0) System.out.println(“Error”); else c = a/b;
  • 79. 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
  • 80. 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
  • 81. 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
  • 82. 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
  • 83. 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 RuntimeException ArrayIndexOutOfBoundsExcept ion NullPointerException ArithmeticExceptio n IOException
  • 84. 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
  • 85. 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.
  • 86. 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
  • 87. 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
  • 88. 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
  • 89. 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
  • 90. 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
  • 91. try { //Protected code } catch(ExceptionName e1) { //Catch block } A try block can be followed by more than one catch blocks try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } Catching the Exception try{ c = a/b; } catch(ArithmeticException e){ System.out.println(“Divide By Zero”); }
  • 92. 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.
  • 93. 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
  • 94. 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
  • 95. 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. }
  • 96. 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
  • 97. 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{ }
  • 99. 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
  • 100. 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
  • 101. 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 same time • A 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
  • 102. 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 execution of the new thread
  • 103. 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
  • 104. 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
  • 105. Life Cycle of a Thread WAITING SLEEPING BLOCKED ALIVE RUNNABLE RUNNING NEWBORN DEAD start() yield() or end of time slice scheduled notify(), notifyAll() wait() sleep() Sleep interval expires I/O request I/O completion run() returns or thread interrupted NON-RUNNABLE
  • 106. 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 class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; } } • Counter is designed so that each invocation of increment will add 1 to c, and each invocation of decrement will subtract 1 from c • However, if a Counter object is referenced from multiple threads, interference between threads may prevent this from happening as expected • It might not seem possible for operations on instances of Counter to interleave, since both operations on c are single, simple statements
  • 107. 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. 6. Thread B: Store result in c; c is now -1.
  • 108. 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
  • 109. 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
  • 110. Synchronized Methods public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } } • It is not possible for two invocations of synchronized methods on the same object to interleave • When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object • when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object • This guarantees that changes to the state of the object are visible to all threads • constructors cannot be synchronized. • using the synchronized keyword with a constructor is a syntax error • Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed
  • 111. 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
  • 112. Synchronized Statement General form of the synchronized statement synchronized(object) { // statements to be synchronized } • Here, object is a reference to the object being synchronized • 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 public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); }
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.