Module 1
Module 1
Module 1
I:Introduction to Java: Structure of a simple java program; Java programming Environment
and Runtime Environment (Command Line & IDE); Java compiler; Java Virtual Machine;
Primitive Data types and Wrapper Types; Casting and Autoboxing; Arrays; Strings; Vector
class; Operators - Arithmetic, Bitwise, Relational, Boolean Logical, Assignment, Conditional
(Ternary); Operator Precedence; Control Statements - Selection Statements, Iteration
Statements and Jump Statements; Functions; Command Line Arguments; Variable Length
Arguments;
II:OOP Concepts :- Data abstraction, encapsulation, inheritance, polymorphism, Procedural
and object oriented programming paradigm; Microservices.
I: INTRODUCTION TO JAVA
1
PBCST304 OBJECT ORIENTED PROGRAMMING
● 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
● Java is an object oriented language which gives a clear structure to programs and allows
code to be reused.
● Reduce the development costs.
● As Java is close to languages like C++ and C#
Features of Java
Features of java is also known as Java buzzwords
1) Simple
● Java syntax is based on C++ (so it is easier for programmers to learn it after 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.
2
PBCST304 OBJECT ORIENTED PROGRAMMING
2)Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organise our software as a combination of different types of objects that
incorporate both data and behaviour.
3) Platform Independent
Java is a write once, run anywhere language.
4)Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java programs runs on JRE(Java Runtime Environment) and no interaction with our system
OS
5)Robust
Meaning of Robust is strong. Java is robust because:
● Strong memory management.
● Lack of pointers that avoids security problems.
● Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
● Exception handling and the type checking mechanism in Java.
6)Architecture-neutral
● Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
7)Portable
● Java is portable because it facilitates you to carry the Java byte code to any platform. It
doesn't require any implementation.
8)High-performance
● Java is faster than other traditional interpreted programming languages because Java
byte code is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++).
● Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
9)Distributed
● Java is distributed because it facilitates users to create distributed applications in Java.
● RMI and `EJB are used for creating distributed applications. Compared to other
languages it is easy to create network connections in Java.
3
PBCST304 OBJECT ORIENTED PROGRAMMING
10)Multi-threaded
● A thread is like a separate program, executing concurrently.
● 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 multimedia, Web applications, etc.
11)Dynamic
● Java is a dynamic language.
● · It supports the dynamic loading of classes.
● It means classes are loaded on demand.
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
There are three types of comments that Java supports
1. Single line Comment //This is single line comment
4
PBCST304 OBJECT ORIENTED PROGRAMMING
Package Statement
Import Statement
If you want to use a class of another package, then you can do this by importing it
directly into your program.
Many predefined classes are stored in packages in Java
We can import a specific class or classes in an import statement.
Examples:
import java.util.Date; //imports the date class
import java.applet.*; /*imports all the classes from the java applet package*/
Interface Statement
Class Definition
The main method is from where the execution actually starts and follows the order
specified for the following statements
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.
5
PBCST304 OBJECT ORIENTED PROGRAMMING
Example
A simple java program to print hello world
public class Hello
{ //main method declaration
public static void main(String[] args)
{
System.out.println("hello world");
}
}
String[] args
System.out.println();
Source File
6
PBCST304 OBJECT ORIENTED PROGRAMMING
● When you compile the Hello.java file then the compiler creates a .class file
● .class file is created with the name Hello.class
● Hello.class contains byte codes
Byte code (.class file) is a specialised set of instructions that JVM can read. Thus this .class
file consisting of byte code can be transported to another system, irrespective of the operating
system it has, and could be executed comfortably without any issue.
● This is why Java is a portable language.
● Because of the same reason java is also popularly known as Write once, run anywhere
(WORA) language.
● JVM is capable of reading, verifying the bytecode.
Internal working during run time
During run or execution time following tasks are performed within JVM:
● Class loader loads the .class files containing bytecode to the memory.
● Next the bytecode is verified and checked for any errors or bugs which may result in
the program exhibiting anomalous behaviour.
● At last, the just-in-time compiler converts the bytecode into machine code.
7
PBCST304 OBJECT ORIENTED PROGRAMMING
JVM,JRE,JDK
JAVA VIRTUAL MACHINE
JVM is a virtual machine which is capable of reading the .class file that contains bytecode.
In java, the compiler produces bytecode during compilation which can be run on any system
that has JVM installed on it. This results in making java a portable programming language. It
can be written on any system and run-on different systems easily irrespective of the operating
system. Thus, java is also referred to as write once, run anywhere.
8
PBCST304 OBJECT ORIENTED PROGRAMMING
JDK comprises JRE and other tools that help in developing, debugging & monitoring the java
application.
9
PBCST304 OBJECT ORIENTED PROGRAMMING
● Java document
● The Java Development Kit (JDK) is a software development environment which is used
to develop Java applications and applets.
● It contains JRE + development tools.
● It physically exists.
● The JDK contains a private Java Virtual Machine (JVM) and a few other resources such
as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.
JAVA COMPILER
Java is compiled language. But it is very different from traditional compiling in the way that
after compilation source code isconverted to byte code. •Javac is the most popular Java
compiler • Java has a virtual machine called JVM which then converts bytecode to target code
of machine on which it is run. • JVM performs like an interpreter. It doesn’t do it alone, though.
Ithas its own compiler to convert the byte code to machine code. This compiler is called Just
In Time or JIT compiler.
JAVA APPLET
An applet is a special kind of Java program that is designed to betransmitted over the Internet
and automatically executed by aJava-compatible web browser • It runs inside the web browser
and works at client side • Applets are used to make the web site more dynamic andentertaining
• Applets are not stand-alone programs. Instead, they run withineither a web browser or an
applet viewer. JDK provides astandard applet viewer tool called applet viewer. • In general,
execution of an applet does not begin at main()method.
10
PBCST304 OBJECT ORIENTED PROGRAMMING
Wrapper data types are class representations of primitive data types. For each primitive data
type, there is a corresponding wrapper class:
Wrapper classes provide additional functionality and methods that are not available in the
primitive data types. For example, they allow you to perform operations such as parsing,
formatting, and converting values. Wrapper classes are also used when you need to work with
collections, such as ArrayList or HashMap, as these collections can only store objects, not
primitive data types.
Variables In JAVA
11
PBCST304 OBJECT ORIENTED PROGRAMMING
• Variable in Java is a data container that stores the data values during Java program execution.
1. Variable Declaration
2. Variable Initialization
1. Variable Declaration
float pi;
double d;
2. Variable Initialization
float pi = 3.14f;
char a = ’v’;
12
PBCST304 OBJECT ORIENTED PROGRAMMING
Types of variables
method.
OPERATORS
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulation.
Java operators can be divided into following categories:
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
Arithmatic Operation
13
PBCST304 OBJECT ORIENTED PROGRAMMING
Relational Operators
14
PBCST304 OBJECT ORIENTED PROGRAMMING
Bitwise Operator
15
PBCST304 OBJECT ORIENTED PROGRAMMING
Logical Operators
Assignment Operators
16
PBCST304 OBJECT ORIENTED PROGRAMMING
OPERATOR PRECEDENCE
•Evaluate 2*x-3*y ?
17
PBCST304 OBJECT ORIENTED PROGRAMMING
To answer these questions satisfactorily one has to understand the priority or precedence of
operations.
Prepared
Precedence order - When two operators share an operand the operator with the higher
precedence goes first.
• Associativity - When an expression has two operators with the same precedence, the
expression is evaluated according to its associativity.
Evaluate i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8
i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: *
i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i = 1 + 1+ 8 - 2 + 0 operation: /
i = 2 + 8- 2 + 0 operation: +
18
PBCST304 OBJECT ORIENTED PROGRAMMING
i = 10 - 2 + 0 operation: +
i = 8 + 0 operation : -
i = 8 operation: +
SELECTION STATEMENTS
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
Also called decision making statements
Java supports various selection statements, like if, if-else and switch
if statement
if-else statement
nested if statement
if-else-if ladder
If statement
Use the if statement to specify a block of Java code to be executed if a condition is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
if-else Statement
if-else statement also tests the condition. It executes the if block
if condition is true otherwise else block is executed.
Syntax
19
PBCST304 OBJECT ORIENTED PROGRAMMING
if (condition)
}
else
20
PBCST304 OBJECT ORIENTED PROGRAMMING
Example
if else if ladder
Syntax
if (condition)
21
PBCST304 OBJECT ORIENTED PROGRAMMING
else if (condition)
{
else
switch case
The if statement in java, makes selections based on a single true or false condition. But switch
case have multiple choice for selection of the statements
It is like if-else-if ladder statement
• Matching each expression with case Once it match, execute all case from where it matched.
• Use default when expression does not match with any case
Syntax
22
PBCST304 OBJECT ORIENTED PROGRAMMING
• When a break statement is encountered, execution branches to the first line of code that
follows the entire switch statement
• The break statement is optional. If you omit the break, execution will continue on into the
next case.
• A loop repeatedly executes the same set of instructions until a termination condition is met.
23
PBCST304 OBJECT ORIENTED PROGRAMMING
While Loop
In while loop first checks the condition if the condition is true then control goes inside the loop
body otherwise goes outside of the body.
Syntax
while (condition)
do...while loop
A do while loop is a control flow statement that executes a block of code at least once, and
then repeatedly executes the block, or not, depending on a given condition at the end of the
block (in while).
Syntax
do {
// code block to be executed
24
PBCST304 OBJECT ORIENTED PROGRAMMING
} while (condition);
for loop
For Loop is used to execute set of statements repeatedly until the condition is true.
Syntax
25
PBCST304 OBJECT ORIENTED PROGRAMMING
Jump statements
Java Break Statement
The Java continue statement is used to continue the loop The continue statement is used
in loop control structure when you need to jump to the next iteration of the loop
immediately
26
PBCST304 OBJECT ORIENTED PROGRAMMING
It continues the current flow of the program and skips the remaining code at the
specified condition.
In case of an inner loop, it continues the inner loop only.
ARRAY
• An array is a collection of similar data types.
• It is also known as static data structure because size of an array must be specified at the time
of its declaration.
• Array in Java is index-based, the first element of the array is stored at the 0th index
Java provides the feature of anonymous arrays which is not available in C/C++.
• Random access: We can get any data located at any index position.
Features of Array
27
PBCST304 OBJECT ORIENTED PROGRAMMING
• Multidimensional Array
Array Declaration
Syntax: datatype[ ] arrayname;
char[ ] name;
short[ ] arr;
long[ ] arr;
Initialization of Array
new operator is used to initializing an array.
Array Declaration
28
PBCST304 OBJECT ORIENTED PROGRAMMING
STRING
Strings are used for storing text
A String variable contains a collection of characters surrounded by double quotes
Eg: Create a variable of type String and assign it a value
String greeting = "Hello";
Output
Hello
String Length
• The length of a string can be found with the length() method
29
PBCST304 OBJECT ORIENTED PROGRAMMING
Output
HELLO WORLD
hello world
Output 7
String Concatenation
• The + operator can be used between strings to combine them. This is called concatenation
concat() method
30
PBCST304 OBJECT ORIENTED PROGRAMMING
Command-Line Arguments
• Sometimes we want to pass information into a program when we run it. This is accomplished
by passing command-line arguments to main( ).
• The main method can receive string arguments from the command line
• To access the command-line arguments inside a Java program is quite easy— they are stored
as strings in a String array passed to the args parameter of main( ).
• The first command-line argument is stored at args[0], the second at args[1], and so on.
31
PBCST304 OBJECT ORIENTED PROGRAMMING
1)Object
● Any entity that has state and behaviour is known as an object. It can be physical or logical.
● Example: A dog is an object because it has states like colour, name, breed, etc. as well as
behaviours like wagging the tail, barking, eating, etc.
● A dog is an object because it has states like colour, name, breed, etc. as well as behaviours
like wagging the tail, barking, eating, etc.
32
PBCST304 OBJECT ORIENTED PROGRAMMING
2)Class
● Collection of objects is called class. It is a logical entity.
● A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
3)Inheritance
Inheritance is a mechanism in which one class acquires the property of another class.
With inheritance, we can reuse the fields and methods of the existing class.
● As we know, a child inherits the properties from his parents. A similar concept is followed in
Java, where we have two classes:
● A class which inherits the properties is known as Child Class whereas a class whose
properties are inherited is known as Parent class
Inheritance Syntax:
class Subclass extends superClass
4)Encapsulation
● Encapsulation is a process of wrapping code and data together into a single unit, for example,
a capsule which is mixed of several medicines.
● In encapsulation, a class's variables are hidden from other classes and can only be accessed
by the methods of the class in which they are found
● We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
33
PBCST304 OBJECT ORIENTED PROGRAMMING
Syntax:
private <Data_Members>;
private <Data_Methods>;
· Security
Flexibility
5)Polymorphism
Polymorphism is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
● Compile-time polymorphism
● Runtime polymorphism.
We can perform polymorphism in java by method overloading and method overriding.
polymorphism.
What is a class?
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
34
PBCST304 OBJECT ORIENTED PROGRAMMING
field;
method;
What is an object?
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Syntax:
ClassName object = new Constructor();
35
PBCST304 OBJECT ORIENTED PROGRAMMING
Using the new keyword is the most popular way to create an object or instance of the class.
When we create an instance of the class by using the new keyword, it allocates memory (heap)
for the newly created object and also returns the reference of that object to that memory
Constructors
Constructor is a block of codes similar to the method. It is called when an instance of the class
is created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new () keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
2. Parameterized constructor
Default Constructor
A constructor is called a "Default Constructor" when it doesn't have any parameter.
Purpose:
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Syntax:
class name(){}
Example
class Fruit
Fruit ()
36
PBCST304 OBJECT ORIENTED PROGRAMMING
System.out.println("Fruit is created");
//main method
Parameterized Constructor
Purpose:
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
Example
class Fruit
//main method
37
PBCST304 OBJECT ORIENTED PROGRAMMING
Access Modifiers
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specify the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
● Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
● Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
● Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
● Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronised, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
38
PBCST304 OBJECT ORIENTED PROGRAMMING
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Keyword
this keyword
● this is a reference variable that refers to the current object.
39
PBCST304 OBJECT ORIENTED PROGRAMMING
int value;
Invoking current class methods: this.methodName() can be used to explicitly call another
method within the same class. While often optional, it enhances clarity
// ...
public Rectangle() {
40
PBCST304 OBJECT ORIENTED PROGRAMMING
this.x = x;
this.y = y;
this.width = width;
this.height = height;
41