Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 170

PROGRAMMING WITH

JAVA
Mr Nkurunziza Gasore
(BSCEIT,MSCIT)
TEL 0788284723
EMAIL:gnkurunziza@uok.ac.rw
History of java
Java was created at Sun Microsystems, Inc.,
where James Gosling led a team of researchers
in an effort to create a new language that
would allow consumer electronic devices to
communicate with each other. Work on the
language began in 1991, and before long the
team's focus changed to a new niche, the World
Wide Web.
What is Java?

• Java is a popular programming language,


created in 1995.
• It is owned by Oracle, and more than 3
billion devices run Java.
• It is used for:
• Mobile applications (specially Android
apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
• And much, much more!
Why Use Java?
• Java works on different platforms
(Windows, Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming
language in the world
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of
millions of developers)
• Java is an object oriented language which
gives a clear structure to programs and
allows code to be reused, lowering
development costs
• As Java is close to C++ and C#, it makes it
easy for programmers to switch to Java or
vice versa
Java Syntax
public class Main
{
public static void main(String[] args)
{
System.out.println("Hello World");
}}
Java Variables

Variables are containers for storing data values.


In Java, there are different types of variables, for example:
•String - stores text, such as "Hello". String values are surrounded
by double quotes
•int - stores integers (whole numbers), without decimals, such as 123
or -123
•float - stores floating point numbers, with decimals, such as 19.99
or -19.99
•char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
•boolean - stores values with two states: true or false
Java Data Types

int myNum = 5; // Integer (whole number) float


myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Java features
OOPS(OBJECT ORIENTED
PROGRAMMING)
INTRODUCTION

• OOP stands for Object-Oriented Programming.


• Procedural programming is about writing procedures or
methods that perform operations on the data, while object-
oriented programming is about creating objects that contain
both data and methods.
• Object-oriented programming has several advantages over
procedural programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP makes it possible to create full reusable applications
with less code and shorter development time
Classes and Objects
• Classes and objects are the two main aspects
of object-oriented programming.
• Look at the following illustration to see the
difference between class and objects:
Multiple Objects
Java Class Attributes
In the previous chapter, we used the term "variable" for
x in the example (as shown below).
It is actually an attribute of the class. Or you could say
that class attributes are variables within a class:
Accessing Attributes
You can access attributes by creating an object of the class,
and by using the dot syntax (.):
The following example will create an object of the
Main class, with the name myObj.
We use the x attribute on the object to print its value:
Modify Attributes
Multiple Attributes
Java Class Methods
Static vs. Non-Static
You will often see Java programs that have either static
or public attributes and methods.
In the example above, we created
a static method, which means that
it can be accessed without creating an object of the class,
unlike public, which can only be accessed by objects:
Example
Access Methods With an Object
Example
Create a Car object named myCar. Call the fullThrottle() and
speed() methods on the myCar object, and run the program:
Example
Java Constructors

• A constructor in Java is a special method


that is used to initialize objects. The
constructor is called when an object of a
class is created. It can be used to set initial
values for object attributes:
Example
Constructor Parameters
Constructors can also take parameters,
which is used to initialize attributes.
The following example adds an
int y parameter to the constructor.
Inside the constructor we set x to y (x=y).
When we call the constructor,
we pass a parameter to the constructor (5),
which will set the value of x to 5:
Constructor Parameters
Example
EXAMPLE TWO
Java Modifiers
Access Modifiers
Final
Static
A static method means that it can be accessed without
creating an object of the class, unlike public:
Abstract
An abstract method belongs to an abstract class,
and it does not have a body.
The body is provided by the subclass:
Example explained
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns
it to the name variable. The this keyword is used
to refer to the current object.
However, as the name variable is declared as private,
we cannot access it from outside this class:
Java Packages
• A package in Java is used to group related
classes. Think of it as a folder in a file
directory. We use packages to avoid name
conflicts, and to write a better maintainable
code. Packages are divided into two
categories:
• Built-in Packages (packages from the Java
API)
• User-defined Packages (create your own
packages)
Java Inheritance (Subclass and
Superclass)
In Java, it is possible to inherit attributes
and methods from one class to another.
We group the "inheritance concept" into two categories:
•subclass (child) - the class that inherits from another class
•superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits
the attributes and methods from the Vehicle class
(superclass):
Inheritance in Java and types
of Inheritance in Java
• When a class is declared, with its
specification, and the other sub-class members
will want to use its member methods
(functions); that’s when they will go for
inheritance concepts. Inheritance in Java is a
process of acquiring all the behaviours of a
parent object.
What is Inheritance in Java?
• Inheritance in Java Definition:
• Inheritance in Java is a concept that
acquires the properties from one class to
other classes; for example, the relationship
between father and son. 
• In Java, a class can inherit attributes and
methods from another class. The class that
inherits the properties is known as the sub-
class or the child class.
• The class from which the properties are
inherited is known as the superclass or the
parent class.
• In Inheritance, the properties of the base
class are acquired by the derived classes.
Why use Inheritance in Java?

• The main advantage of inheritance is code


reusability and also method overriding
(runtime polymorphism). 
• Inheritance is also known as the IS-A
relationship. 
Terms Used in Inheritance 

• Class: ​A class is a collection of objects


which have common properties. 
• Derived Class/Sub-class: ​Derived class is a
class that inherits from a base class. It is also
known as subclass or child class. 
• Base Class/Superclass: ​The base class is the
main class where derived classes inherit the
features. It is also known as the superclass or
parent class. 
• Reusability: ​The name itself says reuse the
repeated code in the programs. It is a
mechanism to reuse existing code when you
are creating new classes. 
• It’s impossible to write java programs without
using inheritance. Enhancing your Java skills
by taking up a certificate course will help you
power ahead in your career. This
java programming free certificate course
covers the fundamentals of the subject,
including Arrays and Functions, and can help
gain great clarity and build a strong
foundation.
Types of Inheritance in Java

• The different types of Inheritance are:


• Single Inheritance
• Multiple Inheritance
• Multi-Level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance
• Creating subclasses from a single base class
is called single inheritance. 
2) Multiple Inheritance

• “Multiple Inheritance” refers to the


concept of one class extending (Or inherits)
more than one base class. The inheritance
we learnt earlier had the concept of one
base class or parent. The problem with
“multiple inheritance” is that the derived
class will have to manage the dependency
on two base classes.
• Note 1: Multiple Inheritance is very rarely
used in software projects. Using Multiple
inheritance often leads to problems in the
hierarchy. This results in unwanted
complexity when further extending the
class.
• Note 2: Most of the new OO languages like
Small Talk, Java, C# do not support
Multiple inheritance. Multiple Inheritance
is supported in C++.
3) Multilevel Inheritance
• Multilevel inheritance refers to a
mechanism in OO technology where one
can inherit from a derived class, thereby
making this derived class the base class for
the new class. As you can see in below
flow diagram C is subclass or child class of
B and B is a child class of A. For more
details and example refer –
Multilevel inheritance in Java.
Hybrid Inheritance in Java
• Hybrid Inheritance in Java is a combination
of Inheritances. In this type of Inheritance,
more than one kind of inheritance is
observed. For example, if we have class A
and class B that extend class C and then
there is another class D that extends class
A, then this type of Inheritance is known as
Hybrid Inheritance.
• Why? Because we clearly observe that there
is two kinds of inheritance here-
Hierarchical and Single Inheritance.
• In the diagram shown below, we see
another example of Hybrid Inheritance.
Why multiple inheritance is not
supported in java?
• Java does not support multiple inheritances
because it leads to the complexity of the
language.
• Inheritance Program in Java
• If we want to call methods and variables
using the Parent class object, you will get
an error. 
Rules for Method overriding
are:
• Methods must share the same name in child
and parent class.
• It must have the same parameter as in the
superclass.
• There must be an IS-A type of Inheritance.
• IS-A Relationship in java
• A combination of two or more classes in
java is known as a relationship.
• In Java, we have two types of relationship:
• Is-A relationship
• Has-A relationship
• Is-A relationship 
• IS-A Relationship is completed related to
inheritance. For example – a carrot is a
vegetable; a fan is a device.
• This relationship can be achieved by:
• Usingextend Keyword
• To avoid code redundancy.
• Super keyword in Java
• Super keyword usage in inheritance, always
refers to its immediate as an object. 
• There are three usages of super keyword in
Java: 
• 1. We can invoke the superclass variables. 
• 2. We can invoke the superclass methods. 
• 3. We can invoke the superclass
constructor. 
Polymorphism in Java
• Polymorphism in Java is the ability of an
object to take many forms. To put it simply,
polymorphism in Java allows us to perform the
same action in many different ways. Any Java
object that can pass more than one IS-A test is
polymorphic in Java. Therefore, all the Java
objects are polymorphic as it has passed the IS-
A test for their own type and for the class
Object. There are two types of polymorphism in
Java: compile-time polymorphism and runtime
polymorphism.
• This article also talks about two types of
polymorphism in Java: compile-time
polymorphism and runtime polymorphism,
Java polymorphism examples, method
overloading, method overriding, why to use
polymorphism in Java, and many more.
• Polymorphism is a feature of the object-
oriented programming language, Java,
which implies that you can perform a
single task in different ways. In the
technical world, polymorphism in Java
allows one to do multiple implementations
by defining one interface. 
Polymorphism in Java
Example
• A superclass named “Shapes” has a method
“area()”. Subclasses of “Shapes” can be
“Triangle”, “circle”, “Rectangle”, etc. Each
subclass has its way of calculating area.
Using Inheritance and Polymorphism
means, the subclasses can use the “area()”
method to find the area’s formula for that
shape.
• Output:
• The formula for the area of Triangle is ½ *
base * height
The formula for the area of the Circle is 3.14
* radius * radius
• Types of Polymorphism
• You can perform Polymorphism in Java via two
different methods:
• Method Overloading
• Method Overriding
• What is Method Overloading in Java?
• Method overloading is the process that can create
multiple methods of the same name in the same
class, and all the methods work in different ways.
Method overloading occurs when there is more than
one method of the same name in the class.
Output:
Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12
• What is Method Overriding in Java?
• Method overriding is the process when the
subclass or a child class has the same method as
declared in the parent class.
• Also, Polymorphism in Java can be
classified into two types, i.e:
• Static/Compile-Time Polymorphism
• Dynamic/Runtime Polymorphism
What is Compile-Time Polymorphism in
Java?
• Compile-Time Polymorphism in Java is
also known as Static
Polymorphism. Furthermore, the call to
the method is resolved at compile-time.
Compile-Time polymorphism is achieved
through Method Overloading. This type
of polymorphism can also be achieved
through Operator Overloading. However,
Java does not support Operator
Overloading.
• Method Overloading is when a class has multiple
methods with the same name, but the number,
types, and order of parameters and the return
type of the methods are different. Java allows the
user freedom to use the same name for various
functions as long as it can distinguish between
them by the type and number of parameters. 
• Example of Compile- Time Polymorphism in
Java
• We will do addition in Java and understand the
concept of compile-time polymorphism using
subtract() 
• The output of the program will be: 
• Sum of two numbers: 120 
• Sum of three numbers: 147 
• In this program, the sum() method overloads
with two types via different parameters. 
• This is the basic concept of compile-time
polymorphism in java where we can perform
various operations by using multiple
methods having the same name.
• What is Runtime Polymorphism in Java?
• Runtime polymorphism in Java is also
popularly known as Dynamic Binding or
Dynamic Method Dispatch. In this
process, the call to an overridden method is
resolved dynamically at runtime rather than
at compile-time. You can achieve Runtime
polymorphism via Method Overriding.
• Method Overriding is done when a child or a
subclass has a method with the same name,
parameters, and return type as the parent or the
superclass; then that function overrides the
function in the superclass. In simpler terms, if
the subclass provides its definition to a method
already present in the superclass; then that
function in the base class is said to be
overridden.
• Also, it should be noted that runtime
polymorphism can only be achieved through
functions and not data members. 
• Overriding is done by using a reference
variable of the superclass. The method to be
called is determined based on the object
which is being referred to by the reference
variable. This is also known as Upcasting.
• Upcasting takes place when the Parent
class’s reference variable refers to the object
of the child class. For example:
• Output:
• Animals eat
Herbivores Eat Plants
Omnivores Eat Plants and meat
Carnivores eat meat
• Example 2:
• In this example, we are creating one
superclass Hillstations and three subclasses
Manali, Mussoorie, Gulmarg. Subclasses
extend the superclass and override its
location() and famousfor() method. We will
call the location() and famousfor() method
by the Parent class’, i.e. Hillstations class.
• As it refers to the base class object and the
base class method overrides the superclass
method; the base class method is invoked at
runtime. Also, as Java Virtual Machine or
the JVM and not the compiler determines
method invocation, it is runtime
polymorphism.
Example of run-time polymorphism in java

• We will create two classes Car and Innova,


Innova class will extend the car class and
will override its run() method.
• The output of the following program will
be; 
• Running fast at 120 km. 
• Another example for run-time
polymorphism in Java
• Now, let us check if we can achieve runtime
polymorphism via data members. 
https://
www.mygreatlearning.com/
blog/polymorphism-in-java/
Polymorphic Subtypes

• Subtype basically means that a subtype can


serve as another type’s subtype, sounds a bit
complicated? 
• Let’s understand this with the help of an
example:
• Assuming we have to draw some arbitrary
shapes, we can introduce a class named
‘shape’ with a draw() method.
• By overriding draw() with other subclasses
such as circle, square, rectangle, trapezium, etc
we will introduce an array of type ‘shape’
whose elements store references will refer to
‘shape’ subclass references. Next time, we will
call draw(), all shapes instances draw ()
method will be called.
• This Subtype polymorphism generally relies
on upcasting and late binding. A casting where
you cast up the inheritance hierarchy from
subtype to a supertype is termed upcasting.
• To call non-final instance methods we use
late binding. In short, a compiler should
not perform any argument checks, type
checks, method calls, etc, and leave
everything on the runtime. 
• What is Polymorphism in
Programming?
• Polymorphism in programming is defined
usage of a single symbol to represent
multiple different types.
• What is Polymorphism Variables?
• A polymorphic variable is defined as a
variable that can hold values of different
types during the course of execution.
• Why use Polymorphism in Java?
• Polymorphism in Java makes it possible to
write a method that can correctly process
lots of different types of functionalities that
have the same name. We can also gain
consistency in our code by using
polymorphism.
• Advantages of Polymorphism in Java
• It provides reusability to the code. The
classes that are written, tested and
implemented can be reused multiple times.
Furthermore, it saves a lot of time for the
coder. Also, the one can change the code
without affecting the original code.
• A single variable can be used to store
multiple data values. The value of a variable
you inherit from the superclass into the
subclass can be changed without changing
that variable’s value in the superclass; or
any other subclasses.
• With lesser lines of code, it becomes easier
for the programmer to debug the code.
Characteristics of Polymorphism
• Polymorphism has many other
characteristics other than Method
Overloading and Method Overriding. They
include:
• Coercion
• Internal Operator Overloading
• Polymorphic Variables or Parameters
1. Coercion
• Coercion deals with implicitly converting
one type of object into a new object of a
different kind. Also, this is done
automatically to prevent type errors in the
code. 
• Programming languages such as C, java, etc
support the conversion of value from one
data type to another data type. Data type
conversions are of two types, i.e., implicit
and explicit. 
• Implicit type conversion is automatically
done in the program and this type of
conversion is also termed coercion. 
• For example, if an operand is an integer and
another one is in float, the compiler
implicitly converts the integer into float
value to avoid type error.
2. Internal Operator
Overloading
• In Operator Overloading, an operator or
symbol behaves in more ways than one
depending upon the input context or the
type of operands. It is a characteristic of
static polymorphism. Although Java does
not support user-defined operator
overloading like C++, where the user can
define how an operator works for different
operands, there are few instances where
Java internally overloads operators.
• Operator overloading is the concept of using
the operator as per your choice. Therefore,
an operator symbol or method name can be
used as a ‘user-defined’ type as per the
requirements. 
• For example, ‘+’ can be used to perform the
addition of numbers (same data type) or for
concatenation of two or more strings.
• In the case of +, can be used for addition and
also for concatenation.
• Similarly, operators like! &, and | are also in
the overload position for logical and bitwise
operations. In both of these cases, the type of
argument will decide how the operator will
interpret.
• In Java, the object or instance variables
represent the polymorphic variables. This is
because any object variables of a class can
have an IS-A relationship with their own
classes and subclasses.
• The Polymorphic Variable is a variable that
can hold values of different types during the
time of execution.
 3. Polymorphic Variables or
Parameters
• Parametric polymorphism specifies that
while class declaration, a field name can
associate with different types, and a method
name can associate with different
parameters and return types.
JAVA DATABASE
CONNECTIVITY (JDBC)
• Netbeans
• Xamp
• Mysql connector
myConnection(method) page
Create page
Delete page
Update page
JAVA SERVER PAGE(JSP)

You might also like