Share Unit 1- Basic concept of object-oriented-programming.ppt

hannahrroselin95 49 views 153 slides Aug 20, 2024
Slide 1
Slide 1 of 153
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153

About This Presentation

Javanu


Slide Content

UNIT 1
FUNDAMENTALS OF OBJECT-
ORIENTED PROGRAMMING
Basic Concepts Of Object Oriented Programming
And Java Environment
By
Hannah Roseline
Assistant Professor

Introduction To Object Oriented Programming:
Object-oriented programming (OOP) is a programming paradigm using
"objects" – data structures consisting of data fields and methods together
with their interactions – to design applications and computer programs.
Programming techniques may include features such as data abstraction,
encapsulation, messaging, modularity, polymorphism, and inheritance.
Many modern programming languages now support OOP.
OOP Which form the heart of java Language.
Definition of OOP:
Object- oriented programming is an approach that provides a way of
modularizing program by creating partitioned memory area for both data
and function that can be used as templates for creating copies of such
modules
On demand.

Programming Paradigm :
A programming paradigm is a fundamental style of computer programming.
Paradigms differ in the concepts and abstractions used to represent the
elements of a program (such as objects, functions, variables, constraints,
etc.) and the steps that compose a computation (assignment, evaluation,
continuations, data flows, etc.).
The combination of data and method make up an object.

Basic Concept Of OOP:
Object:
Objects are the basic runtime entities in an object oriented system. They
may represent a person, a place, a bank account, a table of data or any item
that the program has to handle.
An object is an instance of class that allows programmes to use variable and
method inside the class

Object:
•Object is an run time entity.
•Is an Instance of class
•Represents a Place ,Person ,anything that have some attributes.

Class:
•Object contains data, and code to manipulate that
data. The entire set of data and code of an object
can be made a user- defined data type with the help
of a class
•A class is a blueprint or template for declaring and
creating object.

•A Class is a 3-Compartment Box encapsulating Data
and Functions
•Class name (or identifier): identifies the class.
•Data Members or Variables (or attributes,states,
fields): contains the static attributes of the class.
• Member Functions (or methods, behaviours,
operations):
Contains the dynamicoperations of the class.

Data Encapsulation:
The wrapping up of data and functionsinto asingle unit is known as
encapsulation.
Thedata isnotaccessibleto the
outside world, onlythose function which are wrapped in the
can access it.
These functions provide the interface between the object’s data and
the program.
This insulation of the data from direct access by the program is
called data hiding or information hiding.

Data Abstraction
Abstraction refers to the act of representing essential features
without including the background details or explanations.
Since classes use the concept of data abstraction, they are known
as abstract data types (adt)

Data Encapsulation And Abstraction:
•Data encapsulation, sometimes referred to as data hiding.
•Data Encapsulation and Data Abstraction is one of the most
striking feature of object oriented programming.
•The wrapping up of data and code into a single unit is called
data encapsulation. The data is not accessible to the outside
world only those functions which are wrapped into a class can
only access the private data of the class.

Inheritance :
•Inheritance is one of the most striking feature of object oriented
programming.
•Inheritance is the process by which one class can acquire the
properties of another class.
•The new classes, known as subclasses (or derived classes), inherit
attributes and behavior of the pre-existing classes, which are referred
to as superclasses (or ancestor classes). The inheritance relationships
of classes gives rise to a hierarchy
•Inheritance is the process by which objects of one class acquire the
properties of objects of another class
•In OOP, the concept of inheritance provides the idea of reusability.
This means we can add additional features to an existing class
without modifying it.

•A superclass, base class, or parent class is a class from which
other classes are derived. The classes that are derived from a
super class are known as child classes, derived classes, or
subclasses.
•In object-oriented programming (OOP), inheritance is a way to
compartmentalize and reuse code by creating collections of
attributes and behaviors called objects which can be based on
previously created objects.

Polymorphism:
Polymorphism, a Greek term means to ability to take more than
one form.
An operation may exhibits different behaviors in different
instances. The behavior depends upon the type of data used in the
operation.
For example consider the operation of addition for two numbers;
the operation will generate a sum. If the operands are string then
the operation would produce a third string by concatenation.
The process of making an operator to exhibit different behavior in
different instances is known operator overloading

Benefits Of OOP
OOP offers several benefits to both the program designer & the user
Through inheritance, we can eliminate redundant code and extend the
use of existing class
We can build programs from the standard working module the
communicate with one another, rather than having to start writing code
from scratch. This leads to saving of development time & higher
productivity.
The principle of data hiding helps the programmer to build & secure
programs that cannot be invaded by code in other parts of the program.
It is possible to map objects in the problem domain to those in the
program
It is easy to partition the work in a project based on objects
The data-centered design approach enables us to capture more details
of a model in implementable form.
•.

Object-oriented systems can be easily upgraded from small to
large systems.
Message passing techniques for communication between objects
makes the interface descriptions with external systems much
simpler.
Software complexity can be easily managed .
While it is possible to incorporate all these features in an object-
oriented system, their importance depends on the type of the
project and the preference of the programmer. There are a number
of issues that need to be tackled to reap some of the benefits stated
above. For instance, object libraries must be available for reuse.
The technology is still developing and current productsmaybe
supersededquickly. Strict controls and protocols need to be
compromised

Application of OOP:
•Real-business systems are often much more complex and
contain many more objects with complicated attributes and
methods. OOP is useful in these types of applications because
it can simplify a complex problem. The promising areas for
application of OOP include:
Real-time systems
Simulation and modeling
Object-oriented databases
Hypertext, hypermedia and expertext
Al and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAM/CAD systems(computer Aided manufacturing)
(computer aided design).

About java:

Java Features:

Java and c++:

Java Environment:

Java development kit:

Application programming
interface
•Application programming interface(API) includes
hundreds of classes and methods grouped into several
functional package.
•Language support Package:
A collection of classes and methods required for
implementing basic features of java
Utilities Package:
A collection of class to provide utility function such as
date and time function.

•Input/Output Package:
A collection of classes required for input and output manipulation.
Network Package:
A collection of classes for communicating with other computers via
internet.
Applet Package:
This includes a set of classes that allows us to create Java applet.
Java Virtual machine:
It is a program that interprets the intermediate java byte code and
generate the desired output
Runtime class Libraries:
These are a set of core class libraries that are required for the
execution of java program

•User interface Toolkit:
AWT and swing are the examples of toolkit that support
varied input methods for the users to interact with the
application program.
Deployment Technologies:
Java plug-in: Enable the execution of a java applet on
the browser.
Java Web start: User can launch an application directly
from the web browser without going through the
installation procedure.

Overview of Java:
Introduction:
Java is a object-oriented programming language.
There are two types of java program,
 Stand alone application
 Web applets
Stand alone application:
A type of software program that is designed to run on a
single computer or local machine of the user, without the need
for a server or internet connection.
Executing a stand alone java program involves two steps,
• Compiling source code into byte code using javac
compiler.
• Executing the bytecode program using java interpreter.

Web Applets:
An applet is
 a small program that runs within an
application. Applets are commonly used to make
otherwise static Web pages more interactive. Examples
include animated graphics, games, configurable bar
charts and scrolling messages. Applets also play an
important role in network computers (NCs).

Simple Java Program:

Class Declaration:
•Declares the name of the class along with other attributes such as
the class's superclass, and whether the class is public, final, or
abstract.
 
Opening Brace:
Every Class Definition in java begings with an opening
brace”{“ and ends with a matching closing brace “}” in last line.
The Main Line:
The Java main method is
 the entry point of any Java application.
The most common method to call main is public static void
main(String[] args) It's the starting point where the Java Virtual
Machine (JVM) begins executing your program.

Public:
The public keyword is
 an access modifier used for classes, attributes, methods
and constructors, making them accessible by any other class.
Static:
•When you declare a variable or a method as static,
 it belongs to the class,
rather than a specific instance.
 
Void:
•In Java, the void keyword is
 a reserved type used mainly to specify that a
method does not return any data type.
•Println:
A println() in Java is also
 utilised to display a text on the console,
which is the parameter to this method in String. This method also enables
printing the text on the console, and the cursor remains at the start of the
following line at the console.

Java Program Structure:

•Java is an
 
object-oriented programming,
 
platform-
independent, 
and 
secure 
programming language that
makes it popular.
•Using the Java programming language, we can develop a
wide variety of applications. So, before diving in depth,
it is necessary to understand the
 
basic structure of Java
program 
in detail.
•In this section, we have discussed the basic
 
structure of
a Java program. At the end of this section, you will able
to develop the
 
Hello world Java program, easily.

Documentation
Section
•The documentation section is an important section but optional for a Java program.
It includes
 
basic information 
about a Java program. The information includes
the
 
author's name, date of creation, version, program name, company
name, 
and 
description 
of the program. It improves the readability of the program.
Whatever we write in the documentation section, the Java compiler ignores the
statements during the execution of the program. To write the statements in the
documentation section, we use
 
comments. The comments may be
 
single-line,
multi-line, 
and 
documentation 
comments.
•Single-line Comment: 
It starts with a pair of forwarding slash 
(//). For example:
1.//First
 Java Program
 
 
•Multi-line Comment: 
It starts with a 
/* 
and ends with 
*/. 
We write between these
two symbols. For example:
1./*It
 is an example of
 
2.multiline
 comment*/
 
 
•Documentation Comment: 
It starts with the delimiter 
(/**) 
and ends with 
*/.
 

Package
Declaration
•The package declaration is optional. It is placed just after the
documentation section. In this section, we declare the
 
package
name 
in which the class is placed. Note that there can be 
only one
package 
statement in a Java program. It must be defined before any
class and interface declaration. It is necessary because a Java class can
be placed in different packages and directories based on the module
they are used. For all these classes package belongs to a single parent
directory. We use the keyword
 
package 
to declare the package name.
For example:
1.package 
javatpoint; 
//where
 javatpoint is the package name
 
 
2.package 
com.javatpoint; 
//
where
 com is the root directory and javatpoint is the subdirectory
 
 

Import
Statements
•The package contains the many predefined classes and interfaces. If
we want to use any class of a particular package, we need to import
that class. The import statement represents the class stored in the other
package. We use the
 
import 
keyword to import the class. It is written
before the class declaration and after the package statement. We use
the import statement in two ways, either import a specific class or
import all classes of a particular package. In a Java program, we can
use multiple import statements. For example:
1.import 
java.util.Scanner; 
//it
 imports the Scanner class only
 
 
2.import 
java.util.*; 
//it
 imports all the class of the java.util package
 
 

Interface Section
•It is an optional section. We can create an
 
interface 
in this section if
required. We use the
 
interface 
keyword to create an interface.
An
 
interface 
is a slightly different from the class. It contains
only
 
constants 
and 
method 
declarations. Another difference is that it
cannot be instantiated. We can use interface in classes by using
the
 
implements 
keyword. An interface can also be used with other
interfaces by using the
 
extends 
keyword. For example:
1.interface 
car  
2.{
  
3.void 
start();  
4.void 
stop();  
5.}
  

Class Definition
•In this section, we define the class. It is
 
vital 
part of a Java
program. Without the
 
class, we cannot create any Java program. A
Java program may conation more than one class definition. We use
the
 
class 
keyword to define the class. The class is a blueprint of a
Java program. It contains information about user-defined methods,
variables, and constants. Every Java program has at least one class
that contains the main() method. For example:
1.class 
Student 
//class
 definition
 
 
2.{
  
3.}
  

Main Method Class
•In this section, we define the
 
main() method. 
It is essential for all
Java programs. Because the execution of all Java programs starts
from the main() method. In other words, it is an entry point of the
class. It must be inside the class. Inside the main method, we create
objects and call the methods. We use the following statement to
define the main() method:
1.public static void 
main(String args[])  
2.{
  
3.}
  

Java Tokens:
•In Java, the program contains classes and methods. Further, the methods
contain the expressions and statements required to perform a specific
operation. These statements and expressions are made up of
 tokens
.
In other words, we can say that the expression and statement is a set
of
 
tokens. The tokens are the small building blocks of a Java
program that are meaningful to the
 
Java 
compiler.
Further, these two
components contain variables, constants, and operators. In this section,
we will discuss
 
what is tokens in Java.
What is token in Java?
•The Java compiler breaks the line of code into text (words) is
called
 
Java tokens. These are the smallest element of the
 
Java program.
The Java compiler identified these words as tokens. These tokens are
separated by the delimiters. It is useful for compilers to detect errors.
Remember that the delimiters are not part of the Java tokens.

Types of Tokens
•Keywords
•Identifiers
•Literals
•Operators
•Separators
•Comments

Keywords: 
These are the 
pre-defined 
reserved words of any
programming language. Each
 
keyword 
has a special
meaning. It is always written in lower case, because java is
case-sensitive. Java provides the following keywords:
01. Abstract 02. Boolean 03. Byte 04. Break 05. Class
06. Case 07. Catch 08. Char 09. Continue 10. Default
11. Do 12. Double 13. Else 14. Extends 15. Final
16. Finally 17. Float 18. For 19. If 20. Implements
21. Import 22. Instanceof 23. Int 24. Interface 25. Long
26. Native 27. New 28. Package 29. Private 30. Protected
31. Public 32. Return 33. Short 34. Static 35. Super
36. Switch37. Synchronized 38. This 39. Thro 40. Throws
41. Transient 42. Try 43. Void 44. Volatile 45. While
46. Assert 47. Const 48. Enum 49. Goto 50. Strictfp

Identifie
r:
•Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. It uses letters, underscores, or a dollar sign as the first
character. The label is also known as a special kind of identifier that is used in the
goto statement. Remember that the identifier name must be different from the
reserved keywords. There are some rules to declare identifiers are:
•The first letter of an identifier must be a letter, underscore or a dollar sign. It
cannot start with digits but may contain digits.
•The whitespace cannot be included in the identifier.
•Identifiers are case sensitive.
•Some valid identifiers are:
1. PhoneNumber
  
2.PRICE
  
3.radius
  
4.a
  
5.a1
  
6._phonenumber
  
7.$circumference
  
8.jagged_array
 

Literals:
 
•In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc.
It is defined by the programmer. Once it has been defined cannot be changed. Java
provides five types of literals are as follows:
•Integer
•Floating Point
•Character
•String
•Boolean
Literal Type
23 int
9.86 double
false, true boolean
'K', '7', '-' char
"javatpoint" String
null any reference type

Operators: 
•In programming, operators are the special symbol that tells the
compiler to perform a special operation. Java provides different types of
operators that can be classified according to the functionality they provide.
There are eight types of
 
operators in Java, are as follows:
•Arithmetic Operators
•Assignment Operators
•Relational Operators
•Unary Operators
•Logical Operators
•Ternary Operators
•Bitwise Operators
•Shift Operators

Operator Symbols
Arithmetic + , - , / , * , %
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Ternary (Condition) ? (Statement1) : (Statement2);
Bitwise & , | , ^ , ~
Shift << , >> , >>>

Separators
•The separators in Java is also known as
 punctuators
. There are nine separators
in Java, are as follows:
1.separator
 <= ; | , | . | ( | ) | { | } | [ | ]  
•Square Brackets []: 
It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
•Parentheses (): 
It is used to call the functions and parsing the parameters.
•Curly Braces {}: 
The curly braces denote the starting and ending of a code block.
•Comma (,): 
It is used to separate two values, statements, and parameters.
•Assignment Operator (=): 
It is used to assign a variable and constant.
•Semicolon (;): 
It is the symbol that can be found at end of the statements. It
separates the two statements.
•Period (.): 
It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
separator
 <= ; | , | . | ( | ) | { | } | [ | ]  

Java
statement:

Implementing a java
program:
•Create the program by typing it into a text
editor and saving it to a file –
HelloWorld.java.
•Compile it by typing “javac HelloWorld.java”
in the terminal window.
•Execute (or run) it by typing “java HelloWorld”
in the terminal window.

JVM (Java Virtual Machine)
Architecture
1.Java Virtual Machine
2.Internal Architecture of JVM
•JVM (Java Virtual Machine) is an abstract machine.
It is a specification that provides runtime
environment (JRE) in which java bytecode can be
executed.
•JVMs are available for many hardware and
software platforms (i.e. JVM is platform
dependent).

CONSTANTS,VARIABLE AND
DATA TYPE.

Constants, Variable
and Data Types:
Constants:
Constants in java refer to fixed values that
do not change during the execution of a
program.java support several types of
constant.

Integer constants:
An integer constant refers to the sequence of
digits. There are three type of integer, namely
•Decimal Integer.
•Octal Integer.
•Hexadecimal Integer.

Constant
•It is the value that cannot be changed once
assigned. In Java, the constant values are defined
by using the
 
final 
keyword. The final keyword
represents that the value of the variable cannot be
changed. Note that the identifier name must be
in
 
capital 
letters. We can also define constants as
static.
•Syntax:
1.static final 
datatype identifier_name=value;    

Numeric Constants
•Numeric constants are the constants that contains
numerals. It may also have a leading sign and
decimal point.
•Rule to Define Numeric Constants
•Must have at least one digit.
•It should not have comma, space, and another
special symbol.
•It may have positive or negative sign. If no sign is
preceded then the constant assumed positive. It is
optional to preceded a constant with a positive sign.
•There are the following two types of numeric
contestants:

Integer Constants
•A constant that contains digits (0-9) and does not
have decimal point is called integer constants. By
default, it is type of
 
int. There are the following three
types of integer constants:
•Decimal Constants: 
It contains digits between 0 to
9. Note that must not start with 0. For example,
 
898,
67, 66.
•Octal Constants: 
It contains digits between 0 to 7
and must begin with 0. For example,
 
012, 032, 067.
•Hexadecimal Constants: 
It contains digits between
0 to 9 and letters a to f (either in upper or lower case).
It must begin with 0X or 0x. For example,
 
0x23, 0x76,
0X6A, 0XFF

•Fractional Form
•Rules to Define Fractional Form
1.It must have at least one digit.
2.It must have a decimal point
3.It may have positive or negative sign. The default is positive sign and it
is optional.
4.Comma, spaces, or any other symbols are not allowed.
•For example,
 
3.14, -9.1, 0.67.
•Exponential Form
•It is used to represent a real constant when a number is too small
or too large.
•For example, 0.00000149 can be represented as 1.49e-6. The part
of the number before e is called
 
mantissa 
i.e 1.49, whereas, the
part after e is called the
 
exponent 
i.e, 6.

Non-numeric
Constants
•A constant that does not contain digits is called
 
non-
numeric 
constants. There are the following two types of non-
numeric constants:
Character Constants
•A Character constant is a single alphabet, digit or any special
symbol enclosed using single quotes. For example,
 
'Y', 'd', '6', '#',
'&'.
•The maximum length of a character constant is 1 character long. It
means that we cannot put more than one character inside single
quotation marks.
•As we may already know that inside computer memory
everything is stored in binary form. But how character constants
are stored in the memory? It turns out that Every character constant
has a unique integer associated with it.

String Constants
•String constants consist of zero or more
characters enclosed in double quotes (""). At
the end of the string, the null character i.e '\0'
is automatically placed by the compiler. For
example, "hello", " " (denotes blank space),
"111".

Java
Variables
•A variable is a container which holds the value while
the
 
Java program 
is executed. A variable is assigned
with a data type.
•Variable is a name of memory location. There are three
types of variables in java: local, instance and static.
•There are two types of
 
data types in Java: primitive and
non-primitive.

Types of Variables

1) 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.
2) Instance Variable
•A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as
 
static.
•It is called an instance variable because its value is instance-specific
and is not shared among instances.
3) Static variable
•A variable that is declared as static is called a static variable. It cannot
be local. You can create a single copy of the static variable and share it
among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.

Data Types in Java
Data types specify the different sizes and values that
can be stored in the variable. There are two types of
data types in Java:
1.Primitive data types: 
The primitive data types
include boolean, char, byte, short, int, long, float and
double.
2.Non-primitive data types: 
The non-primitive data
types include
 
Classes,
 
Interfaces, and
 
Arrays.

Java Primitive Data
Types
In Java language, primitive data types are the building blocks
of data manipulation. These are the most basic data types
available in
 
Java language.
There are 8 types of primitive data types:
•boolean data type
•byte data type
•char data type
•short data type
•int data type
•long data type
•float data type
•double data type

Boolean Data Type
•The Boolean data type is used to store only two possible values:
true and false. This data type is used for simple flags that track
true/false conditions.
•The Boolean data type specifies one bit of information, but its
"size" can't be defined precisely.
•Example:
1.Boolean
 one = 
false 

Byte Data Type
•The byte data type is an example of primitive data type. It is an
8-bit signed two's complement integer. Its value-range lies
between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
•The byte data type is used to save memory in large arrays
where the memory savings is most required. It saves space
because a byte is 4 times smaller than an integer. It can also be
used in place of "int" data type.
•Example:
1.byte 
a = 
10,
 
byte 
b = -
20 
 

Short Data Type
•The short data type is a 16-bit signed two's complement integer. Its
value-range lies between -32,768 to 32,767 (inclusive). Its minimum
value is -32,768 and maximum value is 32,767. Its default value is 0.
•The short data type can also be used to save memory just like byte
data type. A short data type is 2 times smaller than an integer.
•Example:
1.short 
s = 
10000,
 
short 
r = -
5000 
 

Int Data Type
•The int data type is a 32-bit signed two's complement integer. Its
value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.
•The int data type is generally used as a default data type for
integral values unless if there is no problem about memory.
Example:
1.int 
a = 
100000,
 
int 
b = -
200000 
 

Long Data Type
The long data type is a 64-bit two's complement integer. Its value-
range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum
value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data
type is used when you need a range of values more than those
provided by int.
Example:
1.long a = 100000L, long b = -200000L  

Float Data Type
•The float data type is a single-precision 32-bit IEEE 754 floating
point.Its value range is unlimited. It is recommended to use a
float (instead of double) if you need to save memory in large
arrays of floating point numbers. The float data type should
never be used for precise values, such as currency. Its default
value is 0.0F.
Example:
•float f1 = 234.5f  

Double Data Type
The double data type is a double-precision 64-bit IEEE
754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values
just like float. The double data type also should never
be used for precise values, such as currency. Its default
value is 0.0d.
•Example:
1.double 
d1 = 
12.3 
 

Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range
lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data
type is used to store characters.
Example:
1.char 
letterA = 
'A' 
 

Non-primitive data types in
Java
•Unlike primitive data types, these are not predefined. These are user-
defined data types created by programmers. These data types are used
to store multiple values
•For example, consider an
 
array 
that stores a group of values. Class is
also a primitive type that stores different methods and variables.
Therefore, these are also called as
 
advanced data types 
in Java.
•Whenever a non-primitive data type is defined, it refers a memory
location where the data is stored in heap memory i.e., it refers to
the memory location where an object is placed. Therefore, a non-
primitive data type variable is also called
 
referenced data
type 
or 
simply object reference variable.
•An object reference variable lives on the stack memory and the object
to which it points always lives on the heap memory. The stack holds a
pointer to the object on the heap.
•In Java programming, all non-primitive data types are simply
called objects that are created by instantiating a class.

Types of Non-primitive data
types
•There are five types of non-primitive data types
in Java. They are as follows:
1.Class
2.Object
3.String
4.Array
5.Interface

Declaration of
Variable:
•In java ,variables are the names of storage location.
•After designing suitable variable names we mustdeclare
them to the compiler.
•It tells the compiler what the variable is.
•It specifies what type of data the variable will hold.
•The variable must be declared before it is used in the
program.
•Variable can be used to store a value of any data type.
•Variables are seprated by commas,A declaration
statement must end with a semicolon.

Giving Values to variables:
•By using an assignment statement.
•By using a read statement.
Assignment statement:
A simple method of giving value to a variable
is through the assignment statement.
Example:
Variable name= value;
Initial value = 0;
Final value = 100;

Read Statement
•Once the class is created, you can use
readLine() with the syntax, String line =
reader. readLine(); This combination allows
you to read a line from a file or any other
input source.

The Scope of Variables in Java
•Variables are an essential part of data storage and
manipulation in the realm of programming. In addition to
making values available within a programme, they offer a
means of holding them temporarily. Not all variables,
though, are made equally. Each variable has a scope that
specifies how long it will be seen and used in a
programme. Java code must be efficient and error-free,
which requires an understanding of variable scope. The
scope of variables in Java will be explored in this section,
along with their effects on how programmes are executed.
•There are four scopes for variables in Java: local, instance,
class, and method parameters. Examining each of these
scopes in more detail will be helpful.

Local Variables
•Local variables are those that are declared inside
of a method, constructor, or code block. Only the
precise block in which they are defined is
accessible. The local variable exits the block's
scope after it has been used, and its memory is
freed. Temporary data is stored in local variables,
which are frequently initialised in the block where
they are declared. The Java compiler throws an
error if a local variable is not initialised before
being used. The range of local variables is the
smallest of all the different variable types.

Instance
Variables:
•Within a class, but outside of any methods, constructors, or
blocks, instance variables are declared. They are accessible to all
methods and blocks in the class and are a part of an instance of
the class. If an instance variable is not explicitly initialised, its
default values are false for boolean types, null for object
references, and 0 for numeric kinds. Until the class instance is
destroyed, these variables' values are retained.
public class 
Circle {  
 
  
double 
radius; 
//
 instance variable
 
 
 
 
public double 
calculateArea() {  
 
    
return 
Math.PI * radius * radius;  
 }
  
}
  

Class Variables (Static Variables)
•In a class but outside of any method, constructor, or block, the
static keyword is used to declare class variables, also referred to
as static variables. They relate to the class as a whole, not to
any particular instance of the class. Class variables can be
accessed by using the class name and are shared by all instances
of the class. Like instance variables, they have default values,
and they keep those values until the programme ends.
public class 
Bank {  
 static double 
interestRate; 
//
 class variable
 
 
 
 
//
 ...
 
 
}
  

Symbolic constants:
•In Java, a symbolic constant is a named
constant value defined once and used
throughout a program. Symbolic constants
are declared using the final keyword.
•Problem in modifiability of the program.
•Problem in understanding the program

Modifiability
Ability of a system to be able to admit changes due to a
new requirement or by detecting an error that needs to be
fixed.
Understandability:
Developers can become confused about which
abstraction to use when there are two or more
abstractions with identical names or implementation.
Further, duplicate implementations bloat the code. These
factors impact the understandability of the design.

Type casting
•The process of converting the value of a single data
type (such as an integer [int], float, or double) into
another data type.
•Type casting is the process in which the compiler
automatically converts one data type in a program to
another one. Type conversion is another name for
type casting. For instance, if a programmer wants to
store a long variable value into some simple integer
in a program, then they can type cast this long into
the int.

DECISION MAKING AND BRANCHING
•Introduction
• Decision Making with If Statement
• Simple If Statement
•The If…..Else Statement
•Nesting of If….Else Statements
•The Else If Ladder
•The Switch Statement(case)
•The ? : Operator

Introduction:
Branching:
When a program breaks the sequential flow and
jumps to another part of the code, it is called
branching.
Conditional Branching:
When the branching is based on a particular
condition, it is known as conditional branching.
Unconditional Branching:
If branching takes place without any decision, it is
known as unconditional branching.

Java language possesses such decision
making capabilities and supports the
following statements known as control or
decision making statements.
1. if statement
2. switch statement
3. conditional operator statement

The if statement is a powerful decision making
statement and is used to control the flow of execution
of statements. It is basically a two-way decision
statement and is used in conjunction with an expression.
It takes the following form
if (test expression)
It allows the computer to evaluate the expression first and
then, depending on whether the value of the expression
(relation or condition) is ‘true’ or ‘false’, it transfers the
control to a particular statement. This point of program
has two paths to follow, one for the true condition and the
other for the false condition
Decision Making with If Statement

Some examples of decision making, using if statement
are:
1. if (balance is zero)
borrow money

2. if (room is dark)
put on lights
3. if (age is more than
55)
person is retired

The if statement may be implemented in different
forms depending on the complexity of conditions to be
tested.
•1. Simple if statement
•2. if..else statement
• 3. Nested if..else statement
•4. else if ladder

Simple if statement
•It is one of the simplest decision-making statement which is used
to decide whether a block of Java code will execute if a certain
condition is true.
Syntax
if 
(condition) {  
 //
 block of code will execute if the condition is true
 
 
}
  
•If the condition evaluates to true, the code within
 
if
statement 
will execute, but if the condition evaluates to false,
then the code after the end of
 
if statement (after the closing of
curly braces) 
will execute.
•Note: The if statement must be written in the lowercase
letters. The use of Uppercase letters (If or IF) will cause a
JavaScript error.

For example
var
  x = 
78;
  
if 
(x>
70)
 {   
 
  
console.log("x
 is greater"
)
   
}
  

The if….else
statement
•An
 
if….else statement 
includes two blocks that are 
if
block 
and 
else block. 
It is the next form of the control statement,
which allows the execution of JavaScript in a more controlled way.
It is used when you require to check two different conditions and
execute a different set of codes. The
 
else statement 
is used for
specifying the execution of a block of code if the condition is false.
Syntax
if 
(condition)  
 {
  
 
 
//
 block of code will execute if the condition is true
 
 
}
  
 else 
 
 {
  
 
 
//
 block of code will execute if the condition is false
 
 
}
  

If the condition is true, then the statements inside
 
if
block 
will be executed, but if the condition is false, then
the statements of the
 
else block 
will be executed.

For example
Let us try to understand
 
if….else 
statement by the following
example:
var
 x = 
40,
 y=
20;
   
if 
(x < y)   
{
   
 
  
system.out.print(“Y
 is greater"
);
   
}
   
else 
  
{
   
 
 
system.out.print(“X
 is greater"
);
   
}
  

The if….else if…..else statement
It is used to test multiple conditions. The
 
if statement 
can have multiple or
zero
 
else if statements 
and they must be used before using the 
else
statement. 
You should always be kept in mind that the 
else
statement 
must come after the 
else if statements.
Syntax
if 
(condition1)   
{
  
 
 
//
  block of code will execute if condition1 is true
 
 
}
  
 else if 
(condition2)   
{
  
 
 
//
  block of code will execute if the condition1 is false and condition2 is true
 
 
}
   
else 
  
{
  
 
 
//
  block of code will execute if the condition1 is false and condition2 is false
 
 
}
  

Example
var
 a = 
10,
 b = 
20,
 c = 
30;
   
if(
 a > b && a > c) {   
 
  
console.log("a
 is greater"
);
   
}
 
else if(
 b > a && b > c ) {   
 
   
console.log("b
 is greater"
);
   
}
 
else 
{   
 
   
console.log("c
 is greater"
);
   
}
  

The nested if
statement
Syntax
if 
(condition1)   
{
   
Statement
 
1;
 
//It
 will execute when condition1 is true
 
 
if 
(condition2)  
 {
   
Statement
 
2;
 
//It
 will execute when condition2 is true
 
 
}
  
else 
 
{
  
 Statement
 
3;
 
//It
 will execute when condition2 is false
 
 
}
  
}
  

Example
var
 num = 
20;
  
if 
(num > 
10)
  
{
  
if 
(num%
2==0)
  
console.log(
 num+ 
"
 is greater than 10 and even number"
)
;
  
else 
 
console.log(num+
 
"
 is greater than 10 and odd number"
);
 
 
}
  
else 
 
{
  
console.log(num+"
 is smaller than 10"
);
  
}
  
console.log("After
 nested if statement"
);
  

The switch
statement
•It is a multi-way branch statement that is also used for
decision-making purposes. In some cases, the
 
switch
statement 
is more convenient than 
if-else statements. 
It
is mainly used when all branches depend upon the value
of a single variable. It executes a block of code
depending upon the different cases.
•The switch statement 
uses
the
 
break 
or 
default 
keywords, but both of them are
optional. Let us define these two keywords:
•break: 
It is used within the 
switch statement 
for
terminating the sequence of a statement. It is optional to
use. If it gets omitted, then the execution will continue on
each statement. When it is used, then it will stop the
execution within the block.

•default: 
It specifies some code to run when there is no case match.
There can be only a single default keyword in a switch. It is also
optional, but it is recommended to use it as it takes care of
unexpected cases.
•If the condition passed to switch doesn't match with any value in
cases, then the statement under the default will get executed.
•Some points to remember
•There can be one or multiple case values for a switch expression.
•The use of
 
break 
and 
default 
keywords are optional.
•The case statements can only include constants and literals. It
cannot be an expression or a variable.
•Unless you put a break after the code of every block, the execution
will continuously flow into the next block.
•It is not necessary that the default case has to be placed at last in a
switch block.

Syntax
switch(expression){
      
case 
value1:      
 //code
 to be executed;    
 
 
 break;
  
//optional
  
 
 
case 
value2:      
 //code
 to be executed;    
 
 
 break;
  
//optional
  
 
 
......
      
 
     
default:
       
 code
 to be executed 
if 
all cases are not matched;      
}
     

Flowchart

Exampl
e
var
 num = 
5;
   
switch(num)
 {   
 
   
case 0 
: {   
 
     
System.out.println("Sunday");
   
 
     
break;
   
 
  
}
   
 
  
case 1 
: {   
 
   
System.out.println ("Monday");
   
 
   
break;
   
 }
   
 
  
case 2 
: {   
 
   
System.out.println ("Tuesday");
   
 
   
break;
   
 }
      
 
  
case 3 
: {   
 
   
System.out.println ("Wednesday");
   
 
   
break;
   
 }
  
 
  

case 4 
: {   
 
   
System.out.println ("Thursday");
   
 
   
break;
   
 }
   
 
  
case 5 
: {   
 
   
System.out.println ("Friday");
   
 
   
break;
   
 }
   
 
  
case 6 
: {   
 
   
System.out.println ("Saturday");
   
 
   
break;
   
 }
      
 
  
default:
 {   
 
     
System.out.println ("Invalid
 choice"
);
   
 
     
break;
                
 
  
}
   
}
  

Operators in Java
Operator 
in 
Java 
is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
•Unary Operator,
•Arithmetic Operator,
•Shift Operator,
•Relational Operator,
•Bitwise Operator,
•Logical Operator,
•Ternary Operator and
•Assignment Operator.

Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~
!
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |=
<<= >>= >>>=

Looping
•Looping in programming languages is a feature which facilitates the
execution of a set of instructions/functions repeatedly while some
condition evaluates to true. Java provides three ways for executing the
loops. While all the ways provide similar basic functionality, they differ in
their syntax and condition checking time.
Java provides Three types of Conditional statements this second
 type is loop
statement .

while loop: 
A while loop is a control flow statement that
allows code to be executed repeatedly based on a given
Boolean condition. The while loop can be thought of as a
repeating if statement.
 

Syntax
while (boolean condition)
{
loop statements...
}

For Loop
For loop provides a concise way of writing the loop structure.
Unlike a while loop, a for statement consumes the
initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of
looping.
 
For loop in Java iterates a given set of statements
multiple times. The Java while loop executes a set of
instructions until a boolean condition is met.
Syntax:
for (initialization condition; testing condition;increment/decrement)
{
statement(s)
}

DO Statement
•The Java do-while loop is used to iterate a part of
the program repeatedly, until the specified
condition is true. If the number of iteration is not
fixed and you must have to execute the loop at least
once, it is recommended to use a do-while loop.
•Java do-while loop is called an exit control loop.
Therefore, unlike while loop and for loop, the do-
while check the condition at the end of loop body.
The Java do-while loop is executed at least once
because condition is checked after loop body.

DoWhileExample
public class DoWhileExample {    
public static void main(String[] args) {    
   int i=1;    
  do{    
     System.out.println(i);    
  i++;    
  }while(i<=10);    
}    
}    

Output:
1
2
3
4
5
6
7
8
9
10

Infinite loop
One of the most common mistakes while implementing any
sort of looping is that it may not ever exit, that is the loop
runs for infinite time. This happens when the condition fails
for some reason.

Nested Loop:
•Nested loop means a loop statement inside another loop statement.
A nested loop is a (inner) loop that appears in the loop body of
another (outer) loop. The inner or outer loop can be any type:
while, do while, or for. For example, the inner loop can be a while
loop while an outer loop can be a for loop.

Jump Statements in Java
Jumping statements are control statements that transfer
execution control from one point to another point in the
program. There are three Jump statements that are provided
in the Java programming language:
1.Break statement.
2.Continue statement.
3.Return Statement

Break statement
•Using Break Statement to exit a loop:
•In java, the
 
break 
statement is used to terminate the
execution of the nearest looping statement or switch
statement. The break statement is widely used with the
switch statement,
 
for
 
loop,
 
while
 
loop,
 
do-while
 
loop.
 
Syntax:
break;

Continue statement.
•The
 
continue
 
statement pushes the next repetition of the
loop to take place, hopping any code between itself and the
conditional expression that controls the loop.
•he Java continue statement is used to continue the
loop. It continues the current flow of the program
and skips the remaining code at the specified
condition.
•We can use Java continue statement in all types of
loops such as for loop, while loop and do-while
loop.

Return Statement
•The “return” keyword can help you transfer control from one
method to the method that called it. Since the control jumps
from one part of the program to another, the return is also a
jump statement.
•“return”
 
is a reserved keyword means we can’t use it as an
identifier.
•It is used to exit from a method, with or without a value.
•In Java, every method is declared with a return type such
as int, float, double, string, etc.
•These return types required a return statement at the
end of the method. A return keyword is used for
returning the resulted value.

Syntax:
return returnvalue;  

Array
•In Java, all arrays are dynamically allocated. (discussed below)
•Arrays may be stored in contiguous memory [consecutive memory locations].
•Since arrays are objects in Java, we can find their length using the object
property
 
length. This is different from C/C++, where we find length using
sizeof.
•A Java array variable can also be declared like other variables with [] after the
data type.
•The variables in the array are ordered, and each has an index beginning with
0.
•Java array can also be used as a static field, a local variable, or a method
parameter.

An array can contain primitives (int, char, etc.) and object
(or non-primitive) references of a class depending on the
definition of the array. In the case of primitive data types,
the actual values might be stored in contiguous memory
locations(JVM does not guarantee this behavior). In the
case of class objects,
 
the actual objects are stored in a heap
segment.
 

Creating, Initializing, and Accessing an Arrays
One-Dimensional Arrays
•The general form of a one-dimensional array declaration is
-- type var-name[ ];
-- type[] var-name;
An array declaration has two components: the type and the
name.
 
type 
declares the element type of the array. The element type
determines the data type of each element that comprises the array. Like
an array of integers, we can also create an array of other primitive data
types like char, float, double, etc., or user-defined data types (objects of a
class). Thus, the element type for the array determines what type of data
the array will hold.
 

Types of Arrays
One-dimensional Array
•Also known as a linear array, the elements are stored in a single row.
For example:
•In this example, we have an array of five elements. They are stored in a
single line or adjacent memory locations.

Two-dimensional Array
Two-dimensional arrays store the data in rows and columns
•In this, the array has two rows and five columns. The index starts from
0,0 in the left-upper corner to 1,4 in the right lower corner.
•In this Java code, we have a two-dimensional array. We have two rows
and three columns. Brackets separate the rows, and the number of
elements separates the columns. For this, we use two
 for loops: one for
rows and one for each element in the row.
 

How to initialize an array in Java?
Initialize an array using known element values
•If we already know the element values we want stored in the array,
we can initialize the array like this:
myArray = new int[]{0, 1, 2, 3};
Initialize an array using length
•Next, if you do not know the exact data elements you want in your
array when you initialize it, you can instead provide the length of the
array, and it will be populated with default values based on the array
type:
int myArray[] = new int[4];

What are Strings in Java?
•Strings are the type of objects that can store the character
of values and in Java, every character is stored in 16 bits
i,e using UTF 16-bit encoding. A string acts the same as an
array of characters in Java.
string name=“geeks”;
Tags