1 Intro
1 Intro
Object Oriented
Programming Using Java
Syllabus
2
MODULE 1: Introduction
Approaches to Software Design - Functional Oriented Design, Object
Oriented Design, Case Study of Automated Fire Alarm System.
Object Modeling Using Unified Modeling Language (UML) – Basic
Object Oriented concepts, UML diagrams, Use case model, Class diagram,
Interaction diagram, Activity diagram, State chart diagram.
Introduction to Java - Java programming Environment and Runtime
Environment, Development Platforms -Standard, Enterprise. Java Virtual
Machine (JVM), Java compiler, Bytecode, Java applet, Java Buzzwords, Java
program structure, Comments, Garbage Collection, Lexical Issues.
3
MODULE 2 : Core Java Fundamentals
Primitive Data types - Integers, Floating Point Types, Characters, Boolean. Literals, Type
Conversion and Casting, Variables, Arrays, Strings, Vector class. Operators - Arithmetic
Operators, Bitwise Operators, Relational Operators, Boolean Logical Operators, Assignment
Operator, Conditional (Ternary) Operator, Operator Precedence. Control Statements -
Selection Statements, Iteration Statements and Jump Statements.
Object Oriented Programming in Java - Class Fundamentals, Declaring Objects, Object
Reference, Introduction to Methods, Constructors, this Keyword, Method Overloading, Using
Objects as Parameters, Returning Objects, Recursion, Access Control, Static Members, Final
Variables, Inner Classes, Command Line Arguments, Variable Length Arguments.
Inheritance - Super Class, Sub Class, The Keyword super, protected Members, Calling Order
of Constructors, Method Overriding, the Object class, Abstract Classes and Methods, using
final with Inheritance.
4
MODULE 3 : More features of Java
Packages and Interfaces - Defining Package, CLASSPATH, Access
Protection, Importing Packages, Interfaces.
Exception Handling - Checked Exceptions, Unchecked Exceptions, try
Block and catch Clause, Multiple catch Clauses, Nested try Statements,
throw, throws and finally.
Input/Output - I/O Basics, Reading Console Input, Writing Console Output,
PrintWriter Class,Object Streams and Serialization, Working with Files.
5
MODULE 4 : Advanced features of Java
Java Library - String Handling – String Constructors, String Length, Special
String Operations - Character Extraction, String Comparison, Searching Strings,
Modifying Strings, using valueOf(), Comparison of StringBuffer and String.
Collections framework - Collections overview, Collections Interfaces- Collection
Interface, List Interface. Collections Class – ArrayList class. Accessing a Collection
via an Iterator.
Event handling - Event Handling Mechanisms, Delegation Event Model, Event
Classes, Sources of Events, Event Listener Interfaces, Using the Delegation Model.
Multithreaded Programming - The Java Thread Model, The Main Thread, Creating
Thread, Creating Multiple Threads, Synchronization, Suspending, Resuming and
Stopping Threads
6
MODULE 5 :Graphical User Interface and
Database support of Java
7
REFERENCE TEXTBOOKS FOR THE
COURSE
COURSE OUTCOMES
SNo Course Outcomes Related Level
Module
CO1 Apply object-oriented analysis and design methods and Unified modelling 1 L3
Language notations to create effective and efficient system designs.
CO2 Develop Java application programs using java constructs, operators, 1,2,3,4 L3
control statements, built in packages, input /output streams, files and
libraries and advanced features of java.
CO3 Apply object-oriented features to solve various computing problems using 2,3 L3
Java.
CO4 Illustrate how robust programs can be written in Java using exception 3 L2
handling Mechanism.
CO5 Develop application programs in Java using multithreading and database 4,5 L3
connectivity.
CO6 Develop GUI based application programs in java utilising event handling 4,5 L3
and Swing.
INTRODUCTION TO JAVA
PROGRAMMING
OBJECTIVES
INTRODUCTION TO JAVA
OVERVIEW OF JDK,JRE AND JVM
JAVA PLATFORMS
JAVA BUZZWORDS
BASIC STRUCTURE OF JAVA PROGRAM
JAVA APPLET
GARBAGE COLLECTION IN JAVA
JAVA LEXICAL ISSUES
11
INTRODUCTION TO JAVA
Java was designed by Sun Microsystems
in the early 1990s to solve the problem of
connecting many household machines
together.
In 1991 when java was started initially, it
was called as “Oak”.
Later Java became popular for
developing web internet applications.
Java was developed by James Gosling
and a small team of engineers. 12
Java Version History
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan 1996)
• JDK 1.1 (19th Feb 1997)
• J2SE 1.2 (8th Dec 1998)
• J2SE 1.3 (8th May 2000)
• J2SE 1.4 (6th Feb 2002)
• J2SE 5.0 (30th Sep 2004)
• Java SE 6 (11th Dec 2006)
• Java SE 7 (28th July 2011)
• Java SE 8 (18th Mar 2014)
• Java SE 9 (21st Sep 2017)
• Java SE 10 (20th Mar 2018)
• Java SE 17 (SEP 2021)
15
16
JAVA DEVELOPMENT KIT (JDK)
The Java Development Kit (JDK) is a software development
environment used for developing and executing 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.
17
Java Runtime Environment (JRE)
JRE is also called as Java runtime, is a part of JDK.
JRE is an installation package which provides environment to only run(not
develop) the java program(or application)onto your machine.
If you want to run Java program you need JRE.
All JDK versions comes bundled with Java Runtime Environment, so you do
not need to download and install the JRE separately in your PC.
The runtime environment loads class files and ensures there is access to
memory and other system resources to run them.
It provides minimum requirements for executing java application.
It contains the class libraries, loader class, and JVM. 18
Java Virtual Machine (JVM)
JVM (Java Virtual Machine) is an abstract machine that enables your
computer to run a Java program.
JVM is a program which provides the runtime environment to execute Java
programs.
JVM is a virtual machine that resides in the real machine (your computer) and
the machine language for JVM is byte code.
Java compiler first compiles your Java code to bytecode.
Then, the JVM translates bytecode into native machine code (set of
instructions that a computer's CPU executes directly).
19
Java Virtual Machine (JVM)
20
Java Bytecode
In case of Java
24
Advantages of Java Bytecode
25
JAVA COMPILER
javac is the most popular Java compiler.
javac is the primary Java compiler included in the Java Development Kit
(JDK) from Oracle Corporation.
The compiler accepts source code conforming to the Java language
specification (JLS) and produces Java bytecode
When you write a program code, verification of method signatures and
other variables is performed at compile-time.
In general, a compiler converts the source code to target code.
26
JVM Architecture
Interpreter – Interpreter is basically a translator which converts Java Bytecodes into machine
code (the actual code understandable to computer known as binary code). It translate bytecodes line
by line.
The interpreter interprets the bytecode faster but executes slowly.
The disadvantage of the interpreter is that when one method is called multiple times, every time a
new interpretation is required.
JIT Compiler –
The JIT Compiler neutralizes the disadvantage of the interpreter.
The Execution Engine will be using the help of the interpreter in converting byte code, but when it
finds repeated code it uses the JIT compiler, which compiles the entire bytecode and changes it to
native code.
This native code will be used directly for repeated method calls, which improve the performance of
the system. 27
The Java Programming Language Platforms
All Java platforms consist of a Java Virtual Machine (JVM) and an application
programming interface (API).
28
The Java Programming Language Platforms
Java SE[Java Standard Edition]
When most people think of the Java programming language, they think of the Java SE
API.
Java SE's API provides the core functionality of the Java programming language.
It defines everything from the basic types and objects of the Java programming language
to high-level classes that are used for networking, security, database access, graphical
user interface (GUI) development
In addition to the core API, the Java SE platform consists of a virtual machine,
development tools, deployment technologies, and other class libraries and toolkits
commonly used in Java technology applications .
29
The Java Programming Language Platforms
Java EE [Java Enterprise Edition]
The Java EE platform is built on top of the Java SE platform. The Java EE
platform provides an API and runtime environment for developing and running
large-scale applications..
The Java EE provides a platform for developers with enterprise features such as
distributed computing and web services, Enterprise JavaBeans, Java Server
Pages, Servlets.
Java EE applications are usually run on reference run times such
as microservers or application servers.
Examples of some contexts where Java EE is used are e-commerce, accounting,
banking information systems. 30
The Java Programming Language Platforms
Java ME [Java Micro Edition]
The Java ME platform provides an API and a small-footprint virtual machine for
running Java programming language applications on small devices, like mobile
phones.
The API is a subset of the Java SE API, along with special class libraries useful
for small device application development.
31
The Java Programming Language Platforms
JavaFX
JavaFX is a software platform for creating and delivering desktop applications,
as well as rich Internet applications (RIAs) that can run across a wide variety of
devices.
The applications built in JavaFX, can run on multiple platforms including Web,
Mobile and Desktops.
JavaFX is intended to replace swing in Java applications as a GUI framework.
JavaFX is a set of graphics and media packages that enables developers to
design, create, test, debug, and deploy rich client applications that operate
consistently across diverse platforms.
32
JAVA APPLET
An applet is a special kind of Java program that runs in a Java enabled
browser
An applet is a Java program that can be embedded into a web page.
To create an applet, a class must class extends java.applet.Applet class.
An Applet class does not have any main() method.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer
considered important.
33
JAVA APPLET
Lifecycle of Java Applet
Applet is initialized.
Applet is started
Applet is painted.
Applet is stopped.
Applet is destroyed.
35
Java Buzzwords
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
36
Java Buzzwords
1.Simple
Java was designed to be easy for the professional programmer to learn and use
effectively.
If you already understand the basic concepts of object-oriented programming, learning
Java will be even easier.
C++ programmer can move to JAVA with very little effort to learn.
Java syntax is based on C++
Java has removed many complicated and rarely-used features, for
example, explicit pointers, operator overloading, etc.
37
Java Buzzwords
2. Object-Oriented
Java strongly supports the concepts of Object-Oriented Programming .
Java supports major Object-Oriented programming features like Encapsulation,
Abstraction, and Inheritance.
Almost everything in Java is an object. All programs and data live within objects
and classes.
‘Objects’ model Java rather than the ‘processes’.
38
Java Buzzwords
3.Secure
When a Java Compatible Web browser is used, downloading can be done safely without fear of viral
infection or malicious intent.
Java is a more secure language as compared to C/C++, as it does not allow a programmer to
explicitly create pointers.
Programs run in a virtual machine sandbox – A separate environment that allows users to execute
their applications without affecting the underlying system.
It has a bytecode verifier that checks the code fragments for any illegal code that violates the access
right.
.
39
Java Buzzwords
What makes java more secure than other languages?
Doesn’t use pointers as other languages do
Automated memory management
The Java compiler check, detects and handles errors seamlessly.
Java Sandbox
Exception Handling
40
Java Buzzwords
4.Robust
Java is a strictly typed language, it checks your code at compile time. However, it also checks your
code at run time .
Two of the main reasons for program failure: memory management mistakes and mishandled
exceptional conditions (that is,run-time errors).
Java virtually eliminates these problems by managing memory allocation and deallocation for you.
Deallocation is completely automatic, because Java provides garbage collection for unused
objects.
Java provides object-oriented exception handling. In a well-written Java program, all run-time
errors can and should be managed by your program.
Hence java is robust.
41
Java Buzzwords
5.Multithreaded
Multithreaded means handling multiple tasks simultaneously or executing multiple portions
(functions) of the same program in parallel.
The code of java is divided into smaller parts and Java executes them in
a sequential and timely manner.
6.Architecture-Neutral
This buzzword means that the program written on one platform or OS is independent of other
platforms or environments and can run on any other Operating System without recompiling them. In
other words, it is based on the ‘Write-once-run-anywhere’ (WORA) or ‘Write-once-run-
everywhere’ (WORE) approach.
Byte-code is not dependent on any machine architecture and Java Virtual Machine (JVM) can easily
translate bytecode into a machine-specific code.
42
Java Buzzwords
7.Interpreted and Compiled
The bytecode can either be interpreted or compiled to native code or directly executed on the
processor. But, if the bytecode is interpreted, it directly affects the speed of the application.
In order to speed up the performance, JIT compiler communicates with JVM at the execution time in
order to compile byte code sequences into native machine code.
Basically, when using JIT Compiler, the native code is easily executed by the hardware when
compared to JVM Interpreter. By doing so, there will be a huge gain in execution speed.
8. Portable
Java programs can execute in any environment (Linux,Window,Mac etc.) for which there is a Java
run-time system (JVM).
That really means there is no implementation dependent features.
43
Java Buzzwords
9. Platform Independent
Being platform-independent means a program compiled on one machine can be executed on any
machine in the world without any change. Java achieves platform independence by using the concept
of the BYTE code.
Java compiler converts the source code into an intermediate code called the byte code and this byte
code is further translated to machine-dependent form by another layer of software called JVM (Java
Virtual Machine).
Therefore, JVM can execute bytecode on any platform or OS .
This is where the “Write Once, run anywhere” (WORA) slogan for Java comes in, which means that
we can develop applications on one environment (OS) and run on any other environment without
doing any modification in the code.
44
Java Buzzwords
9. Platform Independent
45
Java Buzzwords
10. Distributed
Java is distributed because it encourages users to create distributed applications.
In Java, we can split a program into many parts and store these parts on different computers. A Java
programmer sitting on a machine can access another program running on the other machine.
Java helps us to achieve this by providing the concept of RMI (Remote Method
Invocation) and EJB (Enterprise JavaBeans).
Java comes with an extensive library of classes for interacting, using TCP/IP protocols such as HTTP
and FTP, which makes creating network connections much easier than in C/C++.
It also enables multiple programmers at many locations to work together on a single project.
46
Program Structure
A First Simple Program
/*
This is a simple Java program.
Call this file "Example.java".
*/
public class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
47
Here are the most important points to note about the Java programs:
Java code is case sensitive.
To write a Java program, you must have to define class first.
The name of the class in Java (which holds the main method) is the name of the Java
program, and the same name will be given in the filename.
As mentioned above in the sample program;
The name of the class is " Example " in which the main method is, then this file will be
named " Example.Java".
48
Here are the most important points to note about the Java programs:
public class Example • This creates a class called Example .
50
String[] args • It is an array where each element of it is a string, which
has been named as "args". If your Java program is run
through the console, you can pass the input parameter,
and main() method takes it as input.
System.out. • This statement is used to print text on the screen as
println() output, where the system is a predefined class, and out is
an object of the PrintWriter class defined in the system.
• The method println prints the text on the screen with a new
line.
• You can also use print() method instead of println()
method.
51
JAVA PROGRAM STRUCTURE
52
JAVA PROGRAM STRUCTURE
Documentation Section
You can write a comment in this section. It helps to understand the code. These are
optional.
It is used to improve the readability of the program.
The compiler ignores these comments during the time of execution
Types of comments that Java supports
Single line Comment
//This is single line comment
Multi-line Comment
/* this is multiline comment.
and support multiple lines*/ 53
JAVA PROGRAM STRUCTURE
Package Statement
A package is a group of classes that are defined by a name.
That is, if you want to declare many classes within one element, then you can declare it
within a package
Package is declared as: package package_name;
Eg: package mypackage;
Import Statement
If you want to use a class of another package, then you can do this by importing it
directly into your program.
import java.util.Date; //imports the date class
54
JAVA PROGRAM STRUCTURE
Class Definition
A Java program may contain several class definitions. Classes are the main and essential
elements of any Java program.
Main Method Class
The main method is from where the execution actually starts .
Every Java stand-alone program requires the main method as the starting point of the
program.
This is an essential part of a Java program.
There may be many classes in a Java program, and only one class defines the main
method
Methods contain data type declaration and executable statements.
55
Garbage Collection in Java
When JVM starts up, it creates a heap area which is known as runtime data area. This is
where all the objects (instances of class) are stored.
Since this area is limited, it is required to manage this area efficiently by removing the
objects that are no longer in use.
The process of removing unused objects from heap memory is known as Garbage
collection and this is a part of memory management in Java.
Languages like C/C++ don’t support automatic garbage collection, however in java, the
garbage collection is automatic.
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically.
In other words, it is a way to destroy the unused objects.
56
Garbage Collection in Java
Main objective of Garbage Collector is to free heap memory by destroying
unreachable objects.
Unreachable objects : An object is said to be unreachable iff it doesn’t contain
any reference to it.
Eligibility for garbage collection : An object is said to be eligible for
GC(garbage collection) iff it is unreachable.
finalize() method – This method is invoked each time before the object is
garbage collected and it perform cleanup processing.
57
Garbage Collection in Java
Basic process.
In the first step, unreferenced objects are identified and marked as ready for
garbage collection.
In the second step, marked objects are deleted.
Optionally, memory can be compacted after the garbage collector deletes
objects, so remaining objects are in a contiguous block at the start of the heap.
The compaction process makes it easier to allocate memory to new objects
sequentially after the block of memory allocated to existing objects.
58
Garbage Collection in Java
Request for Garbage Collection
The garbage collection implementation lives in the JVM.
We now know that the unreachable and unusable objects are available for
garbage collection but the garbage collection process doesn’t happen instantly.
Which means once the objects are ready for garbage collection they must to
have to wait for JVM to run the memory clean-up program that performs
garbage collection.
We can request to JVM for garbage collection by calling System.gc() method.
59
Garbage Collection in Java
Advantage of Garbage Collection
It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM)
so we don't need to make extra efforts.
60
Garbage Collection -The finalize( ) Method
When no references to an object exist, that object is assumed to be no longer
needed, and the memory occupied by the object can be reclaimed. Java handles
deallocation for you automatically.
Sometimes an object will need to perform some action when it is destroyed.
To handle such situations, Java provides a mechanism called finalization.
By using finalization, you can define specific actions that will occur when an
object is just about to be reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the finalize( ) method.
61
Garbage Collection -The finalize( ) Method
The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( )
method, you will specify those actions that must be performed before an object is destroyed.
The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or
indirectly through other referenced objects.
63
Lexical issues
Whitespace
Java is a free-form language. This means that you do not need to follow any special
indentation rules.
There should be at least one whitespace character between each token that was not
already delineated by an operator or separator.
In Java, whitespace is a space, tab, or newline.
White space in Java is used to separate tokens in the source file. It is also used to improve
readability of the source code.
Eg: int i = 0;
64
Lexical issues
Identifiers
Java Identifiers are the user-defined names of variables, methods, classes, arrays,
packages, and interfaces.
An identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.
They must not begin with a number.
Again, Java is case-sensitive, so VALUE is a different identifier than Value.
Some examples of valid identifiers are
AvgTemp, count, a4..
65
Lexical issues
Identifiers
Identifier must follow some rules.
All identifiers must start with either a letter( a to z or A to Z ) or currency
character($) or an underscore.
They must not begin with a digit.
After the first character, an identifier can have any combination of characters.
A Java keywords cannot be used as an identifier.
Identifiers in Java are case sensitive, foo and Foo are two different
identifiers.
They can be any length Eg: int a; char name;
66
Lexical issues
Constants or Literals
Literals or Constants are fixed values of a particular type of data, which cannot
be modified in a program.
Literals are constant variables with fixed values.
For example, here are some literals:
Eg int num = 100;
float num = 88.9;
char example = ‘c’
String str = “hai”
boolean b = false;
67
Lexical issues
Comments
As mentioned, there are three types of comments defined by Java. You have already seen
two: single-line and multiline.
The third type is called a documentation comment. This type of comment
is used to produce an HTML file that documents your program.
The documentation comment begins with a /** and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon.
68
Lexical issues
Separators
69
Lexical issues
The Java Keywords
Keywords in Java are predefined or reserved words that have special meaning to the Java
compiler.
Each keyword is assigned a special task or function and cannot be changed by the user.
These keywords, combined with the syntax of the operators and separators, form the
foundation of the Java language.
These keywords cannot be used as names for a variable, class, or method.
The keywords const and goto are reserved but not used.
In addition to the keywords, Java reserves the following: true, false, and null. These are
values defined by Java.
You may not use these words for the names of variables, classes, and so on.
70
Lexical issues
The Java Keywords
71
Lexical issues
Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a
result.
• Unary Operator
• Arithmetic Operator
• shift Operator
• Relational Operator
• Bitwise Operator
• Logical Operator
• Ternary Operator
• Assignment Operator 72