Object Oriented Programming with Java
Programming
Structures in Java
Rita Nagar
Assistant Professor, CSE Department MPGI
Outlines
1. Final Members
2. Comments
3. Data types
4. Variables
5. Operators
6. Control Flow
7. Arrays & String
Final members
A final member variable in Java is a constant—it
must be initialized once and cannot be modified later.
It is applicable only to a variable, a method, or a
class
Final Variable
When a variable is declared with the final keyword, its value
can’t be changed, essentially, a constant. This also means that
you must initialize a final variable.
Output
Final Method
The final keyword before
the name of a method
indicates that the
method cannot be
overridden by subclasses.
When a method is
declared as the final
method in the parent
class, then any child class
cannot override or modify
the final method in java.
Output
Final Class
In Java, the final class cannot be inherited by another class
Data types
Data Types in Java are defined as specifiers that allocate different
sizes and types of values that can be stored in the variable or an
identifier. Java has a rich set of data types.
Data types in Java can be divided into two parts :
[Link] Data Types :- include integer, character, boolean, and
float
[Link]-primitive Data Types :- include classes, arrays and
interfaces.
Data type Bits Acquired In Memory
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
short 16(2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
Java Tokens
• A token is the smallest element of a program that is
meaningful to the compiler.
• 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.
Types of Tokens
• Literals
• Keywords
• Variables
• Symbolic Constants
Literals
• Any constant value assigned to the variable is called
literal/constant.
• Literals in Java is a representation of boolean, numeric,
character, or string data.
• Literals represent fixed values in a source code.
• Once it has been defined cannot be changed.
Java supports several types of literals
• Integer literals: Used to represent integer values, such as 12, 15
• Floating-point literals: Used to represent floating-point values, such as
3.14159
• Boolean literals: Used to represent boolean values, such as true or false.
• Character literals: Used to represent single characters, enclosed in
single quotes, such as ‘a’ or ‘9’.
• String literals: Used to represent sequences of characters enclosed in
double quotes, such as “Hello, Btech (Sec-B) II semester!”.
• Null literal: Used to represent a reference that does not refer to any
object, represented by the keyword null.
Keywords
• Keywords are reserved words or pre-defined reserved
words in a programming language.
• Examples of keywords in Java include class, public, private,
if, else, while, for, switch, case, break, continue, return, and
static, among others.
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.
Three types of variables in java
Local variable
Instance variable
Static variable
1) Local Variables
Local Variables are a variable that are declared inside the
body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword
.They are defined Outside a method declaration. They are
Object specific and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the
program execution. These variables should be initialized
first, before the initialization of any instance variables.
symbolic constant
• A symbolic constant is a named constant value defined
once and used throughout a program.
• Symbolic constants are declared using the final keyword.
Which indicates that the value cannot be changed once
it is initialized
static final double PRICE=432.78
Scope of variables
• Scope of a variable is the part of the program
where the variable is accessible.
Scope
Method
Block Scope
scope
Method Scope
•Variables declared directly inside a
method are available anywhere in the
method following the line of code in
which they were declared:
Method scope
Block Scope
• A block of code refers to all of the code
between curly braces {}.
• Variables declared inside blocks of code
are only accessible by the code between
the curly braces, which follows the line in
which the variable was declared
Example of block level
class Test
{
public static void main(String args[])
{
for (int x = 0; x < 4; x++)
{
[Link](x);
}
// Will produce error
[Link](x);
}
}
Operators
Java operators are special symbols that perform operations on
variables or values. They can be classified into several
categories based on their functionality.
Types of Operators in Java
[Link] Operators
[Link] Operators
[Link] Operator
[Link] Operators
[Link] Operators
[Link] Operator
[Link] Operators
[Link] Operators
[Link] of operator
Arithmetic operators
Arithmetic operators are used to perform common
mathematical operations like addition, subtraction,
multiplication, and division
Relational operators
Relational Operators in Java are used to comparing two variables for
equality, non-equality, greater than, less than, etc. Java relational operator
always returns a boolean value - true or false.
Operator Description
== is the equality operator. This returns true if both the
operands are referring to the same object, otherwise false.
!= is for non-equality operator. It returns true if both the
operands are referring to the different objects, otherwise
false
< is less than operator.
> is greater than operator.
<= is less than or equal to operator
>= is greater than or equal to operator.
Example
Logical operators
Logical operators are used to perform logical “AND”, “OR”
and “NOT” operations,
Logic gates
Example
Assignment operators
Increment and Decrement operators
Increases the value of
++ Increment ++x
a variable by 1
Decreases the value
-- Decrement --x
of a variable by 1
It will
return 10
It will
return 11
Conditional operator
check the condition and decides the desired result on the basis
of both conditions.
Conditional operator
Conditional AND Conditional OR Ternary Operator
Conditional AND
• The operator is applied between two Boolean expressions. It
is denoted by the two AND operators (&&). It returns true if
and only if both expressions are true, else returns false.
Conditional OR
The operator is applied between two Boolean expressions.
It is denoted by the two OR operator (||). It returns true if
any of the expression is true, else returns false
Example
public class C_O
{
public static void main(String args[])
{
int x=5, y=4, z=7;
[Link](x>y && x>z || y<z);
[Link]((x<z || y>z) && x<y);
}
} true
false
Ternary Operator
• The meaning of ternary is composed of three parts. The
ternary operator (? :) consists of three operands. It is
used to evaluate Boolean expressions. The operator
decides which value will be assigned to the variable. It is
the only conditional operator that accepts three
operands. It can be used instead of the if-else statement.
variable = (condition) ? expression1 : expression2
Example
Bitwise Operator
• Bitwise operators work on binary digits or bits
of input values
• Bitwise operators are used to performing the
manipulation of individual bits of a number.
• They can be used with any integral type (char,
short, int, etc.).
Bitwise operators work on a binary equivalent
of decimal numbers and perform operations
on them bit by bit as per the given operator:
• First, the operands are converted to their binary
representation
• Next, the operator is applied to each binary number
and the result is calculated
• Finally, the result is converted back to its decimal
representation
Bitwise Logical Operators
Bitwise Operator
AND(&) XOR(^) OR(|) NOT(~)
Example
public class op {
public static void main(String[ ] args)
{
int a = 5;
int b = 7;
// bitwise and
// 0101 & 0111=0101 = 5
[Link]("a&b = " + (a & b));
}
}
0101
&0111
0101
Control flow
Java compiler executes the code from top to
bottom. The statements in the code are executed
according to the order in which they appear.
However, Java provides statements that can be
used to control the flow of Java code. Such
statements are called control flow statements.
Types of control flow statements
Control flow statement
Conditional Looping Jump
Statement Statement Statement
Conditional statements in Java
1) if: if statement is the most simple decision-making
statement. It is used to decide whether a certain statement or
block of statements will be executed or not i.e if a certain
condition is true then a block of statements is executed
otherwise not.
Syntax –
Example
class Demo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link](“It is less");
}
}
2) if - else
The if statement tells us that if a condition is true it will execute
a block of statements and if the condition is false , the else
block will execute.
Syntax –
Example code
class IfElseDemo {
public static void main(String args[])
{
int a = 10,b=10;
if (a > b)
[Link](“a is greater");
else
• [Link](" b is greater ");
}
}
Nested if…else
A nested if is an if statement that is the target of another if or
else. Nested if statements mean an if statement inside an if
statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if
statement.
Syntax –
Example
class NestedIfDemo {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i<15) {
if (i < 15)
[Link]("i is smaller than 15");
if (i < 12)
[Link]("i is smaller than 12 too");
} else{
[Link]("i is greater than 15");
}
}
}
if-else-if ladder
It is an extension of the if-else statement in Java. It allows you to
check multiple conditions in a cascading manner and execute
different blocks of code based on the condition that evaluates to
true.
Syntax –
Example
switch statement
The switch statement is a control flow statement that allows to select one
of many code blocks to execute based on the value of a variable or an
expression
Syntax –
Example
class demo {
public static void main (String[] args) {
int num=34;
switch(num){
case 5 : [Link]("It is 5");
break;
case 10 : [Link]("It is 10");
break;
case 34 : [Link]("It is 34");
break;
case 20 : [Link]("It is 20");
break;
default: [Link]("Not present");
}
}
}
Jump statements
Jump statements are used to transfer the control of the program
to the specific statements. In other words, jump statements
transfer the execution control to the other part of the program
Jump
break continue return
Break statement
• It is used to break the current flow of the program and
transfer the control to the next statement outside a loop or
switch statement. However, it breaks only the inner loop in
the case of the nested loop.
• The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
Example
class breakdemo {
public static void main(String[] args)
{
int n = 9;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
[Link](i);
}
}
}
It will break the loop when the value of i becomes 6
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.
•The continue statement in Java never terminates the execution
of any loops.
•It can only work inside the "loop statement".
•The primary job of the "Continue statement" is the iteration of
that specific loop.
•Continue statement assists the bypass of all the other statements
by making them fall under it.
•The nature of the Continue statement is to skip the current
iteration and force for the next one.
Example
Return statement
• The return statement is used only inside the functions or
methods.
• The purpose of using a Return statement is to terminate the
current method of execution and transfer the control to the
next "calling method".
• There are two types of Return statements, which are "Return
with a value" and "Return without a value".
Example
In any method whenever we use return which means that
method is returning value
OUTPUT : Sum = 30
Looping statements
Loops are a block of code that executes itself until
the specified condition becomes false.
Types of looping statements
Looping statement
For while do-while
for - each
For loop
• The Java for loop is used to iterate a part of the program
several times. If the number of iteration is fixed, it is
recommended to use for loop.
Syntax –
•.
• Initialization: It is the initial condition which is executed once
when the loop starts.
• Condition: It is the second condition which is executed each
time to test the condition of the loop. It continues execution until
the condition is false. It must return boolean value either true or
false. It is an optional condition.
• Increment/Decrement: It increments or decrements the variable
value. It is an optional condition
Example code
Advanced for loop
• It iterate through the elements of a collection or array.
• It starts with the keyword for like a normal for-loop.
• Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a
colon, which is then followed by the array name.
• In the loop body, you can use the loop variable you created rather than
using an indexed array element.
• It’s commonly used to iterate over an array or a Collections class (eg,
ArrayList)
Syntax –
Example
Output
Create Pyramid using for loop
Output
Reverse Pyramid
Output
full pyramid
Output
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.
Example
class while_demo { Output
public static void main (String[] args) { 0
int i=0; 1
while (i<=10) 2
3
{ 4
[Link](i); 5
i++; 6
} 7
} 8
9
} 10
do - while
• 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.
• do while loop is similar to while loop with only
difference that it checks for condition after
executing the statements, and therefore is an
example of Exit Control Loop.
Example
Output
public class DoWhiledemo { 0
public static void main(String[] args) { 1
int i=1; 2
do{ 3
4
[Link](i);
5
i++; 6
}while(i<=10); 7
} 8
} 9
10
Print table using loop
Output
Array
Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for each
value.
To declare an array, define the variable type with square
brackets:
Advantage of Java Array
• Code Optimization: It makes the code
optimized, we can retrieve or sort the data
easily.
• Random access: We can get any data located
at any index position.
Disadvantage of Java Array
• Size Limit: It can store only fixed size of
elements in the array. It doesn't grow its size at
runtime.
• To solve this problem, collection framework is
used in java.
Types of Array
Array
Single
Multidimensional
Dimensional
Array
Array
1 D Array
int[ ] intArray = new int[ ]{ 1,2,3,4,5,6,7,8,9,10 };
Int[ ] Num={10, 20 , 30 ,40 };
Question: Write a Java program to compute the sum of all elements in a one-
dimensional array.
Find EVEN/ODD from array
Output
2D Array
public class multiDimensional {
// main function
public static void main(String args[])
{
int arr[][]= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
Write a Java program that multiplies two matrices of size 2x2.
String Class in Java
• Strings are used for storing [Link] is a sequence
of characters. But in java, string is an object that
represents a sequence of characters.
• String class is used to create string object.
A String variable contains a collection of characters
surrounded by double quotes
How to declare string in java -
String s=“MPGI College”;
Array of string -
S[0] S[1] S[2] S[3]
S Sneha Aman Dhruv Mayank
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Create object for string
• By string Literals
• By new keyword
By string Literals
• Java String literal is created by using double
quotes.
String s = “Java ”;
Using new keyword
String s = new String (“Java”);
String Method
• Java String charAt( )
• The Java String class charAt() method returns a char
value at the given index number.
Output J
int length It returns string length
Output
toUpperCase() : Convert the string in capital letters
toLowerCase() : Convert the string in lower case .
Output
equals() method is used to compare strings
String str = "one";
String st = "one"; [Link] ([Link](st));
String Types
Immutable Mutable
unmodifiable modifiable
or
unchangeable
Immutable String in Java
In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a
new string object is created.
Reference variable
s points to the "Sachin Tendulkar". Please
notice that still sachin object is not modified.
Why string objects are immutable in java?
• Suppose there are 5 reference variables, All refers to one object “s". If
one reference variable changes the value of the object, It will be affected
to all the reference variables. That is why string objects are immutable in
java.
String s=“JAVA”;
s=[Link](“OOPS”);
s=[Link](“Language”);
s=[Link](“JAVA1”);
String Buffer
StringBuffer class is used to create mutable (modifiable) strings.
The StringBuffer class in Java is the same as the String class
except it is mutable i.e. it can be changed
StringBuffer is a class in Java that represents a mutable
sequence of characters. It provides an alternative to the
immutable String class, allowing you to modify the contents of a
string without creating a new object every time.
Example
Output
Insert Method
HJavaello