Dr. R. Manikandan Assistant Professor (Senior Grade) Vit Bhopal University
Dr. R. Manikandan Assistant Professor (Senior Grade) Vit Bhopal University
JAVA
UNIT I
DR. R. MANIKANDAN
ASSISTANT PROFESSOR (SENIOR GRADE)
VIT BHOPAL UNIVERSITY
1
COURSE OBJECTIVE
• Creating high-performing multi-threaded applications
• Creating Java technology applications that leverage the object-oriented
features of the Java language, such as encapsulation, inheritance, and
polymorphism
• Implementing input/output (I/O) functionality to read from and write to
data and text files and understand advanced I/O streams
• Executing a Java technology application from the command line
• Manipulating files, directories and file systems using the JDK NIO.2
specification
• Creating applications that use the Java Collections framework
• Performing multiple operations on database tables, including creating,
reading, updating and deleting using both JDBC and JPA technology
• Searching and filter collections using Lambda Expressions
• Implementing error-handling techniques using exception handling
• Using Lambda Expression concurrency features
2
BENEFITS TO YOU
• You can use this course to further develop your skills
with the Java language and prepare for the Oracle
Certified Professional, Java SE 8 Programmer Exam!
3
COURSE SYLLABUS
4
TEXTBOOK / REFERENCE BOOKS
TEXT BOOK
• Herbert Schildt, “Java The complete reference”, 11th edition,
Oracle press , 2018.
5
TEXTBOOK / REFERENCE BOOKS
REFERENCE BOOKS
• Oracle University Reference E-Kit
• Deitel and Deitel, “Java How to
Program (Early
objects)”,10thedition,Pearson,
2015
• Cay S.Horstmann and Gary
Cornell, “Core Java Vol I–
Fundamentals”,8thedition,Pearso
n, 2011
• Steven Holzner et al., “Java 2
Black Book”, Dreamtech press,
Reprint edition 2010
6
COURSE ASSESSMENT DETAILS
S.No Name of the Nos. Marks Remarks
Component
1 CAT1 1 15 Exam will Conduct 50 Marks
then convert into 15 Marks
2 CAT2 1 15
6 Attendance Based on % 5
Total 100
7
WHAT DO YOU EXPECT OUT OF
THIS COURSE?
8
Programming Paradigm: Overview
• Programming Paradigm can be classified into 3 primary types
• Unstructured Programming
14
Programming Paradigm: Overview
Object Oriented programming
Advantages
• It provides a clear modular structure for programs which makes it
good for defining abstract data types in which implementation details
are hidden
• Objects can also be reused within an across applications. The reuse of
software also lowers the cost of development. More effort is put into
the object-oriented analysis and design, which lowers the overall cost
of development.
• It makes software easier to maintain. Since the design is modular,
part of the system can be updated in case of issues without a need to
make large-scale changes 15
Programming Paradigm: Overview
Advantages
• Reuse also enables faster development. Object-oriented
programming languages come with rich libraries of objects, and
code developed during projects is also reusable in future projects.
• It provides a good framework for code libraries where the supplied
software components can be easily adapted and modified by the
programmer. This is particularly useful for developing graphical user
interfaces.
• Better Productivity as OOP techniques enforce rules on a
programmer that, in the long run, help us get more work done;
finished programs work better, have more features and are easier to
read and maintain.
– OOP programmers take new and existing software objects and "stitch" them
together to make new programs. Because object libraries contain many useful
functions, software developers don't have to reinvent the wheel as often;
more of their time goes into making the new program.
16
Programming Paradigm: Overview
OOPs Vs Structure or Procedural oriented Programming Paradigm
17
OOPs Concepts: Recap
18
OOPs Concepts: Recap
Object
• Object is a real world entity, which has state, behaviour and
identity .
• The state of an object can be described as a set of attributes
and their values.
– For example, a bank account has a set of attributes such as
Account Number, Name, Account Type, Balance, and values of
all these attributes.
• The behaviour or operation of an object refers to the
changes that occur in its attributes over a period of time.
• Each object has a unique identity that can be used to
distinguish it from other objects. Two objects may exhibit
the same behaviour and they may or may not have the
same state, but they never have the same identity.
19
OOPs Concepts: Recap
Class
• Class is a group of objects with similar properties, common
behaviour, common relationships with other objects, and
common semantics.
• A class is the template / blueprint from which individual objects
are created.
• For example, Each bicycle was built from the same set of
blueprints and therefore contains the same components.
• In object-oriented terms, we say that your bicycle is an instance
of the class of objects known as bicycles.
20
OOPs Concepts: Recap
Object & Class
21
OOPs Concepts: Recap
Object & Class
22
OOPs Concepts: Recap
Abstraction
23
OOPs Concepts: Recap
Encapsulation
• Encapsulation is defined as the process of enclosing one or more
details from outside world through access right. It says how much
access should be given to particular details.
• Both Abstraction & Encapsulation works hand in hand because
Abstraction says what details to be made visible &
Encapsulation provides the level of access right to that visible
details. i.e. – It implements the desired level of abstraction.
24
OOPs Concepts: Recap
Inheritance
• Inheritance enables new objects to take on the properties of
existing objects. A class that is used as the basis for inheritance is
called a super class or base class. A class that inherits from a
super class is called a sub class or derived class.
• For example, a child inherits the traits of his/her parents.
With inheritance, we can reuse the fields and methods of the
existing class. Hence, inheritance facilitates Reusability and is an
important concept of OOPs.
25
OOPs Concepts: Recap
Inheritance
26
OOPs Concepts: Recap
Inheritance
27
OOPs Concepts: Recap
Polymorphism
• Polymorphism is the concept where an object behaves differently
in different situations. There are two types of polymorphism –
compile time polymorphism and runtime polymorphism.
• More precisely we say it as 'many forms of single entity'. This
play a vital role in the concept of OOPS.
• For Example, we are turn on the phone by one button at the
same time we can turn off the phone by the same button.
28
Object Oriented Programming vs.
Object Based Programming
• Object oriented and Object based programming languages have
some different features and behaviour
Object oriented language
• Object-oriented language supports all the features of OOPs.
• Object-oriented language doesn't has in-built object.
• Object-oriented languages are C++, C#, Java, Python, PHP etc.
Object based language
• Object-based language doesn't support all the features of OOPs
like Polymorphism and Inheritance
• Object-based language has in-built object like JavaScript has
window object.
• Object-based languages are JavaScript, VB etc.
29
JAVA: Introduction
• Java is an object-oriented, class-based, concurrent,
secured and general-purpose computer-programming
language.
• Java is a platform.
• Platform: Any hardware or software environment in
which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is
called a platform.
30
JAVA: History
• Java initial work started in 1990 by Sun Microsystems
engineer Patrick Naughton as a part of the Stealth Project.
• The Stealth Project soon changed to the Green Project, with
Mike Sheridan and James Gosling joining the ranks, and the
group began developing new technology for programming
next-generation smart appliances.
• James Gosling, Mike Sheridan, and Patrick Naughton initiated
the Java language project in June 1991.
• Gosling attempted to modify and extend C++ (a development
he refers to as "C++ ++ --"), but quickly abandoned this
approach in favour of creating an entirely new language.
• Firstly, it was called "Greentalk" by James Gosling, and file
extension was .gt. After that, it was called Oak, named after
the tree that stood outside his office.
31
JAVA: History
• Originally designed for small, embedded systems in electronic
appliances like set-top boxes. Then incorporate some changes
based on emergence of World Wide Web, which demanded
portable programs.
• In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies.
• The first publicly available version of Java (Java 1.0) was released
in 1995.
• In 2006 Sun started to make Java available under the GNU
General Public License (GPL). Sun Microsystems was acquired by
the Oracle Corporation in 2010. Oracle continues this project
called OpenJDK.
32
JAVA Version: History
33
Why JAVA?
Programming Popularity (2019) Other Comparisons
• Copy-of-top-programming-l
anguages-1.webp
• top-programming-languages
-1.webp
• Most-pull-requests-1.webp
34
Where it is used?
• 850 million PCs as Java Runtime Environment
• More then 3 billion devices run java
– Desktop Applications such as acrobat reader, media
player, antivirus etc.
– Web Applications
– Enterprise Applications such as banking applications.
– Mobile
– Web services
– Cloud
– Embedded System
– Smart Card
– Robotics
– Games etc.
35
JAVA Editions
36
How JAVA is different from C?
– Major difference is that C is a structure oriented language and
Java is an object oriented language and has mechanism to
define classes and objects.
– Java does not support an explicit pointer type
– Java does not have preprocessor, so we cant use #define,
#include and #ifdef statements.
– Java does not include structures and unions types.
– Java does not include keywords like goto, sizeof and typedef.
– Java adds labeled break and continue statements.
– Java adds many features required for object oriented
programming. 37
How JAVA is different from C++?
• C++ language Features removed in java:
Java doesn’t support pointers to avoid unauthorized access
of memory locations.
Java does not include structures and unions types.
Java does not support operator over loading.
Preprocessor plays less important role in C++ and so
eliminated entirely in java.
Java does not perform automatic type conversions that
result in loss of precision.
38
How JAVA is different from C++?
Java does not support global variables. Every method and
variable is declared within a class and forms part of that class.
Java does not allow default arguments.
Java does not support inheritance of multiple super classes by
a sub class (i.e., multiple inheritance). This is accomplished by
using ‘interface’ concept.
It is not possible to declare unsigned integers in java.
In java objects are passed by reference only. In C++ objects
may be passed by value or reference.
39
How JAVA is different from C++?
New features added in Java:
Multithreading, that allows two or more pieces of the same program to
execute concurrently.
C++ has a set of library functions that use a common header file. But java
replaces it with its own set of API classes.
It adds packages and interfaces.
Java supports automatic garbage collection.
break and continue statements have been enhanced in java to accept
labels as targets.
The use of Unicode characters ensures portability and
Internationalization.
40
How JAVA is different from C++?
Features that differ:
Though C++ and java supports Boolean data type, C++ takes any
nonzero value as true and zero as false. True and false in java
are predefined literals that are values for a boolean expression.
Java has replaced the destructor function with a finalize()
function.
C++ supports exception handling that is similar to java's.
However, in C++ there is no requirement that a thrown
exception be caught.
41
Java Environment
• Java includes many development tools, classes and
methods
– Development tools are part of Java Development Kit (JDK) and
– The classes and methods are part of Java Standard Library
(JSL), also known as Application Programming Interface (API).
43
JDK VS JRE VS JVM
• JDK is a software development environment used for
developing Java applications and applets.
• It includes the Java Runtime Environment (JRE), an
interpreter/loader (Java), a compiler (javac), an
archiver (jar), a documentation generator (Javadoc)
and other tools needed in Java development.
44
JDK VS JRE VS JVM
• JRE stands for “Java Runtime Environment” and may
also be written as “Java RTE.” The Java Runtime
Environment provides the minimum requirements
for executing a Java application; it consists of
the Java Virtual Machine (JVM), core classes,
and supporting files.
45
JDK VS JRE VS JVM
• JVM
– Java Interpreter + Just-In-Time Compiler
– JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which java
byte code can be executed.
– JVMs are available for many hardware and software platforms.
It is the code execution component of the Java platform.
– It is a Runtime Instance Whenever you write java command on
the command prompt to run the java class, an instance of JVM
is created.
• Note:
– JVM, JRE and JDK are platform dependent because
configuration of each OS differs. But, Java is platform
independent.
46
JAVA Features
47
JAVA Features
Simple
• Java is very easy to learn, and its syntax is simple,
clean and easy to understand.
– Java syntax is based on C++ & C.
– Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator
overloading, etc.
– There is no need to remove unreferenced objects because
there is an Automatic Garbage Collection in Java.
Object-oriented
– Java is an fully object-oriented programming language.
Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types
of objects that incorporates both data and behaviour.
– It supports all the OOPs concepts 48
JAVA Features
Secured
• Java is secured because:
– No explicit pointer
– Java Programs run inside a virtual machine sandbox
51
Architecture-neutral
JAVA Features
– Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
– In C programming, int data type occupies 2 bytes of memory for 32-
bit architecture and 4 bytes of memory for 64-bit architecture.
However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
Portable
– Java is portable because it facilitates you to carry the Java bytecode
to any platform. It doesn't require any additional implementation.
High-performance
– Java is a little bit slower than a compiled language (e.g., C++). Java is
an compiled and interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.
– But with the use of Just-In-Time compilers, Java enables high
performance than C, C++, etc.
52
Dynamic
JAVA Features
– Java is a dynamic language. It supports dynamic loading of classes.
It means classes are loaded on demand. It supports dynamic
compilation and automatic memory management (garbage
collection).
Distributed
– Java is distributed because it facilitates users to create distributed
applications in Java.
– RMI and EJB are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods
from any machine on the internet.
Multi-threaded
– A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it
doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web
53
applications, etc.
First Java Program
• For executing any java program, you need to Install the JDK if you
don't have installed it, download the JDK and install it.
– https://www.oracle.com/technetwork/java/javase/downloads/index.html
• Create the java program using any editor like notepad, notepad++
and save with file extension .java. Ex: Simple.java
https://www.oreilly.com/library/view/learning-java/1565927184/ch10.html
55
First Java Program
• The path is required to be set for using tools such as
javac, java, etc.
• If you are saving the Java source file inside the JDK/bin
directory, the path is not required to be set because all
the tools will be available in the current directory.
• If you have your Java file outside the JDK/bin folder, it is
necessary to set the path of JDK.
There are two ways to set the path in Java:
• Temporary
• In Comment Prompt
• set path= C:\Program Files\Java\jdk1.8.0_191\bin
• Permanent
• Set Path using Environmental Variables option
56
First Java Program
• Compile and run the java program
• To compile:
– Javac Simple.java
• To run:
– java Simple
57
First Java Program: JVM & JIT
58
First Java Program: JVM
59
First Java Program: JIT
• The Just-In-Time (JIT) compiler is a component of the runtime
environment that improves the performance of Java
applications by compiling byte codes to native machine code
at run time.
• The JIT compiler is enabled by default. When a method has
been compiled, the JVM calls the compiled code of that
method directly instead of interpreting it. Theoretically, if
compilation did not require processor time and memory
usage, compiling every method could allow the speed of the
Java program to approach that of a native application.
More Details
• https://www.ibm.com/support/knowledgecenter/en
/SSYKE2_8.0.0/com.ibm.java.vm.80.doc/docs/jit_ove
rview.html
60
First Java Program
QA:
1. Is necessary main class is public in java?
2. Is necessary main class name should be same as filename?
3. Why java main method is static and public?
63
Basics of JAVA: Data Types
64
Basics of JAVA: Variables
• The variable is the basic unit of storage in a Java
program. A variable is defined by the combination of
an identifier, a type, and an optional initializer.
• In addition, all variables have a scope, which defines
their visibility, and a lifetime.
• There are three types of variables in java:
Local Variable
– A variable declared inside the body of the method is called
local variable. You can use this variable only within that
method and the other methods in the class aren't even
aware that the variable exists.
– A local variable cannot be defined with "static" keyword.
65
Basics of JAVA: Variables
Instance Variable or Non-static variable
– A variable declared inside the class but outside the body of
the method, is called instance variable. It is not declared
as static.
– Instance variables are created when the objects are
instantiated and therefore they are associated with the
objects.
Static variable or Class variable
– A variable which is declared as static is called static
variable. It cannot be local. You can create a single copy of
static variable and share among all the instances of the
class.
– Memory allocation for static variable happens only once
when the class is loaded in the memory.
66
Basics of JAVA: Variables
Example:
class A
{ QA:
int data=50;//instance variable 1. Which code fragment correctly assign a
numeric literal?
static int m=100;//static variable
void method() A) byte b1 = b1011;
{ B) byte b2 = 1011b;
int n=90;//local variable C) byte b3 = 0b1001;
} D) byte b4 = 0xb001;
}//end of class
Note:
• The prefix 0x or 0X indicates hexadecimal and 0b or 0B indicates binary:
// The number 26, in decimal int decVal = 26;
// The number 26, in hexadecimal int hexVal = 0x1a;
// The number 26, in binary int binVal = 0b11010;
67
Literals
• A literal is the source code representation of a fixed value; literals
are represented directly in your code without requiring
computation.
• Examples
– boolean result = true;
– char capitalC = 'C';
– byte b = 100;
– short s = 10000;
– int i = 100000;
• Using Underscore Characters in Numeric Literals
• In Java SE 7 and later, any number of underscore characters (_)
can appear anywhere between digits in a numerical literal.
• This feature enables you, for example. to separate groups of digits
in numeric literals, which can improve the readability of your
code.
68
Literals
• Examples
– long creditCardNumber = 1234_5678_9012_3456L;
– long socialSecurityNumber = 999_99_9999L;
– float pi = 3.14_15F;
– long hexBytes = 0xFF_EC_DE_5E;
– long hexWords = 0xCAFE_BABE;
– long maxLong = 0x7fff_ffff_ffff_ffffL;
– byte nybbles = 0b0010_0101;
– long bytes = 0b11010010_01101001_10010100_10010010;
• You can place underscores only between digits; you cannot place
underscores in the following places:
– At the beginning or end of a number
– Adjacent to a decimal point in a floating point literal
– Prior to an F or L suffix
– In positions where a string of digits is expected
69
Basics of JAVA: Unicode
• Unicode is a universal international standard character encoding
that is capable of representing most of the world's written
languages.
Why java uses Unicode System?
• Before Unicode, there were many language standards:
– ASCII (American Standard Code for Information Interchange) for
the United States.
– ISO 8859-1 for Western European Language.
– KOI-8 for Russian.
– GB18030 and BIG-5 for Chinese, and so on.
This caused two problems:
– A particular code value corresponds to different letters in the
various language standards.
– The encodings for languages with large character sets have
variable length. Some common characters are encoded as single
bytes, other require two or more byte. 70
Basics of JAVA: Unicode
• Solution
• To solve these problems, a new language standard was developed
i.e. Unicode System.
• In Unicode, character holds 2 byte, so java also uses 2 byte for
characters. The range of a char is 0 to 65,536
• lowest value:\u0000 highest value:\uFFFF
71
Basics of JAVA: Operators
72
Basics of JAVA: Type Conversion
Widening or Automatic Type Conversion
• Widening conversion takes place when two data types are
automatically converted. This happens when:
– The two data types are compatible.
– When we assign value of a smaller data type to a bigger data type.
• For Example, in java the numeric data types are compatible with
each other but no automatic conversion is supported from
numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
• Example: Type1.java
73
Basics of JAVA: Type Conversion
Narrowing or Explicit Conversion
• If we want to assign a value of larger data type to a smaller data
type we perform explicit type casting or narrowing.
– This is useful for incompatible data types where automatic conversion
cannot be done.
– Here, target-type specifies the desired type to convert the specified value
to.
• Example: Type2.java
74
Basics of JAVA: Control Statements
76
Basics of JAVA: Wrapper class
• Wrapper class in java provides the mechanism to convert
primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature converts
primitive into object and object into primitive automatically.
• The automatic conversion of primitive into object is known as
autoboxing and vice-versa unboxing.
• Need of Wrapper Classes
– They convert primitive data types into objects. Objects are needed if we
wish to modify the arguments passed into a method (because primitive
types are passed by value).
– Each class contains some useful methods
– The classes in java.util package handles only objects and hence wrapper
classes help in this case also.
– Data structures in the Collection framework, such as ArrayList and Vector,
store only objects (reference types) and not primitive types.
– An object is needed to support synchronization in multithreading.
77
Basics of JAVA: Wrapper class
• Example: WrappingUnwrapping.java
78
Control Statements : Loops
Loops
82
Basics of JAVA: Array
• An array is a collection of similar type of elements that have a
contiguous memory location.
• Java array is an object which contains elements of a similar data type. It
is a data structure where we store similar elements. We can store only a
fixed set of elements in a Java array.
• Array in java is index-based, the first element of the array is stored at
the 0 index.
Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
• Random access: We can get any data located at an index position.
Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
83
framework is used in Java which grows automatically.
Basics of JAVA: Array
Types of Array
• There are two types of array.
– Single Dimensional Array
– Multidimensional Array
• Single Dimensional Array in Java
Example
TestJaggedArray.java
85
Basics of JAVA: Array
Types of Array
• Multi Dimensional Array in Java
Syntax to Declare an Array in Java Example1:
dataType[][] arrayRefVar; (or) int [ ][ ] s;
dataType [][]arrayRefVar; (or) s=new int[3][3];
dataType arrayRefVar[][]; (or) Example2:
dataType []arrayRefVar[]; //declaration and instantiation
Instantiation of an Array in Java int s[ ][ ]=new int[3][3]
arrayRefVar=new datatype[row][col];
• Jagged Array in Java
– it is an array of arrays with different number of columns.
Example
TestJaggedArray.java
86
Basics of JAVA: Naming Convention
87
Basics of JAVA: String Class
• String is a sequence of characters. In java, objects of String are
immutable which means a constant and cannot be changed
once created.
Creating a String
• There are two ways to create string in Java:
– String literal: String s = “GeeksforGeeks”;
– Using new keyword: String s = new String (“GeeksforGeeks”);
• Example: StringExample.java
88
Basics of JAVA: StringBuffer and StringBuilder class
• The StringBuffer and StringBuilder classes are used when there
is a necessity to make a lot of modifications to Strings of
characters.
• Unlike Strings, objects of type StringBuffer and String builder
can be modified over and over again without leaving behind a
lot of new unused objects.
• The Java StringBuilder class is same as StringBuffer class except
that it is non-synchronized. It is available since JDK 1.5.
• Both have similar type of methods
Creating a String
• StringBuffer sb = new StringBuffer(“Test");
• StringBuilder sb1 = new StringBuilder(“Hello");
• Example: StringExample2.java
90
Basics of JAVA: Read Input from console
91
Basics of JAVA: Read Input from console
• Scanner is a class in java.util package used for obtaining the
input of the primitive types like int, double etc. and strings.
• To create an object of Scanner class, we usually pass the
predefined object System.in, which represents the standard
input stream. We may pass an object of class File if we want to
read input from a file.
• To read numerical values of a certain data type XYZ, the function
to use is nextXYZ(). For example, to read a value of type short,
we can use nextShort()
• To read strings, we use nextLine() or next().
• To read a single character, we use next().charAt(0). next()
function returns the next token/word in the input as a string and
charAt(0) funtion returns the first character in that string.
• Example: ScannerDemo1.java, ScannerDemo2.java,
ScannerDemo3.java
92