Java
Java
Java
Sabyasachi Moitra
moitrasabyasachi@hotmail.com
Introduction
O Like C & C++, Java is also a high level
programming language.
O Java programming language was developed by
Sun Microsystems which was initiated by James
Gosling and was released in 1995.
O Like C++, Java is also an object oriented
programming language.
O Platform independent
- Unlike C/C++, when a Java code is compiled it is
converted into bytecode. This bytecode is a
platform-independent code because it can be
run on multiple platforms.
2
Types of Java Applications
O Standalone Application
- An application that we need to install on every
machine.
O Web Application
- An application that runs on the server side and
creates dynamic page.
O Enterprise Application
- An application that is distributed in nature.
O Mobile Application
- An application that is created for mobile
devices.
3
Java Platforms / Editions
O Java SE (Java Standard Edition)
- It is a java programming platform.
O Java EE (Java Enterprise Edition)
- It is an enterprise platform which is mainly used
to develop web and enterprise applications.
O Java ME (Java Micro Edition)
- It is a micro platform which is mainly used to
develop mobile applications.
O JavaFx
- It is used to develop rich internet applications.
4
OOP vs POP
OOP POP
Object Oriented Programming Procedure Oriented Programming
Programs are divided into what are known Large programs are divided into smaller
as objects. programs known as functions.
Objects may communicate with each other Data move openly around the system from
through functions. function to function.
Data is hidden & cannot be accessed by Does not have any proper way for hiding
external functions. Thus, more secure. data. Thus, less secure.
Follows bottom-up approach. Follows top-down approach.
5
OOP Terminologies
Terminology Description
Objects are the basic run-time entities in an
Object
object-oriented system.
A class is a collection of similar type of
objects.
Class Example
Employee emp1;
emp1 OBJECT
Employee CLASS
6
OOP Terminologies (2)
Terminology Description
Inheritance is the process by which objects of one
Inheritance class acquire the properties of objects of another
class.
• Ability to take more than one form.
• Using a single function name to perform
different types of tasks is known as Function
Polymorphism Overloading.
• The process of making an operator to exhibit
different behaviors in different instances is
termed as Operator Overloading.
Connecting a method call to the method body is
known as Binding.
When type of the object is determined at compile-
Dynamic Binding
time, it is known as Static Binding.
When type of the object is determined at run-time,
it is known as Dynamic Binding.
Involves specifying the name of the object, name
Message Passing of the function (message) & the information to be
sent.
7
C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system Java is mainly used for
programming. application programming.
C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It
can be achieved by interfaces
in java.
C++ supports operator Java doesn't support operator
overloading. overloading.
C++ uses compiler only. Java uses both compiler and
interpreter.
8
First Java Program
Source Code
Output
(HelloWorld.java)
class HelloWorld HELLO WORLD!!!
{
public static
void main(String
args[])
{
System.out.print
ln("HELLO WORLD!!!");
}
}
9
Parameter Description
class • Keyword.
• Used to declare a class in java.
public • Keyword.
• Access modifier.
• Represents visibility.
• Means visible to all.
static • Keyword.
• If any method is declared as
static, it is known as static
method.
• The core advantage of static
method is that there is no need
to create an object to invoke the
static method.
• The main method is executed
by the JVM, so it doesn't require
to create object to invoke the
main method.
• Saves memory.
10
Parameter Description
void • Return type of the
method.
• Means the method
doesn't return any value.
main() Represents the start-up of
the program.
String args[] Used for command line
argument.
System.out.println() Used to print statement.
11
Flow of Java Program
HelloWorld.java
COMPILER
HelloWorld.class
JVM
Output
12
JVM, JRE & JDK
JVM
O Java Virtual Machine.
O It is an abstract machine which provides a runtime
environment for executing the java bytecode.
JRE
O Java Runtime Environment.
O It is the implementation of JVM.
O It physically exists.
O It contains the set of libraries + other files that JVM uses at
runtime.
JDK
O Java Development Kit.
O It physically exists.
O It contains JRE + development tools.
13
JVM, JRE & JDK (2)
JVM
JRE
JDK
14
Constants, Variables &
Data Types
Tokens
Smallest individual units in a program are
known as tokens.
TOKENS
Special
Keywords Identifiers Constants Strings Operators
Symbols
16
Keywords
O Reserved identifiers.
O Cannot be used as names for the program
variables or other user-defined program
elements.
abstract boolean break byte
case catch char class
const continue default do
double else enum extends
final finally float …..
17
Identifiers
O Identifiers refer to the names of variables,
functions, arrays, etc., created by the
programmers.
O An identifier starts with a letter A to Z, a to z, or
an underscore '_' followed by zero or more
letters, underscores, and digits (0 to 9).
O Punctuation characters such as @, $, and % are
not allowed within identifiers.
O Case-sensitive, i.e., account & ACCOUNT are two
different identifiers.
18
Literals
Literals (or Constants) refer to fixed values that
do not change during the execution of a
program.
Literals
Backslash
Floating Point Boolean Character
Integer Literals String Literals Character
Literals Literals Literals
Literals
19
Variables
O A variable is a data name that is used to
store a data value which can be changed
during program execution.
O E.g. sum, avg, etc.
short
Integer
int
long
float
Primitive
Floating-Point
double
DATA TYPE
Character char
Boolean boolean
Array
Non-Primitive String
etc.
21
Operators & Expressions
Operators
O An operator is a symbol that tells the
computer to perform certain mathematical
or logical manipulations.
O Operators are used in programs to
manipulate data & variables.
O They usually form a part of the
mathematical or logical expressions.
23
Types of Operator
Type Operators
Arithmetic Operators +, -, *, /, %
Relational Operators ==, !=, >, <, >=, <=
Logical Operators &&, ||, !
Increment & Decrement ++, --
Operators
Conditional Operator ?:
Bitwise Operators &, |, ~, ^, <<, >>
=, +=, -=, *=, /=, %=, &=, |=,
Assignment Operators
^=, <<=, >>=
24
Example
(Scanner class)
25
Example
(BufferedReader class)
26
Scanner VS BufferedReader
Scanner BufferedReader
Reads data alone. Can’t read data alone, takes
help from InputStreamReader.
Reads & parse data, hence Only reads data, hence faster.
slower.
Reads int, float, char. Reads only strings.
Buffer size 1kb, hence Buffer size 8kb, hence
suitable for reading small suitable for reading file with
user inputs. long string.
Available from JDK 5. Available from JDK 1.1.
27
Decision Making &
Branching
Simple if Statement
O An if statement consists of a Boolean
expression followed by one or more
statements.
O If the Boolean expression evaluates to true,
then the block of code inside the if
statement will be executed. If the Boolean
expression evaluates to false, then the first
set of code after the end of the if statement
will be executed.
29
Example
30
if…else Statement
O An if statement can be followed by an
optional else statement, which executes
when the Boolean expression is false.
O If the Boolean expression evaluates to true,
then the if block will be executed, otherwise,
the else block will be executed.
31
Example
32
Nested if or if…else Statements
Use of one if or if…else statement inside
another if or if…else statement(s).
33
Example
34
if…else if Ladder Statement
The if…else if statement is used to execute
one code from multiple conditions.
35
Example
36
switch Statement
A switch statement allows a variable to be
tested for equality against a list of values
known as case.
37
Example
38
Decision Making &
Looping
What is loop?
O A loop in Java language is used to execute a
block of code or a part of the program for
several times.
O It saves code.
40
Types of Loops
LOOPS
41
while Loop
O Iterates the code until the condition is false.
O Condition is given before the code. So the
code may be executed 0 or more times.
42
Example
Source Code Output
public class WhileExample
{
1
public static void 2
main(String[] args)
{
3
int i=1; 4
while(i<=10)
5
{ 6
System.out.println(i);
7
i++; 8
}
}
9
} 10
43
do while Loop
O Iterates the code until the condition is false.
O Condition is given after the code. So at least
once the code is executed whether the
condition is true or false.
44
Example
Source Code Output
public class DoWhileExample
{
1
public static void 2
main(String[] args)
{
3
int i=1; 4
do
5
{ 6
System.out.println(i);
7
i++; 8
}while(i<=10);
}
9
} 10
45
for Loop
O Iterates the code until the condition is false.
O Initialization, condition and
increment/decrement is given before the
code. So the code may be executed 0 or
more times.
46
Example
Source Code Output
public class ForExample
{
1
public static void 2
main(String[] args)
{
3
int i=1; 4
for(i=1;i<=10;i++)
5
{ 6
System.out.println(i);
}
7
} 8
}
9
10
47
for-each Loop
O Introduced in Java5.
O Mainly used to traverse array or collection
elements.
O Eliminates the possibility of bugs and makes
the code more readable.
48
Example
Source Code Output
public class ForEachExample
{
12
public static void 13
main(String[] args)
{
14
int arr[]={12,13,14,44}; 44
int i;
for(i:arr)
{
System.out.println(i);
}
}
}
49
break VS continue
break continue
O Can appear in both O Can appear only in
switch and loop loop statements.
statements. O When encountered,
O When encountered, gets the control to the
terminates the block next iteration of the
and gets the control loop.
out of the switch or
loop.
50
Example
break continue
public class BreakExample public class ContinueExample
{ {
public static void public static void
main(String[] args) main(String[] args)
{ {
int i=1; int i=1;
System.out.println(i); System.out.println(i);
} }
} }
} }
1234 1 2 3 4 6 7 8 9 10
51
Arrays
What is Array?
O Collection of homogeneous (similar)
elements (data) in a contiguous memory
location.
O Linear Data Structure
- A data structure (data organization and
storage format that enables efficient access
and modification) is said to be linear if the
elements form a sequence.
53
Example (1D Array)
54
Example (2D Array)
55
Classes & Objects
56
What is a Class?
O A class is a way to bind the data & its
associated methods together.
O General form of a class definition:
57
Access Modifiers in Java
Access Modifier Description
Accessible only within the
private
class.
Accessible only within the
default
package.
• Accessible within the
package and outside the
package but through
protected
inheritance only.
• Can't be applied on the
class.
public Accessible everywhere.
58
Determining Access to Class
Members
59
What is an Object?
O An object is an entity that has state and
behaviour.
O General form of a object declaration:
60
Example
(Rectangle.java)
61
RecAreaCalc.java
62
Output
63
Constructor
64
What is Constructor?
O A special type of method that is used to
initialize the object.
O It is invoked at the time of object creation.
65
Types of Constructor
CONSTRUCTOR
constructor constructor
without with
parameters parameters
Default Parameterized
66
Default Constructor
Source Code Output
class Student{
int id;
Bike is created
String name; 0 null
Student(){System.out.println(“S
tudent is created");}
void
display(){System.out.println(id
+" "+name);}
public static void main(String
args[]){
Student s=new Student();
s.display();
}
}
67
Parameterized Constructor
Source Code Output
class Student
{ 111 Karan
int id;
String name;
Student(int i,String n)
{
id=i;
name=n;
}
void display()
{
System.out.println(id+"
"+name);
}
s.display();
}
} 68
Constructor Overloading
O A technique in Java in which a class can
have any number of constructors that differ
in their parameter lists.
O The compiler differentiates these
constructors by taking into account the
number of parameters in the list and their
type.
69
Example
70
Constructor VS Method
Constructor Method
Constructor is used to Method is used to expose
initialize the state of an behaviour of an object.
object.
Constructor must not have Method must have return
return type. type.
Constructor is invoked Method is invoked explicitly.
implicitly.
Constructor name must be Method name may or may not
same as the class name. be same as class name.
71
this Keyword
O Refers to the current object.
72
Java Garbage Collection
O A way to destroy the unused objects in Java.
O Frees memory of an object which is out of its
scope.
O Similar destructor in C++.
73
Example
74
static variable
O Used to refer the common property of all
objects, i.e., not unique for each object.
O Gets memory only once.
75
Example
76
static Method
O A static method belongs to a class rather
than the object of the class.
O A static method can be invoked without the
need for creating an instance of a class.
O static method can access static data
member and can change the value of it.
77
Example
78
Inheritance
What is Inheritance?
O Inheritance is a process in which one object
acquires all the properties and behaviours of its
parent object automatically.
O We can reuse, extend or modify the attributes
and behaviours which are defined in other class.
O The class which inherits the members of another
class is called child class and the class whose
members are inherited is called parent class.
O Inheritance represents the IS-A relationship, also
known as parent-child relationship.
80
Types of Inheritance
81
Single Inheritance
82
Multilevel Inheritance
83
Hierarchical Inheritance
84
Multiple Inheritance
O To reduce the complexity and simplify the
language, Multiple Inheritance is not supported
in java.
O Consider a scenario where A, B & C are three
classes. The C class inherits A & B classes. If A &
B classes have same method and you call it
from child class object, there will be ambiguity to
call method of A or B class.
O Implemented through Interfaces (discussed
later).
85
Hybrid Inheritance
Combination of more than one inheritance:
O Single + Hierarchical or vice-versa
O Multilevel + Hierarchical or vice-versa
86
Hierarchical + Single Inheritance
87
88
super keyword
O The super keyword in java is a reference
variable which is used to refer immediate
parent class object.
O Whenever an instance of subclass is
created, an instance of parent class is
created implicitly which is referred by super
reference variable.
89
Example
90
Aggregation
O Member of a class is object of another class.
O Represents HAS-A relationship.
class Emp
{
int empno;
String name; //object of String class
double sal;
.....
}
91
Example
92
Polymorphism
Method Overloading
O Overloading refers to the use of the same thing
for different purposes.
O Java supports overloading of methods, i.e., using
the same method name to create methods that
perform a variety of different tasks.
O Using the concept of method overloading, we
can design a family of methods with one method
name by changing the number of arguments &
the data type.
[NOTE: Method Overloading is not possible by
changing the return type of the method only.]
94
Example
95
Method Overriding
O If a sub (child) class has the same method as
declared in the super (parent) class, it is known
as method overriding in java.
O The sub class provides a specific
implementation of the method that is already
provided by its super class.
O Runtime polymorphism.
96
Example
97
Method Overloading VS
Method Overriding
Method Overloading Method Overriding
Use to increase the Use to provide the specific
readability of the program. implementation of the
method that is already
provided by its super class.
Performed within class. Occurs in two classes that
have IS-A (inheritance)
relationship.
Return type can be same or Return type & parameter
different, but parameter must must be same, i.e., signature
be different. must be same.
Compile time polymorphism. Run time polymorphism.
98
final Keyword
O If a variable is declared as final, the value of
that variable cannot be changed.
O If a method is declared as final, the method
cannot be overriding.
O If a class is declared as final, the class
cannot be inherited.
99
Abstraction
100
Abstract Class
O Class declared with abstract keyword, is known as
abstract class in java.
O Can have constructor, data member, methods
(abstract and non-abstract (method with body)).
O Can’t be instantiate, i.e., can’t create any object.
O If there is any abstract method in a class, that class
must be abstract.
O Class extending any abstract class that have abstract
method, must either provide the implementation of
the method or make this class (child /sub class)
abstract.
O Mustn’t be declared as final.
101
Example
abstract class Bike{
abstract void run(); //no body and abstract
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4(); //dynamic binding
obj.run();
}
}
Output
running safely..
102
Interface
O Like class, interface also have data members & member
methods, but doesn’t have any constructor.
O By default in interface all member methods are public &
abstract, & all member variables are public, static &
final.
O An interface can extend multiple interfaces. Thus, we
can say that using interface multiple inheritance can be
implemented.
O A class can implement one/more than one interfaces.
O A class implementing an interface must have to override
all the abstract methods defined within the interface to
become a concrete class.
O Interface can be declared either as public or as default.
103
Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
printable obj = new A6();
obj.print();
}
}
Output
Hello
104
Multiple Inheritance
(using Interface)
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Output
Hello
105
Interface Inheritance
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Output
Hello
Welcome
106
Abstract Class VS Interface
Abstract Class Interface
Can have abstract and non-abstract Can have only abstract methods.
methods.
Doesn't support multiple inheritance. Supports multiple inheritance.
Can have final, non-final, static and Has only static and final variables.
non-static variables.
The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
Can extend another Java class and Can extend another Java interface
implement multiple Java interfaces. only.
A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc. by default.
107
Package
108
What is a Package?
O Group of similar types of classes, interfaces
and sub-packages.
O Can be categorized into two forms:
- Built-in package (java, lang, awt, javax,
swing, net, io, util, sql, etc.)
- User-defined package
109
110
Advantages of a Package
O Used to categorize the classes and
interfaces so that they can be easily
maintained.
O Removes naming collision.
111
Example
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Output
Welcome to package
112
How to access package from
another package?
There are three ways to access the package
from another package:
O import package.*;
O import package.classname;
O fully qualified name
113
Example
(using packagename.*)
[NOTE: If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.]
114
Example
(using packagename.classname)
115
Example
(using fully qualified name)
116
String Handling
O The String Class (see at the end)
O String Methods (see at the end)
118
String s = "java5" VS
String s = new String("java5“)
119
Exception Handling
What is an Exception?
O An Exception is a problem that arises during the execution of a
program (e.g., attempt to divide by zero).
O An Exception Handling is a process to handle such runtime errors.
O In Java 5 keywords are used to perform exception handling:-
- try (block, used to enclose the code that might throw an Exception)
- catch (block, used to handle the Exception)
- finally (block, always executed whether Exception is handled or
not)
- throw (used to explicitly throw an Exception)
- throws (used to declare an Exception)
[NOTE: For each try block there can be zero or more catch blocks, but
only one finally block]
121
Hierarchy of Java Exception
classes
122
Types of Exception
• Classes extending Throwable Irrecoverable.
class, except RuntimeException E.g., OutOfMemoryError,
& Error. VirtualMachineError,
• Checked at compile-time.
Exception AssertionError etc.
124
Exception Propagation
An exception is first thrown from the top of the
stack and if it is not caught, it drops down the
call stack to the previous method, If not
caught there, the exception again drops down
to the previous method, and so on until they
are caught or until they reach the very bottom
of the call stack. This is called Exception
Propagation.
125
Example
126
Diagrammatic Representation
127
Example
(throw)
128
Example
(throws)
129
Throw VS Throws
Throw Throws
Used to explicitly throw an Used to declare an exception.
exception.
Throw is followed by an Throws is followed by class.
instance.
Used within the method. Used with the method
signature.
Multiple exceptions can’t be Multiple exceptions can be
thrown. declared.
public void method()throws
IOException,SQLException
130
Final VS Finally VS Finalize
Final Finally Finalize
Used to apply restrictions on Used to place important Used to perform clean up
class, method and variable. code. It will be executed processing just before object
Final class can't be inherited, whether exception is is garbage collected.
final method can't be handled or not.
overridden and final variable
value can't be changed.
Final is a keyword. Finally is a block. Finalize is a method.
131
Working with Files
What is a File?
O A file is a collection of related data stored in a
particular area on the disk.
O Until now we have been using the standard input
(keyboard) for reading and standard output
(screen) for writing.
- It becomes cumbersome & time consuming to
handle large volumes of data through terminal.
- The entire data is lost when either the program
is terminated or the computer is turned off.
O To overcome the discussed problems the
concept of files is employed in Java
programming.
133
Writing to a File
134
Reading from a File
135
Appending to a File
136
References
O E Balagurusamy, Object Oriented
Programming with C++, 5th Edition,
McGrawHill
O Courtesy of JavaTPoint – Java Tutorial. URL:
https://www.javatpoint.com/java-tutorial
O Herbert Schildt, Java: The Complete
Reference, Seventh Edition, TMGH, 2007
O Courtesy of TutorialsPoint – Java Tutorial.
URL: https://www.tutorialspoint.com/java
137
The String Class
Objectives:
word ―java"
―Java"
Empty Strings
An empty String has no characters. It‘s
length is 0.
String word1 = ""; Empty strings
String word2 = new String();
result += word3;
//concatenates word3 to result ―rethinking‖
if(team.equalsIgnoreCase(“raiders”))
System.out.println(“Go You “ + team);
Methods — Comparisons
int diff = word1.compareTo(word2);
returns the ―difference‖ word1 - word2
int diff = word1.compareToIgnoreCase(word2);
returns the ―difference‖ word1 - word2,
case-blind
Usually programmers don‘t care what the numerical ―difference‖ of
word1 - word2 is, just whether the difference is negative (word1
comes before word2), zero (word1 and word2 are equal) or positive
(word1 comes after word2). Often used in conditional statements.
//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal
//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
Methods — trim
String word2 = word1.trim ();
returns a new string formed from word1 by
removing white space at both ends
does not affect whites space in the middle
String word1 = ― Hi Bob ―;
String word2 = word1.trim();
//word2 is ―Hi Bob‖ – no spaces on either end
//word1 is still ― Hi Bob ― – with spaces
Methods — replace
String word2 = word1.replace(oldCh, newCh);
returns a new string formed from word1 by
replacing all occurrences of oldCh with newCh
A common bug:
word1
word1.toUpperCase();
remains
unchanged
Numbers to Strings
Three ways to convert a number into a string:
1. String s = "" + num; Integer and Double
s = ―‖ + 123;//‖123‖ are ―wrapper‖ classes
2. String s = Integer.toString (i); from java.lang that
represent numbers as
String s = Double.toString (d); objects. They also
s = Integer.toString(123);//‖123‖ provide useful static
s = Double.toString(3.14); //‖3.14‖ methods.
int compareTo(Object o)
Compares this String to another Object.
boolean
equalsIgnoreCase(String anotherStri
ng)
Compares this String to another String,
ignoring case considerations.
int length()
Returns the length of this string.
String toUpperCase()
Converts all of the characters in this String
to upper case using the rules of the default locale.
String trim()
Returns a copy of the string, with leading and
trailing whitespace omitted.