OOP Through Java Unit - 1 - Updated
OOP Through Java Unit - 1 - Updated
UNIT I: Introduction to OOP, procedural programming language and object oriented language,
principles of OOP, applications of OOP, history of java, java features, JVM, program structure.
Variables, primitive data types, identifiers, literals, operators, expressions, precedence rules and
associativity, primitive type conversion and casting, flow of control.
Introduction to OOP
The major motivating factor in the invention of object-oriented approach is to remove
drawbacks of procedural oriented approach.
OOP treats data as critical element in the program development and does not allow it
freely to flow around the system or application or program.
OOP combines the data and methods(functions) into a single unit this process is called
encapsulation.
The organisation of data and Methods(functions) in object-oriented programming is
shown in the following diagram.
OOP allows divide a problem into a no of entities called as objects and then build data
and Methods(functions) around these objects.
The data of an object can be accessed only by the method(function) associated with that
object.
In OOP, method(function) of one object can access the method(function) of other objects.
1
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Disadvantages:
1. Large programs are divided into smaller programs known as functions. These functions can
call one another. Hence security is not provided.
2. No importance is given to security of data and importance is given to doing things.
3. Data move openly around the system from function to function.
4. Most functions accesses global data, what happens to the data is not known.
4 In POP large program is divided into In OOP entire program is divided into
functions. objects.
5 Global data is shared among the Data is shared among the objects
functions in the program. through the methods.
6 Instead of focusing on data, POP focuses OOP mainly focuses on data security
on method or procedure. instead of focusing on method or
procedure.
7 POP does not support access modifiers. OOP supports access modifiers.
S.No. C Java
1 C is Procedure Oriented Programming Java is an Object-Oriented Programming
language language.
3
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
5 In C In Java
6 In C format specifiers are required to read In Java format specifiers are optional or
and print the data. not required to print or read the data.
7 C uses “#include <stdio.h>” header file for Java uses “import java.io.*;” for the
input and output oprations. same purpose.
8 In C all variables are declared at the In Java all variables are declared
starting of the scope. anywhere in the scope.
11 In C, malloc() and calloc() Functions are In Java, new is used for Memory
used for Memory Allocation and free() Allocation and Deallocation is done by
function for memory Deallocating. the JVM.
17 C does not support Exception handling and Java supports Exception handling and
Event handling. Event handling.
4
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
S. No C++ Java
1 C++ was developed by Bjarne Stroustrup Java was developed by James Gosling
in 1979. in 1995.
2 C++ is not a purely object oriented Java is purely an object oriented
language, since it is possible to write C++ language, since it is not possible to write
programs without using a class or object. java programs without using
atleast one class.
3 It is platform dependent. It is platform independent.
4 Uses compiler only Uses compiler and interpreter
5 C++ uses cin for input and cout for an Java uses the (System
output operation. class): System.in for input
and System.out for output.
6 It doesn‟t support documentation It supports documentation comments
comments for source code. (e.g., /**.. */) for source code.
7 C++ supports goto keyword. Java doesn‟t support goto Keyword
8 C++ supports Structures and Unions. Java doesn‟t support Structures and
Unions.
9 It has 63 keywords It has 50 keywords
10 Supports Multiple inheritance in C++. Doesn‟t support multiple inheritance in
java, but we can achieve this by
interfaces.
11 There are constructors and destructors in Only constructors are available in Java.
C++.
12 It supports call by value and call by It supports call by value only
Reference
13 It supports both method and operator It supports only method overloading
overloading. and doesn‟t allow operator overloading.
14 It has Virtual Keyword It doesn‟t have Virtual Keyword.
15 It supports manual object management Automatic object management with
using new and delete. garbage collection.
16 Execution can be done by OS. Execution can be done by JVM.
17 C++ doesn't support >>> operator. Java supports >>> operator.
18 The extension of C++ program is “.cpp”. The extension of Java program is
5
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
“.java”
Basic Concepts (Key Concepts) / principles / features of Object-Oriented Programming:
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
It simplifies the software development and maintenance by providing some concepts like:
Class
Object
Encapsulation & Data hiding
Inheritance
Polymorphism
Abstraction
Message Passing
Class:
Class is an abstract data type (user defined data type) / non-primitive data type that contains
attributes and methods that operate on data. It starts with the keyword class.
(or)
Class is a blueprint or template for creating an object.
6
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Inheritance:
It is a process of using the properties of one class inside other class is known as inheritance.
The main aim of Inheritance is Reusability of the data and methods i.e. data and methods
declared in one class can be accessed by other class.
In Inheritance, two classes are involved (super class/base class/parent class and sub
class/derived class/child class).
The class which gives the properties is called as super class / base class / parent class.
The class which takes the properties and methods is called as sub-class/derived class /child
class.
Base Class
Derived Class
Polymorphism:
The word polymorphism is derived from two latin words poly(many) and morph (forms).
7
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Polymorphism means the ability to take many forms. Polymorphism allows to take different
implementations for same name.
Poly -> many
Morph -> forms
ism -> behaviours
There are two types of polymorphism, Compile time polymorphism and Run time
polymorphism.
In Compile time polymorphism binding is done at compile time and in runtime polymorphism
binding is done at runtime.
e.g.: Method Overloading and Method Overriding
Method Overloading:
Method overloading is used for compile time polymorphism.
Method Overriding:
Method overriding is used for runtime polymorphism
Abstraction:
It is a process of Hiding internal details and showing functionality is known as abstraction.
For example: Phone call, we don't know the internal processing.
Message Passing:
An object-oriented program contains a set of objects that communicate with one another. The
process of object-oriented programming contains the basic steps:
1. Creating classes
2. Creating objects
3. Establishing communication among objects
Example:
8
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Advantages of OOP:
Object oriented technology provides many advantages to the programmer and the user. This
technology solves many problems related to software development, provides improved quality and
low-cost software.
Applications of OOP:
History of java
1. Java is an Object-Oriented Programming language, High level, Case Sensitive and
General purpose programming language.
2. JAVA was developed by James Gosling and his team at Sun Microsystems Inc in the
year 1991, later acquired by Oracle Corporation.
3. James Gosling is known as the father of Java.
4. Before Java, it was called Oak and was developed as a part of the Green project. Since Oak
was already a registered company, so James Gosling and his team changed the name from
Oak to Java In 1995.
5. Java is an island in Indonesia where the first coffee was produced (called Java coffee). Java
name was chosen by James Gosling while having a cup of coffee nearby his office.
9
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
1. Simple: Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, and explicit memory allocation.
2. Object-Oriented: Java Supports OOP features like Class, Object, Encapsulation and Data
hiding, Abstraction, Inheritance, Polymorphism, Message Communication/ Message
Passing.
3. Portable: Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
4. Platform independent: Java code can be executed on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
5. Secured: Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
6. Robust: Java language is robust that means reliable.
The main features of java that make it robust are garbage collection, Exception Handling,
and memory allocation.
10
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
8. Compiled and Interpreted: Unlike other languages Java uses a system with both a
compiler and an interpreter for program execution. First, the compiler converts the program
code to bytecode which in turn is converted to machine code on any machine, using the
interpreter.
10. Multithreaded: A thread is like a separate program, executing concurrently. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web applications, etc.
11. Distributed: We can create distributed applications using the java programming language.
12. Dynamic: Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages, i.e., C
and C++.
Applications of Java:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
11
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Java Versions:
Many java versions have been released till now. The current stable release of Java is Java SE 10.
Note: Since Java SE 8 release, the Oracle corporation follows a pattern in which every even
version is release in March month and an odd version released in September month.
12
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
13
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
1)
Class Loader
The class loader is a subsystem used for loading class files. It performs three major functions -
Loading, Linking, and Initialization.
2) Method Area
In the method area, all class level information like class name, immediate parent class name,
methods and variables information etc. are stored, including static variables.
3) Heap
Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is
also a shared resource.
4) JVM language Stacks
Java language Stacks store local variables, and it‟s partial results.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing.
6) Native Method Stacks
It contains all the native methods used in the application.
7) Execution Engine
14
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
It contains:
Interpreter: It interprets the bytecode line by line and then executes.
Just-In-Time (JIT) compiler: It is used to increase the efficiency of an interpreter. It compiles
the entire bytecode and changes it to native code.
8) Native Method interface
It is an interface that interacts with the Native Method Libraries and provides the native libraries
(C, C++) required for the execution.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries (C, C++) which are needed by the Execution
Engine.
It is a class including a group of method declaration. It is used when multiple inheritances are
implementing
Class definition
Classes are defining to make the objects of real-world problem. The number of classes used
depends on complexity of the program
Main method class:
It is the starting point and essential part of java programming while executing. It creates object of
16
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Identifiers in Java
Identifiers in Java are symbolic names used for identification. They can be a class name, variable
name, method name, package name, constant name, and more.
Rules for Identifiers in Java
If the identifiers are not properly declared, we may get a compile-time error. Following are some
rules and conventions for declaring identifiers:
A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore
(_) or a dollar sign ($).
For example, @sample is not a valid identifier because it contains a special character
which is @.
There should not be any space in an identifier.
17
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Variables
A variable is a name given to a memory location that is used to store the value.
The value stored in a variable can be changed during program execution.
In Java, all the variables must be declared before use.
Variable Declaration:
Variable initialization:
}
}
18
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside any method,
constructor, or block.
As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
3. Static Variables
Static variables are also known as Class variables.
These variables are declared similarly as instance variables. The difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
Static variables are created at the start of program execution and destroyed automatically
when execution ends.
we can access the static variable like the Instance variable (through an object).
we can access the static variable with class name.
we can access the static variable without class name.
19
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example:
class Add{
static int a=10, b=20; // static variables
public static void main(String[] args){
}
}
Instance Variables:
Instance Variables are declared without static keyword.
They are specific to object i.e., for every object, separate memory will be allocated for
each instance Variable.
They can be accessed only by using the Object.
Static Variables:
Static Variables are declared with static keyword.
They are also called as “Class Variables”.
They are not specific to any object.
The memory for static Variables will be allocated whenever the class is loaded in to the
memory i.e., memory will be allocated only once which will be shared by all the objects of the
class.
Note:
Except Boolean and char all remaining data types are considered as signed data types because we
can represent both “+ve” and”-ve” numbers.
1. Primitive Data Types:
There are 8 primitive data types supported by Java.
Primitive data types are predefined by the language and named by a key word.
A. byte:
Size: 1 Byte (8 bits)
Max-value: +127
Min-value: -128
Range: -128 to 127 [-27 to 27 -1]
Example:
byte b=10;
byte data type is best suitable if we are handling data in terms of streams either from thefile or
from the network.
B. short:
Size: 2 Bytes
Range: -32768 to 32767 (-215 to 215 -1)
21
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example:
short s=130;
The most rarely used data type in java is short.
Short data type is best suitable for 16-bit processors like 8086 but these processors are
completely outdated and hence the corresponding short data type is also outdated data
type.
C. Int:
Size: 4 bytes
Range: -2147483648 to 2147483647 (-231 to 231 -1)
Example:
int i=130;
This is most commonly used data type in java.
D. long:
Size: 8 bytes
Range: -263 to 263 -1
Example:
long l= 13l;
To hold the no. Of characters present in a big file int may not enough hence the
return type of length() method is long.
long l=f.length() ; ►f is a file
Whenever int is not enough to hold big values then we should go for long data type.
E. Floating Point Data types:
float double
If we want to 5 to 6 decimal places of If we want to 14 to 15 decimal places
accuracy then we should go for float. of accuracy then we should go for
double.
Size: Size:
4 bytes 8 bytes
Range: Range:
-3.4e38 to 3.4e38 -1.7e308 to1.7e308.
22
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Literals in Java
Literal: Any constant value which can be assigned to the variable is called literal/constant.
Example:
23
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
5. Boolean Literals
6. Null Literals
1. Integral Literals
Integral literals are specified in four different ways, as follows:
Octal:
It has base eight and allows digits from 0 to 7. While assigning an octal literal in the Java code, a
number must have a prefix 0.
Hexadecimal:
It has base 16. Hexadecimal allows digits from 0 to 9, and characters from A to F. Even though
Java is case sensitive, and it also provides an exception for using either uppercase or lowercase
characters in the code for hexadecimal literals.
For example:
int x = 0X123Fadd;
int x = 0xFACE;
int x = 0xFace;
Binary:
It can be specified in binary literals, that is 0 and 1 with a prefix 0b or 0B.
For example: int x = 0b1011;
3. Char literals:
char ch=’a’;
24
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
4.String literals:
➤ Any sequence of characters with in double quotes is treated as String literal.
Example:
String s="Raghu"; ►Valid
5.Boolean literals:
➤ The only allowed values for the boolean type are true (or) false where case is important.
Example:
1. boolean b=true; ►valid
2. boolean b=0; ► Invalid ►C.E: incompatible types
3. boolean b=True; ► Invalid ►C.E: cannot find symbol True
4. b="true"; ► Invalid ►C.E: incompatible types
6.Null Literals
➤ Null literal in Java representing a null value.
Operators in Java
Operator in Java is a symbol that is used to perform operations on variables / operands /
constants.
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Unary Operators
7. Conditional Operator
8. Misc Operators
1. Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
25
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
The following table lists the arithmetic operators and Assume integer variable A holds 10 and
variable B holds 20, then
Example Output
public class Test { a + b = 30
public static void main(String args[]) {
a - b = -10
int a = 10;
int b = 20; a * b = 200
int c = 25; b/a=2
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b)); b%a=0
System.out.println("a * b = " + (a * b)); c%a=5
System.out.println("b / a = " + (b / a));
System.out.println("b % a = " + (b % a));
System.out.println("c % a = " + (c % a));
}
2. Relational Operators
Relational operators are used to check the relationship between two operands.
The following table lists the Relational operators and Assume integer variable A holds 10 and
variable B holds 20, then
26
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example
public class Test {
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
27
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
3. Bitwise Operators
Bitwise operators in Java are used to perform operations on individual bits.
The following table lists the bitwise operators and Assume integer variable A holds 60 and
variable B holds 13 then
28
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example:
public class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
29
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
4. Logical Operators:
Logical operators are used to check whether an expression is true or false. They are used in
decision making.
The following table lists the logical operators and Assume Boolean variables A holds true and
variable B holds false, then
Example: Output
public class Test {
a && b = false
public static void main(String args[]) {
a || b = true
boolean a = true;
!(a && b) = true
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b));
System.out.println(“! (a && b) = " +! (a && b));
}
}
30
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
5. Assignment Operators:
Assignment operators are used in Java to assign values to variables.
Following are the assignment operators supported by Java language.
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
Example:
public class Test {
c = a + b;
System.out.println("c = a + b = " + c);
c += a;
System.out.println("c += a = " + c);
c -= a; Output
System.out.println("c -= a = " + c);
c = a + b = 30
c *= a; c += a = 40
System.out.println("c *= a = " + c); c -= a = 30
c *= a = 300
a = 10; c /= a = 1
c = 15; c %= a = 5
c /= a;
System.out.println("c /= a = " + c);
a = 10;
c = 15;
c %= a;
System.out.println("c %= a = " + c);
}
}
31
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
6. Unary Operators
In Java, the unary operator is an operator that can be used only with an operand. It is used to
represent the positive or negative value, increment/decrement the value by 1, and
complement a Boolean value.
The following table describes the short description of the unary operators.
32
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
7. Conditional Operator:
The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first, we verify a condition, then we perform
one operation out of the two operations based on the condition result. If the condition is TRUE the
first option is performed, if the condition is FALSE the second option is performed.
Syntax:
Example:
public class ConditionalOperator {
c = (a>b)? a : b;
Output:
c = 20
8. Misc Operators
Instanceof operator:
The java instanceof operator is used to test whether the object is an instanceof the specified type
(class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the instance
with type. It returns either true or false. If we apply the instanceof operator with any variable that
has null value, it returns false.
Example:
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);
}
}
33
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Output:
true
Expressions in Java
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic
operations, logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a
direct value or variable or address of memory location.
Following are some of the examples for expressions in Java:
34
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Operator precedence determines which operator is performed first in an expression with more
than one operator with different precedence.
Example:
public class Precedence {
public static void main(String[] args) {
System.out.println(3 + 5 * 5);
System.out.println((3 + 5) * 5);
}
}
Output:
28
40
35
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Associativity:
Operators Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left.
For example: „*‟ and „/‟ have same precedence and their associativity is Left to Right
public class Precedence {
Output:
10
In the above expression, the operators / and * both belong to the same group in the operator
precedence table. So, we have to check the associativity rules for evaluating the above expression.
Associativity rule for / and * group is left-to-right i.e, evaluate the expression from left to right.
So, 10/5 is evaluated to 2 and then 2*5 is evaluated to 10.
36
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
2 Type conversion is only used with It can be used both compatible data type
compatible data types, and hence it and incompatible data type.
does not require any casting operator.
5 When converting one data type to When casting one data type to another,
another, the destination type should be the destination data type must be smaller
greater than the source data type. than the source data.
37
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
The control statements are used to control the order of execution according to our requirements.
Java provides several control statements, and they are classified as follows.
Types of Control Statements
In java, the control statements are classified as follows.
Selection Control Statements (Decision Making Statements)
Iterative Control Statements (Looping Statements)
Jump Statements
Selection Control Statements
In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based
on a condition. Java provides the following selection statements.
if statement
if-else statement
if-else-if ladder statement
nested if statement
switch statement
38
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
if statement
The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block
of statements is ignored.
Syntax:
if(condition){
//code to be executed
}
Example:
class IfStatement {
public static void main(String[] args) {
int number = 10;
if (number < 0) {
System.out.println("The number is negative.");
}
Output:
Statement outside if block
if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
class Main {
public static void main(String[] args) {
int number = 10;
if (number > 0)
System.out.println("The number is positive.");
else
System.out.println("The number is not positive.");
}
}
39
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Output:
The number is positive
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade
40
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
Output:
You are eligible to donate blood
41
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Switch Statement
The switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
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;
}
Example:
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
Output:
20
42
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
2. 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.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition is false.
The different types of iterative statements are:
For loop
While loop
Do-while loop
for-each loop
for loop:
For
for-each loop
The Java for-each statement was introduced since Java 5.0 version.
It provides an approach to traverse through an array or collection in Java.
The for-each statement executes the block of statements for each element of the given array or
collection.
Syntax:
43
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
For-each Loop
While
initialization
while (condition){
//code to be executed
Increment / decrement statement
}
Do-While
initialization
do{
//code to be executed / loop body
//update statement
}while (condition);
44
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Examples:
ForExample.java Output:
//Java Program to demonstrate the example of for loop 1
public class ForExample { 2
public static void main(String[] args) { 3
4
//Code of Java for loop 5
for(int i=1;i<=10;i++){ 6
7
System.out.println(i);
8
} 9
} 10
}
//Java Program to demonstrate the example of While loop
WhileExample.java
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
//Java Program to demonstrate the example of Do-While loop
DoWhileExample.java
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
45
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Infinite Loop:
ForExample.java o/p
//Java program to demonstrate the use of infinite for loop Infinite Loop
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
//Java program to demonstrate the use of infinite While loop
WhileExample.java
public class WhileExample2 {
public static void main(String[] args) {
// setting the infinite while loop by passing true to the condition
while(true){
System.out.println("infinitive loop");
}
}
}
//Java program to demonstrate the use of infinite Do-While loop
DoWhileExample2.java
public class DoWhileExample2 {
public static void main(String[] args) {
do{
System.out.println("infinitive loop");
}while(true);
}
}
46
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example: PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
*
**
***
****
*****
Example: ForEachExample.java
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
47
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line. The java programming language provides the following jump
statements.
break statement
continue statement
labelled break and continue statements
break statement
The break statement in java is used to terminate a switch or looping statement. That means the
break statement is used to come out of a switch statement and a looping statement like while, do-
while, for, and for-each.
Example:
public class JavaBreakStatement {
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
Output:
48
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
10
20
Continue Statement
The 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. In case of an inner loop, it
continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do- while
loop.
Example: ContinueExample.java
Output:
1
2
4
5
49
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Output:
11
12
13
21
50
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
51